aboutsummaryrefslogtreecommitdiffstats
path: root/nihil.config/store.cc
blob: 06c2035b7631f929104590d4c8aaa286d660e761 (plain) (blame)
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
// This source code is released into the public domain.
module nihil.config;

import nihil.std;
import nihil.core;

namespace nihil::config {

store::store() = default;

auto store::get() -> store &
{
	static auto instance = store();
	return instance;
}


auto store::register_option(this store &self, option *object)
	-> std::expected<void, error>
{
	auto [it, okay] = self.m_options.insert(
				std::pair{object->name(), object});

	if (okay)
		return {};

	return std::unexpected(error(std::format(
			"attempt to register duplicate "
			"configuration option '{0}'",
			object->name())));
}

auto store::unregister_option(this store &self, option *object)
	-> std::expected<void, error>
{
	auto it = self.m_options.find(object->name());
	if (it == self.m_options.end())
		return std::unexpected(error(std::format(
			"attempt to unregister non-existent "
			"configuration option '{}'",
			object->name())));

	self.m_options.erase(it);
	return {};
}

auto store::fetch(this store const &self, std::string_view name)
	-> std::expected<option const *, error>
{
	if (auto it = self.m_options.find(name); it != self.m_options.end())
		return it->second;

	return std::unexpected(error(std::format(
		"unknown configuration option '{}'",
		name)));
}

auto store::fetch(this store &self, std::string_view name)
	-> std::expected<option *, error>
{
	auto opt = co_await static_cast<store const &>(self).fetch(name);
	co_return const_cast<option *>(opt);
}

auto store::all(this store const &self) -> nihil::generator<option const *>
{
	for (auto &&it : self.m_options)
		co_yield it.second;
}

auto store::all(this store &self) -> nihil::generator<option *>
{
	for (auto &&it : self.m_options)
		co_yield it.second;
}

auto get_option(std::string_view option_name)
	-> std::expected<option *, error>
{
	co_return co_await store::get().fetch(option_name);
}

} // namespace nihil::config