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
36 static constexpr auto npos = std::numeric_limits<size_type>::max();
37
38 constexpr basic_string_literal(const character_type (&data)[Size]) noexcept {
39 detail::copy(data, data + Size - 1, _data.data());
40 }
41
42 constexpr auto begin() const noexcept -> iterator {
43 return std::begin(_data);
44 }
45
46 constexpr auto end() const noexcept -> iterator {
47 return std::end(_data.data());
48 }
49
50 constexpr auto data() const noexcept -> const character_type* {
51 return _data.data();
52 }
53
54 constexpr auto size() const noexcept -> size_type {
55 return Size - 1;
56 }
57
58 constexpr auto is_empty() const noexcept -> bool {
59 return size() == 0;
60 }
61
62 constexpr auto operator[](size_type index) const noexcept -> character_type {
63 return _data[index];
64 }
65
66 constexpr operator string_view_type() const noexcept {
67 return string_view_type{_data.data(), Size};
68 }
69
70 std::array<character_type, Size - 1> _data;
71
72}; // class basic_string_literal
73
74template<std::size_t Size>
76
77template<std::size_t Size>
79
80} // namespace sbx::utility
81
82template<std::size_t Size>
83struct fmt::formatter<sbx::utility::string_literal<Size>> {
84
85 template<typename ParseContext>
86 constexpr auto parse(ParseContext& context) -> decltype(context.begin()) {
87 return context.begin();
88 }
89
90 template<typename FormatContext>
91 auto format(const sbx::utility::string_literal<Size>& value, FormatContext& context) -> decltype(context.out()) {
92 return fmt::format_to(context.out(), "{}", fmt::join(value._data, ""));
93 }
94
95}; // struct fmt::formatter<sbx::utility::primitive<Type>>
96
97#endif // LIBSBX_UTILITY_STRING_LITERAL_HPP_
Definition: string_literal.hpp:27