Debian Codegraph @

common/main/nvparse.h

raw
1 /*
2 * This file is copyright by Rebirth contributors and licensed as
3 * described in COPYING.txt.
4 * See COPYING.txt for license details.
5 */
6
7 #pragma once
8
9 #include <algorithm>
10 #include <cassert>
11 #include <cstdint>
12 #include <cstdlib>
13 #include <cstring>
14 #include <iterator>
15 #include <optional>
16 #include <ranges>
17 #include <type_traits>
18 #include <utility>
19 #include "dxxsconf.h"
20 #include "ntstring.h"
21
22 template <std::size_t N>
23 requires(N > 1)
24 [[nodiscard]]
25 static inline bool compare_nonterminated_name(const auto &candidate, const char (&name)[N])
26 {
27 /* C++ rules for string literals guarantee that `name` has a trailing null
28 * terminator. Callers pass `candidate` with no trailing null terminator,
29 * so the simple invocation of `std::ranges::equal(range, range)` will
30 * always fail to match.
31 *
32 * `compare_nonterminated_name` considers the candidate equal to the name
33 * if the name without the null terminator compares equal to the candidate,
34 * so use `std::prev` to exclude the terminator.
35 */
36 return std::ranges::equal(std::ranges::begin(candidate), std::ranges::end(candidate), std::ranges::begin(name), std::prev(std::ranges::end(name)));
37 }
38
39 template <std::integral T>
40 [[nodiscard]]
41 static inline std::optional<T> convert_integer(const char *const value, int base, auto libc_str_to_integer)
42 {
43 char *e;
44 const auto r = libc_str_to_integer(value, &e, base);
45 if (*e)
46 /* Trailing garbage found */
47 return std::nullopt;
48 if constexpr (std::is_same<T, bool>::value)
49 {
50 if (r != 0 && r != 1)
51 return std::nullopt;
52 }
53 else if (!std::in_range<T>(r))
54 /* Result truncated */
55 return std::nullopt;
56 return static_cast<T>(r);
57 }
58
59 template <std::integral T>
60 [[nodiscard]]
61 static inline auto convert_integer(const std::span<char>::iterator value, int base, auto libc_str_to_integer)
62 {
63 return convert_integer<T>(value.base(), base, libc_str_to_integer);
64 }
65
66 template <std::signed_integral T>
67 [[nodiscard]]
68 static inline auto convert_integer(auto &&value, int base = 10)
69 {
70 return convert_integer<T>(std::move(value), base, std::strtol);
71 }
72
73 template <std::unsigned_integral T>
74 [[nodiscard]]
75 static inline auto convert_integer(auto &&value, int base = 10)
76 {
77 return convert_integer<T>(std::move(value), base, std::strtoul);
78 }
79
80 template <std::integral T>
81 static inline void convert_integer(T &t, auto &&value, int base = 10)
82 {
83 if (const auto r{convert_integer<T>(std::move(value), base)})
84 t = *r;
85 }
86
87 template <std::size_t N, typename I>
88 static inline void convert_string(ntstring<N> &out, I value, I eol)
89 {
90 assert(*eol == 0);
91 std::advance(eol, 1);
92 const std::size_t i = std::distance(value, eol);
93 if (i > out.size())
94 /* Only if not truncated */
95 return;
96 std::copy(std::move(value), std::move(eol), out.begin());
97 }