open_file_map.hpp 1.36 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
};

Tommaso Tocci's avatar
Tommaso Tocci committed
enum file_type {
    regular,
    directory
};

Marc Vef's avatar
Marc Vef committed
class OpenFile {
Tommaso Tocci's avatar
Tommaso Tocci committed
protected:
    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_;
    std::recursive_mutex files_mutex_;
Marc Vef's avatar
Marc Vef committed

    int safe_generate_fd_idx_();
Marc Vef's avatar
Marc Vef committed

public:
    OpenFileMap();

    std::shared_ptr<OpenFile> get(int fd);
    bool exist(int fd);

    int add(std::shared_ptr<OpenFile>);
    
    bool remove(int fd);
Marc Vef's avatar
Marc Vef committed

    int dup(int oldfd);

    int dup2(int oldfd, int newfd);

Marc Vef's avatar
Marc Vef committed
};


#endif //IFS_OPEN_FILE_MAP_HPP