Botcraft 1.21.4
Loading...
Searching...
No Matches
ConstexprStrProcessing.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <array>
4#include <stdexcept>
5#include <string_view>
6
7namespace ProtocolCraft
8{
9 namespace Internal
10 {
11 /// @brief Get the size of a string_view once converted to snake_case
12 /// @param str string to convert to snake_case
13 /// @return Number of characters in the snake_case string
14 constexpr size_t GetSnakeCaseSize(std::string_view str)
15 {
16 size_t size = 0;
17 for (size_t i = 0; i < str.length(); ++i)
18 {
19 if (i > 0 &&
20 ((str[i] >= 'A' && str[i] <= 'Z') ||
21 (str[i] >= '0' && str[i] <= '9' && (str[i - 1] < '0' || str[i - 1] > '9')))
22 )
23 {
24 size += 2;
25 }
26 else
27 {
28 size += 1;
29 }
30 }
31 return size;
32 }
33
34 /// @brief Get a snake_case char array from a string_view
35 /// @tparam N Size of the output array, should match GetSnakeCaseSize(str)
36 /// @param str String to convert to snake_case
37 /// @return std::array of the converted string
38 template <size_t N>
39 constexpr std::array<char, N> ToSnakeCase(std::string_view str)
40 {
41 // We can't static_assert based on str, so throw instead
42 if (GetSnakeCaseSize(str) != N)
43 {
44 throw std::invalid_argument("ToSnakeCase called with wrong output size");
45 }
46 std::array<char, N> output{};
47 size_t index = 0;
48 for (size_t i = 0; i < str.length(); ++i)
49 {
50 if (str[i] >= 'A' && str[i] <= 'Z')
51 {
52 if (i > 0)
53 {
54 output[index++] = '_';
55 }
56 output[index++] = str[i] + 'a' - 'A';
57 }
58 else if (i > 0 && str[i] >= '0' && str[i] <= '9' && (str[i - 1] < '0' || str[i - 1] > '9'))
59 {
60 output[index++] = '_';
61 output[index++] = str[i];
62 }
63 else
64 {
65 output[index++] = str[i];
66 }
67 }
68 return output;
69 }
70
71 /// @brief Convert a std::array of char to string_view
72 /// @tparam N Size of the array
73 /// @param a array to convert to string_view
74 /// @return std::string_view wrapping around a chars
75 template <size_t N>
76 constexpr std::string_view ToStringView(const std::array<char, N>& a)
77 {
78 return std::string_view(a.data(), N);
79 }
80
81 }
82}
constexpr std::string_view ToStringView(const std::array< char, N > &a)
Convert a std::array of char to string_view.
constexpr size_t GetSnakeCaseSize(std::string_view str)
Get the size of a string_view once converted to snake_case.
constexpr std::array< char, N > ToSnakeCase(std::string_view str)
Get a snake_case char array from a string_view.