userver: userver/utils/string_literal.hpp Source File
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages Concepts
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/assert.hpp>
16#include <userver/utils/null_terminated_view.hpp>
17
18USERVER_NAMESPACE_BEGIN
19
20namespace utils {
21
22/// @ingroup userver_containers
23///
24/// @brief Non-empty string view to a compile time known null terminated char array that lives for the lifetime of
25/// program, as per [lex.string]; a drop-in replacement for `static const std::string kVar = "value"` and
26/// `constexpr std::string_view kVar = "value"`.
28public:
29 StringLiteral() = delete;
30
31#if defined(__clang__) && __clang_major__ < 18
32 // clang-16 and below lose (optimize out) the pointer to `literal` with consteval. Clang-18 is know to work
33 constexpr
34#else
35 USERVER_IMPL_CONSTEVAL
36#endif
37 StringLiteral(const char* literal) noexcept
38 : NullTerminatedView{literal} {
39 // data()[size()] == '\0' is guaranteed by std::string_view that calls std::strlen(literal)
40 }
41
42 /// Constructs a StringLiteral from a pointer and size.
43 /// @warning `str[len]` should be '\0' and `str` should point to compile time literal.
44 static constexpr StringLiteral UnsafeMake(const char* str, std::size_t len) noexcept {
45 return StringLiteral(str, len);
46 }
47
48private:
49 explicit constexpr StringLiteral(const char* str, std::size_t len) noexcept
51};
52
53template <class Value>
54Value Serialize(StringLiteral literal, formats::serialize::To<Value>) {
55 return typename Value::Builder(std::string_view{literal}).ExtractValue();
56}
57
58} // namespace utils
59
60USERVER_NAMESPACE_END
61
62template <>
63struct fmt::formatter<USERVER_NAMESPACE::utils::StringLiteral, char> : fmt::formatter<std::string_view> {};