commons 0.1.5
Header-only C++23 library of common/shared types for the C++ libraries
Loading...
Searching...
No Matches
fixed_string.hpp
Go to the documentation of this file.
1#pragma once
2
6
7#include <cstddef>
8#include <string_view>
9
10namespace comms {
11
20template <std::size_t N>
22 // NOLINTBEGIN(cppcoreguidelines-avoid-c-arrays,modernize-avoid-c-arrays,google-explicit-constructor,hicpp-explicit-conversions)
23 char value[N]{};
24
28 constexpr FixedString() noexcept = default;
29
31 constexpr FixedString(const char (&str)[N]) noexcept {
32 for (std::size_t i = 0; i < N; ++i) {
33 value[i] = str[i];
34 }
35 }
36
37 [[nodiscard]] constexpr std::string_view view() const noexcept {
38 return std::string_view{static_cast<const char*>(value), N - 1};
39 }
40
41 [[nodiscard]] constexpr operator std::string_view() const noexcept {
42 return view();
43 }
44 // NOLINTEND(cppcoreguidelines-avoid-c-arrays,modernize-avoid-c-arrays,google-explicit-constructor,hicpp-explicit-conversions)
45
46 [[nodiscard]] static constexpr std::size_t size() noexcept {
47 return N - 1;
48 }
49
50 [[nodiscard]] static constexpr bool empty() noexcept {
51 return N <= 1;
52 }
53
54 template <std::size_t M>
55 [[nodiscard]] constexpr bool operator==(const FixedString<M>& other) const noexcept {
56 if constexpr (M != N) {
57 return false;
58 } else {
59 for (std::size_t i = 0; i < N; ++i) {
60 if (value[i] != other.value[i]) {
61 return false;
62 }
63 }
64 return true;
65 }
66 }
67};
68
69} // namespace comms
Compile-time fixed-size string usable as a non-type template parameter.
Definition fixed_string.hpp:21
char value[N]
Character storage, including the trailing null terminator.
Definition fixed_string.hpp:23
constexpr FixedString() noexcept=default
Default-constructs an all-‘’\0'string.