C++ Essence Library 0.1.0
A Utility Library for Modern C++ Programming
Loading...
Searching...
No Matches
naming_convention.hpp
1/*
2 * Copyright (c) 2024 The RefValue Project
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a copy
5 * of this software and associated documentation files (the "Software"), to deal
6 * in the Software without restriction, including without limitation the rights
7 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 * copies of the Software, and to permit persons to whom the Software is
9 * furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice shall be included in
12 * all copies or substantial portions of the Software.
13 *
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 * THE SOFTWARE.
21 */
22
23#pragma once
24
25#include "../../basic_string.hpp"
26#include "../../char8_t_remediation.hpp"
27
28#include <cctype>
29#include <string>
30#include <string_view>
31
32namespace essence::meta::detail {
33 inline constexpr auto underscore = U8('_');
34
35 template <std_basic_string T>
36 T camelize_or_pascalize(std::string_view name, bool camel) {
37 T result{name};
38
39 if (!result.empty()) {
40 result.front() = camel ? std::tolower(result.front()) : std::toupper(result.front());
41 }
42
43 for (auto iter = result.begin(); iter != result.end(); ++iter) {
44 if (*iter == underscore && iter + 1 != result.end()) {
45 *(iter + 1) = std::toupper(*(iter + 1));
46 }
47 }
48
49 std::erase_if(result, [](char c) { return c == underscore; });
50
51 return result;
52 }
53
54 template <std_basic_string T>
55 T make_snake_case(std::string_view name) {
56 if (name.empty()) {
57 return {};
58 }
59
60 T result(name.size() * 2, U8('\0'));
61 auto iter_result = result.begin();
62
63 *iter_result++ = std::tolower(*name.begin());
64
65 for (auto iter = name.begin() + 1; iter != name.end(); ++iter, ++iter_result) {
66 if (std::isupper(*iter)) {
67 *iter_result = underscore;
68 *(++iter_result) = std::tolower(*iter);
69 continue;
70 }
71
72 *iter_result = *iter;
73 }
74
75 result.resize(iter_result - result.begin());
76 result.shrink_to_fit();
77
78 return result;
79 }
80} // namespace essence::meta::detail