#include #include #include #include #include #include #include #include #include #include #include #include #include namespace kapi::devices { namespace { constinit auto static registry = std::optional{}; } auto interface_registry::init() -> void { if (registry.has_value()) { system::panic("[kernel] Device interface registry has already been initialized."); } registry.emplace(); } auto interface_registry::get() -> interface_registry & { if (!registry) { system::panic("[kernel] Device interface registry has not been initialized."); } return *registry; } auto interface_registry::do_publish(kstd::shared_ptr device, kstd::string name, interface interface, void * implementation) -> kstd::result { erase_if(m_entries, [interface](auto e) { return e.interface() == interface && !e.device(); }); if (!device || !implementation || name.empty()) { return kstd::failure(make_error_code(kstd::errc::invalid_argument)); } auto published = std::ranges::any_of(m_entries, [&](auto const & entry) { return entry.interface() == interface && entry.device().get() == device.get(); }); if (published) { return kstd::failure(make_error_code(kstd::errc::file_exists)); } m_entries.emplace_back(device, std::move(name), interface, implementation); return kstd::success(); } auto interface_registry::unpublish(device const & device, interface interface) -> void { erase_if(m_entries, [&](auto e) { auto locked_device = e.device(); return e.interface() == interface && locked_device && locked_device.get() == &device; }); } auto interface_registry::all(interface interface) const -> kstd::vector { auto filtered = m_entries; erase_if(filtered, [&](auto e) { auto locked_device = e.device(); return !(e.interface() == interface && locked_device); }); return filtered; } auto interface_registry::resolve(interface interface, std::string_view name) -> void * { auto found = std::ranges::find_if(m_entries, [&](auto e) { return e.name() == name && e.device(); }); if (found == m_entries.cend()) { return nullptr; } else if (auto device = found->device()) { return resolve(interface, *device); } return nullptr; } auto interface_registry::resolve(interface interface, device & device) -> void * { if (auto by_device = device.as(interface)) { return by_device; } auto found = std::ranges::find_if(m_entries, [&](auto e) { auto locked_device = e.device(); return e.interface() == interface && locked_device && locked_device.get() == &device; }); if (found == m_entries.cend()) { return nullptr; } return found->implementation(); } } // namespace kapi::devices namespace kapi::test_support::devices { auto deinit_interface_registry() -> void { kapi::devices::registry.reset(); } } // namespace kapi::test_support::devices