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

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

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

		// cppcheck-suppress noExplicitConstructor; NOLINTNEXTLINE(hicpp-explicit-conversions)
		inline MaybeString(std::string s) : value_ {std::move(s)} { }

		// cppcheck-suppress noExplicitConstructor; NOLINTNEXTLINE(hicpp-explicit-conversions)
		inline MaybeString(std::string_view s) : value_ {s} { }

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

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

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

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

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

	private:
		using value_type = std::variant<std::string_view, std::string>;
		value_type value_;
	};
};

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