-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsize_prefixed_string_literal.hh
97 lines (72 loc) · 2.37 KB
/
size_prefixed_string_literal.hh
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
// Copyright (c) 2022 Mikael Simonsson <https://mikaelsimonsson.com>.
// SPDX-License-Identifier: BSL-1.0
// # Size prefixed string literal
#pragma once
#include "snn-core/array_view.hh"
#include "snn-core/range/contiguous.hh"
namespace snn
{
// ## Classes
// ### size_prefixed_string_literal
class size_prefixed_string_literal final
{
public:
// #### Converting constructors
template <same_as<const char> ConstChar, usize N>
requires(N >= 2 && N <= 257) // 0-255 (not counting size prefix char + trailing '\0').
consteval size_prefixed_string_literal(ConstChar (&s)[N]) noexcept
: string_{s}
{
snn_should(size_() == N - 2);
}
// #### Implicit conversion operators
constexpr operator cstrview() const noexcept
{
return view();
}
// #### Range
[[nodiscard]] constexpr cstrrng range() const noexcept
{
return cstrrng{view()}; // Convert from view to skip nullptr check.
}
// #### View
[[nodiscard]] constexpr cstrview view() const noexcept
{
return cstrview{not_null{data_()}, size_()};
}
// #### Comparison operators
// Compare with another `size_prefixed_string_literal`. Implicit conversion disabled.
constexpr bool operator==(
const same_as<size_prefixed_string_literal> auto other) const noexcept
{
return view() == other.view();
}
constexpr auto operator<=>(
const same_as<size_prefixed_string_literal> auto other) const noexcept
{
return view() <=> other.view();
}
// Compare with a string.
constexpr bool operator==(const transient<cstrview> s) const noexcept
{
return view() == s.get();
}
constexpr auto operator<=>(const transient<cstrview> s) const noexcept
{
return view() <=> s.get();
}
private:
const char* string_;
SNN_DIAGNOSTIC_PUSH
SNN_DIAGNOSTIC_IGNORE_UNSAFE_BUFFER_USAGE
constexpr const char* data_() const noexcept
{
return &string_[1];
}
constexpr usize size_() const noexcept
{
return usize{to_byte(string_[0])};
}
SNN_DIAGNOSTIC_POP
};
}