userver
C++ Async Framework
Loading...
Searching...
No Matches
string_literal.hpp
Go to the documentation of this file.
1
#
pragma
once
2
3
/// @file userver/utils/string_literal.hpp
4
/// @brief @copybrief utils::StringLiteral
5
/// @ingroup userver_universal
6
7
#
include
<
string
>
8
#
include
<
string_view
>
9
#
include
<
type_traits
>
10
11
#
include
<
fmt
/
core
.
h
>
12
13
#
include
<
userver
/
formats
/
serialize
/
to
.
hpp
>
14
#
include
<
userver
/
utils
/
zstring_view
.
hpp
>
15
16
USERVER_NAMESPACE_BEGIN
17
18
namespace
utils
{
19
20
/// @ingroup userver_containers
21
///
22
/// @brief Non-empty string view to a compile time known null terminated char array that lives for the lifetime of
23
/// program, as per [lex.string]; a drop-in replacement for `static const std::string kVar = "value"` and
24
/// `constexpr std::string_view kVar = "value"`.
25
class
StringLiteral
:
public
zstring_view
{
26
public
:
27
StringLiteral() =
delete
;
28
29
#
if
defined
(
__clang__
)
&&
__clang_major__
<
18
30
// clang-16 and below lose (optimize out) the pointer to `literal` with consteval. Clang-18 is know to work
31
constexpr
32
#
else
33
consteval
34
#
endif
35
StringLiteral(
const
char
* literal)
noexcept
36
:
zstring_view
{literal} {
37
// data()[size()] == '\0' is guaranteed by std::string_view that calls std::strlen(literal)
38
}
39
40
void
swap(
zstring_view
&) =
delete
;
// loses guarantee on lifetime because zstring_view may refer to non-literal
41
void
swap(
StringLiteral
& other)
noexcept
{
zstring_view
::swap(other); }
42
43
/// Constructs a StringLiteral from a pointer and size.
44
/// @warning `str[len]` should be '\0' and `str` should point to compile time literal.
45
static
constexpr
StringLiteral
UnsafeMake
(
const
char
* str, std::size_t len)
noexcept
{
46
return
StringLiteral
(str, len);
47
}
48
49
private
:
50
explicit
constexpr
StringLiteral(
const
char
* str, std::size_t len)
noexcept
51
:
zstring_view
{
zstring_view
::
UnsafeMake
(
str
,
len
)
} {}
52
};
53
54
template
<
class
Value>
55
Value Serialize(
StringLiteral
literal, formats::
serialize
::To<Value>) {
56
return
typename
Value::Builder(std::string_view{literal}).ExtractValue();
57
}
58
59
}
// namespace utils
60
61
USERVER_NAMESPACE_END
62
63
template
<>
64
struct
fmt::formatter<USERVER_NAMESPACE::
utils
::
StringLiteral
,
char
> : fmt::formatter<std::string_view> {};
userver
utils
string_literal.hpp
Generated on Thu Apr 16 2026 13:30:00 for userver by
Doxygen
1.13.2