summaryrefslogtreecommitdiff
path: root/icespider/common/maybeString.h
blob: b76da2f67d2fa11b3568e4261f2adcb3f8e8643c (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
#pragma once

#include <iosfwd>
#include <string>
#include <string_view>
#include <utility>
#include <variant>

namespace IceSpider {
	class MaybeString {
	public:
		MaybeString() = default;

		// cppcheck-suppress noExplicitConstructor; NOLINTNEXTLINE(hicpp-explicit-conversions)
		MaybeString(std::string str) : valueContainer {std::move(str)} { }

		// cppcheck-suppress noExplicitConstructor; NOLINTNEXTLINE(hicpp-explicit-conversions)
		MaybeString(std::string_view str) : valueContainer {str} { }

		// NOLINTNEXTLINE(hicpp-explicit-conversions)
		[[nodiscard]] operator std::string_view() const
		{
			if (valueContainer.index() == 0) {
				return std::get<0>(valueContainer);
			}
			return std::get<1>(valueContainer);
		}

		[[nodiscard]] std::string_view
		value() const
		{
			return *this;
		}

		[[nodiscard]] bool
		isString() const
		{
			return valueContainer.index() > 0;
		}

		[[nodiscard]] bool
		operator<(const MaybeString & other) const
		{
			return value() < other.value();
		}

		[[nodiscard]] bool
		operator<(const std::string_view other) const
		{
			return value() < other;
		}

	private:
		using ValueType = std::variant<std::string_view, std::string>;
		ValueType valueContainer;
	};
};

namespace std {
	inline std::ostream &
	operator<<(std::ostream & strm, const IceSpider::MaybeString & value)
	{
		return strm << value.value();
	}
}