diff options
Diffstat (limited to 'kernel/kapi/devices/device_registry.cpp')
| -rw-r--r-- | kernel/kapi/devices/device_registry.cpp | 106 |
1 files changed, 106 insertions, 0 deletions
diff --git a/kernel/kapi/devices/device_registry.cpp b/kernel/kapi/devices/device_registry.cpp new file mode 100644 index 00000000..aca0e7fe --- /dev/null +++ b/kernel/kapi/devices/device_registry.cpp @@ -0,0 +1,106 @@ +#include <kapi/devices/device_registry.hpp> + +#include <kapi/devices/device.hpp> +#include <kapi/system.hpp> + +#include <kstd/memory.hpp> +#include <kstd/print.hpp> +#include <kstd/string.hpp> +#include <kstd/vector.hpp> + +#include <optional> +#include <string_view> +#include <utility> + +namespace kapi::devices +{ + + namespace + { + auto constinit instance = std::optional<device_registry>{}; + } + + auto device_registry::init() -> void + { + if (instance) + { + system::panic("[OS:DEV] Device registry has already been initialized"); + } + + instance = device_registry{}; + } + + auto device_registry::get() -> device_registry & + { + if (!instance) + { + system::panic("[OS:DEV] Device registry has not been initialized"); + } + + return *instance; + } + + auto device_registry::add(kstd::shared_ptr<device> device) -> bool + { + if (!device) + { + return false; + } + + kstd::println("[OS:DEV] Registering device {}", device->name()); + + auto found = m_devices.find(device->name()); + if (found != m_devices.end()) + { + if (!found->second.expired()) + { + return false; + } + + found->second = device; + return true; + } + + return m_devices.emplace(device->name(), device).second; + } + + auto device_registry::remove(device &) -> bool + { + kstd::println("[OS:DEV] TODO: implement device deregistration"); + return false; + } + + auto device_registry::find(std::string_view name) const -> kstd::shared_ptr<device> + { + auto found = m_devices.find(kstd::string{name}); + if (found == m_devices.end()) + { + return nullptr; + } + + return found->second.lock(); + } + + auto device_registry::all() const -> kstd::vector<kstd::shared_ptr<device>> + { + auto result = kstd::vector<kstd::shared_ptr<device>>{}; + + for (auto const & [name, weak_device] : m_devices) + { + if (auto device = weak_device.lock()) + { + result.push_back(std::move(device)); + } + } + + return result; + } +} // namespace kapi::devices + +namespace kapi::test_support::devices +{ + auto deinit_device_registry() -> void + { + kapi::devices::instance.reset(); + } +} // namespace kapi::test_support::devices
\ No newline at end of file |
