sandbox
Loading...
Searching...
No Matches
string_literal.hpp
1#ifndef LIBSBX_UTILITY_STRING_LITERAL_HPP_
2#define LIBSBX_UTILITY_STRING_LITERAL_HPP_
3
4#include <utility>
5#include <string_view>
6#include <array>
7#include <limits>
8
9#include <fmt/format.h>
10
11namespace sbx::utility {
12
13namespace detail {
14
15template<std::forward_iterator InputIterator, std::sentinel_for<InputIterator> Sentinel, std::forward_iterator OutputIterator>
16constexpr auto copy(InputIterator first, Sentinel last, OutputIterator result) -> OutputIterator {
17 while (first != last) {
18 *result++ = *first++;
19 }
20
21 return result;
22}
23
24} // namespace detail
25
26template<typename Character, std::size_t Size>
28
29public:
30
31 using character_type = Character;
32 using size_type = std::size_t;
33 using iterator = const character_type*;
34 using string_view_type = std::basic_string_view<character_type>;
35 using string_type = std::basic_string<character_type>;
36
37 static constexpr auto npos = std::numeric_limits<size_type>::max();
38
39 constexpr basic_string_literal(const character_type (&data)[Size]) noexcept {
40 detail::copy(data, data + Size - 1, _data.data());
41 }
42
43 constexpr auto begin() const noexcept -> iterator {
44 return std::begin(_data);
45 }
46
47 constexpr auto end() const noexcept -> iterator {
48 return std::end(_data.data());
49 }
50
51 constexpr auto data() const noexcept -> const character_type* {
52 return _data.data();
53 }
54
55 constexpr auto size() const noexcept -> size_type {
56 return Size - 1;
57 }
58
59 constexpr auto is_empty() const noexcept -> bool {
60 return size() == 0;
61 }
62
63 constexpr auto operator[](size_type index) const noexcept -> character_type {
64 return _data[index];
65 }
66
67 constexpr operator string_view_type() const noexcept {
68 return string_view_type{_data.data(), Size};
69 }
70
71 constexpr operator string_type() const noexcept {
72 return (Size != 0u) ? string_type{_data.data(), Size} : std::string{};
73 }
74
75 std::array<character_type, Size - 1> _data;
76
77}; // class basic_string_literal
78
79template<std::size_t Size>
81
82template<std::size_t Size>
84
85} // namespace sbx::utility
86
87template<std::size_t Size>
88struct fmt::formatter<sbx::utility::string_literal<Size>> {
89
90 template<typename ParseContext>
91 constexpr auto parse(ParseContext& context) -> decltype(context.begin()) {
92 return context.begin();
93 }
94
95 template<typename FormatContext>
96 auto format(const sbx::utility::string_literal<Size>& value, FormatContext& context) -> decltype(context.out()) {
97 return fmt::format_to(context.out(), "{}", std::string{value.data(), value.size()});
98 }
99
100}; // struct fmt::formatter<sbx::utility::primitive<Type>>
101
102#endif // LIBSBX_UTILITY_STRING_LITERAL_HPP_
Definition: string_literal.hpp:27