Debian Codegraph @

common/main/player-callsign.h

raw
1 /*
2 * Portions of this file are copyright Rebirth contributors and licensed as
3 * described in COPYING.txt.
4 * Portions of this file are copyright Parallax Software and licensed
5 * according to the Parallax license below.
6 * See COPYING.txt for license details.
7 */
8
9 #pragma once
10
11 #include <algorithm>
12 #include <cassert>
13 #include <cctype>
14 #include <cstddef>
15 #include <ranges>
16 #include <span>
17 #include "dxxsconf.h"
18 #include <array>
19
20 #define CALLSIGN_LEN 8 // so can use as filename (was: 12)
21
22 struct callsign_t
23 {
24 static constexpr std::size_t array_length{CALLSIGN_LEN + 1};
25 operator const void *() const = delete;
26 std::array<char, array_length> a;
27 [[nodiscard]]
28 static char lower_predicate(char c)
29 {
30 return std::tolower(static_cast<unsigned>(c));
31 }
32 template <std::size_t Extent>
33 requires(Extent == std::dynamic_extent || Extent <= array_length)
34 void copy(const std::span<const char, Extent> s)
35 {
36 /* Zero the entire array first, so that word-sized moves can be used to
37 * store the null bytes in bulk. Then copy an appropriate number of
38 * characters using byte-sized moves, with a limit to prevent
39 * overwriting the final null byte even if the input string is too
40 * long.
41 */
42 a = {};
43 std::ranges::copy_n(s.begin(), std::min(array_length - 1, s.size()), a.begin());
44 }
45 template <std::size_t Extent>
46 requires(Extent == std::dynamic_extent || Extent <= array_length)
47 void copy_lower(const std::span<const char, Extent> sc)
48 {
49 a = {};
50 const auto input_begin{std::ranges::begin(sc)};
51 std::ranges::transform(input_begin, std::next(input_begin, std::min(array_length - 1, sc.size())), a.begin(), lower_predicate);
52 }
53 template <std::size_t Extent>
54 void copy_lower(const std::span<char, Extent> sc)
55 {
56 copy_lower(std::span<const char, Extent>(sc.begin(), sc.size()));
57 }
58 void lower()
59 {
60 const auto ba{a.begin()};
61 /* The buffer should be null-terminated before calling `lower()`. */
62 assert(!a.back());
63 std::ranges::transform(ba, std::prev(a.end()), ba, lower_predicate);
64 }
65 [[nodiscard]]
66 auto &buffer()
67 {
68 return *reinterpret_cast<char(*)[array_length]>(a.data());
69 }
70 template <std::size_t N>
71 void operator=(const char (&s)[N])
72 {
73 copy(std::span(s));
74 }
75 void fill(const char c)
76 {
77 a.fill(c);
78 }
79 /* Only expose the `const` version of `operator[]`. Callers should not use
80 * `operator[]` to modify the underlying array.
81 */
82 [[nodiscard]]
83 constexpr const char &operator[](const std::size_t i) const
84 {
85 return a[i];
86 }
87 [[nodiscard]]
88 operator const char *() const
89 {
90 return a.data();
91 };
92 [[nodiscard]]
93 constexpr bool operator==(const callsign_t &r) const = default;
94 };
95 static_assert(sizeof(callsign_t) == CALLSIGN_LEN + 1, "callsign_t too big");