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/compiler/impl/constexpr.hpp>
14#include <userver/formats/serialize/to.hpp>
15#include <userver/utils/zstring_view.hpp>
16
17USERVER_NAMESPACE_BEGIN
18
19namespace 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"`.
27public:
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
50private:
51 explicit constexpr StringLiteral(const char* str, std::size_t len) noexcept
53};
54
55template <class Value>
56Value Serialize(StringLiteral literal, formats::serialize::To<Value>) {
57 return typename Value::Builder(std::string_view{literal}).ExtractValue();
58}
59
60} // namespace utils
61
62USERVER_NAMESPACE_END
63
64template <>
65struct fmt::formatter<USERVER_NAMESPACE::utils::StringLiteral, char> : fmt::formatter<std::string_view> {};