userver: userver/utils/string_literal.hpp Source File
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
16USERVER_NAMESPACE_BEGIN
17
18namespace 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"`.
26public:
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
49private:
50 explicit constexpr StringLiteral(const char* str, std::size_t len) noexcept
52};
53
54template <class Value>
55Value Serialize(StringLiteral literal, formats::serialize::To<Value>) {
56 return typename Value::Builder(std::string_view{literal}).ExtractValue();
57}
58
59} // namespace utils
60
61USERVER_NAMESPACE_END
62
63template <>
64struct fmt::formatter<USERVER_NAMESPACE::utils::StringLiteral, char> : fmt::formatter<std::string_view> {};