open_file_map.hpp 1.19 KiB
Newer Older
Marc Vef's avatar
Marc Vef committed

#ifndef IFS_OPEN_FILE_MAP_HPP
#define IFS_OPEN_FILE_MAP_HPP

#include <map>
#include <mutex>
#include <memory>
Marc Vef's avatar
Marc Vef committed

enum class OpenFile_flags {
    append = 0,
    creat,
    trunc,
    rdonly,
    wronly,
    rdwr,
    flag_count // this is purely used as a size variable of this enum class
};

Marc Vef's avatar
Marc Vef committed
class OpenFile {
private:
    std::array<bool, static_cast<int>(OpenFile_flags::flag_count)> flags_ = {false};
    off64_t pos_;
    std::mutex pos_mutex_;
    std::mutex flag_mutex_;
Marc Vef's avatar
Marc Vef committed

public:
    // multiple threads may want to update the file position if fd has been duplicated by dup()
    OpenFile(const std::string& path, int flags);
Marc Vef's avatar
Marc Vef committed

    // getter/setter
    std::string path() const;
Marc Vef's avatar
Marc Vef committed

    void path(const std::string& path_);
Marc Vef's avatar
Marc Vef committed

    off64_t pos();
Nafi3's avatar
Nafi3 committed

    void pos(off64_t pos_);
Nafi3's avatar
Nafi3 committed

    const bool get_flag(OpenFile_flags flag);
    void set_flag(OpenFile_flags flag, bool value);
Marc Vef's avatar
Marc Vef committed
};


class OpenFileMap {

private:
    std::map<int, std::shared_ptr<OpenFile>> files_;
Marc Vef's avatar
Marc Vef committed
    std::mutex files_mutex_;


public:
    OpenFileMap();

    OpenFile* get(int fd);
    bool exist(int fd);

    int add(std::string path, int flags);

    bool remove(int fd);
Marc Vef's avatar
Marc Vef committed

};


#endif //IFS_OPEN_FILE_MAP_HPP