userver: userver/utils/null_terminated_view.hpp Source File
Loading...
Searching...
No Matches
null_terminated_view.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/utils/null_terminated_view.hpp
4/// @brief @copybrief utils::NullTerminatedView
5/// @ingroup userver_universal
6
7#include <string>
8#include <string_view>
9#include <type_traits>
10
11#include <fmt/format.h>
12
13#include <userver/formats/serialize/to.hpp>
14#include <userver/utils/assert.hpp>
15
16USERVER_NAMESPACE_BEGIN
17
18namespace utils {
19
20/// @ingroup userver_containers
21///
22/// @brief Non-empty string view to a null terminated char array.
24public:
25 NullTerminatedView() = delete;
26
27 constexpr NullTerminatedView(const char* str) noexcept : std::string_view{str} {
28 // data()[size()] == '\0' is guaranteed by std::string_view that calls std::strlen(str)
29 }
30
31 NullTerminatedView(const std::string& str) noexcept : std::string_view{str} {}
32
33 constexpr const char* c_str() const noexcept { return data(); }
34
35 /// Constructs a NullTerminatedView from a pointer and size.
36 /// @warning `str[len]` should be '\0'.
37 static constexpr NullTerminatedView UnsafeMake(const char* str, std::size_t len) noexcept {
38 return NullTerminatedView{str, len};
39 }
40
41private:
42 constexpr NullTerminatedView(const char* str, std::size_t len) noexcept : std::string_view{str, len} {
43 UASSERT_MSG(str, "null not allowed");
44 UASSERT_MSG(str[len] == '\0', "Not null terminated");
45 }
46};
47
48template <class Value>
49Value Serialize(NullTerminatedView view, formats::serialize::To<Value>) {
50 return typename Value::Builder(std::string_view{view}).ExtractValue();
51}
52
53} // namespace utils
54
55USERVER_NAMESPACE_END
56
57template <>
58struct fmt::formatter<USERVER_NAMESPACE::utils::NullTerminatedView, char> : fmt::formatter<std::string_view> {};