#include "filesystem/file_descriptor_table.hpp" #include "kapi/system.hpp" #include "filesystem/open_file_description.hpp" #include #include #include namespace filesystem { namespace { constinit auto static global_file_descriptor_table = std::optional{}; } // namespace auto file_descriptor_table::init() -> void { if (global_file_descriptor_table) { kapi::system::panic("[FILESYSTEM] File descriptor table has already been initialized."); } global_file_descriptor_table.emplace(file_descriptor_table{}); } auto file_descriptor_table::get() -> file_descriptor_table & { if (!global_file_descriptor_table) { kapi::system::panic("[FILESYSTEM] File descriptor table has not been initialized."); } return *global_file_descriptor_table; } auto file_descriptor_table::add_file(open_file_description & file_description) -> int { auto it = std::ranges::find_if(m_open_files, [](auto & open_file) { return !open_file.has_value(); }); if (it != m_open_files.end()) { *it = file_description; return static_cast(it - m_open_files.begin()); } return -1; } auto file_descriptor_table::get_file(int fd) const -> std::optional { if (fd < 0) { return std::nullopt; } auto const index = static_cast(fd); if (index >= m_open_files.size() || !m_open_files[index].has_value()) { return std::nullopt; } return *m_open_files[index]; } auto file_descriptor_table::remove_file(int fd) -> void { if (fd < 0) { return; } auto const index = static_cast(fd); if (index >= m_open_files.size()) { return; } m_open_files[index].reset(); } } // namespace filesystem