#include "kernel/filesystem/file_descriptor_table.hpp" #include "kapi/system.hpp" #include "kernel/filesystem/open_file_description.hpp" #include #include #include #include namespace { constinit auto static global_file_descriptor_table = std::optional{}; } // namespace namespace kernel::filesystem { 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(kstd::shared_ptr const & file_description) -> int { if (!file_description) { // TODO BA-FS26 panic or errorcode? return -1; } auto it = std::ranges::find_if(m_open_files, [](auto const & open_file) { return open_file == nullptr; }); if (it != m_open_files.end()) { *it = file_description; return static_cast(it - m_open_files.begin()); } m_open_files.push_back(file_description); return static_cast(m_open_files.size() - 1); } auto file_descriptor_table::get_file(int fd) const -> kstd::shared_ptr { if (fd < 0) { return nullptr; } auto const index = static_cast(fd); if (index >= m_open_files.size()) { return nullptr; } return m_open_files.at(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.at(index) = nullptr; } } // namespace kernel::filesystem namespace kernel::tests::filesystem::file_descriptor_table { auto deinit() -> void { global_file_descriptor_table.reset(); } } // namespace kernel::tests::filesystem::file_descriptor_table