aboutsummaryrefslogtreecommitdiff
path: root/kernel/kapi/devices/device_registry.cpp
blob: aca0e7fe7326e4ad88215f5cb1c817d3d757a93e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
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