aboutsummaryrefslogtreecommitdiffstats
path: root/nihil.config/string.ccm
blob: 8a114d2298b08621e5d99543e43fb6beef918ead (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
// This source code is released into the public domain.
export module nihil.config:string;

import nihil.std;
import nihil.core;
import nihil.ucl;

import :option;

namespace nihil::config {

// A string option.  The backing type is std::string.
export struct string final : option
{
	string(std::string &storage, std::string_view const name,
	       std::string_view const description) noexcept
		: option(name, description)
		, m_storage(storage)
	{
	}

	~string() override = default;

	// Not copyable.
	string(string const &) = delete;
	auto operator=(string const &) -> string & = delete;

	// Not movable.
	string(string &&) = delete;
	auto operator=(string &&) -> string & = delete;

private:
	// Get this option as a string; simply returns the storage.
	[[nodiscard]] auto get_string() const -> std::string override
	{
		return m_storage;
	}

	// Set this option to a string value; assigns to the storage.
	[[nodiscard]] auto
	set_string(std::string_view const new_value) -> std::expected<void, error> override
	{
		m_storage = new_value;
		return {};
	}

	// Convert this option to a UCL object.
	[[nodiscard]] auto get_ucl() const -> std::expected<ucl::object, error> override
	{
		return ucl::make_string(m_storage);
	}

	// Set this option from a UCL object.
	[[nodiscard]] auto set_ucl(ucl::object const &uclobj) -> std::expected<void, error> override
	{
		auto obj = co_await object_cast<ucl::string>(uclobj).transform_error(
			[&](ucl::type_mismatch const &m) {
				return error(std::format("'{}': expected string, not {}", name(),
			                                 str(m.actual_type())));
			});

		m_storage = obj.value();
		is_default(false);
		co_return {};
	}

	std::string &m_storage;
};

} // namespace nihil::config