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
/
compiler
/
impl
/
constexpr
.
hpp
>
14
#
include
<
userver
/
formats
/
serialize
/
to
.
hpp
>
15
#
include
<
userver
/
utils
/
zstring_view
.
hpp
>
16
17
USERVER_NAMESPACE_BEGIN
18
19
namespace
utils {
20
21
/// @ingroup userver_containers
22
///
23
/// @brief Non-empty string view to a compile time known null terminated char array that lives for the lifetime of
24
/// program, as per [lex.string]; a drop-in replacement for `static const std::string kVar = "value"` and
25
/// `constexpr std::string_view kVar = "value"`.
26
class
StringLiteral
:
public
zstring_view
{
27
public
:
28
StringLiteral() =
delete
;
29
30
#
if
defined
(
__clang__
)
&&
__clang_major__
<
18
31
// clang-16 and below lose (optimize out) the pointer to `literal` with consteval. Clang-18 is know to work
32
constexpr
33
#
else
34
USERVER_IMPL_CONSTEVAL
35
#
endif
36
StringLiteral(
const
char
* literal)
noexcept
37
:
zstring_view
{literal} {
38
// data()[size()] == '\0' is guaranteed by std::string_view that calls std::strlen(literal)
39
}
40
41
void
swap(
zstring_view
&) =
delete
;
// loses guarantee on lifetime because zstring_view may refer to non-literal
42
void
swap(
StringLiteral
& other)
noexcept
{
zstring_view
::swap(other); }
43
44
/// Constructs a StringLiteral from a pointer and size.
45
/// @warning `str[len]` should be '\0' and `str` should point to compile time literal.
46
static
constexpr
StringLiteral
UnsafeMake
(
const
char
* str, std::size_t len)
noexcept
{
47
return
StringLiteral
(str, len);
48
}
49
50
private
:
51
explicit
constexpr
StringLiteral(
const
char
* str, std::size_t len)
noexcept
52
:
zstring_view
{
zstring_view
::
UnsafeMake
(
str
,
len
)
} {}
53
};
54
55
template
<
class
Value>
56
Value Serialize(
StringLiteral
literal,
formats
::
serialize
::
To
<Value>) {
57
return
typename
Value::Builder(std::string_view{literal}).ExtractValue();
58
}
59
60
}
// namespace utils
61
62
USERVER_NAMESPACE_END
63
64
template
<>
65
struct
fmt::formatter<USERVER_NAMESPACE::utils::
StringLiteral
,
char
> : fmt::formatter<std::string_view> {};
userver
utils
string_literal.hpp
Generated on Wed Dec 24 2025 09:55:15 for userver by
Doxygen
1.9.8