cpp-stat-bench 0.24.0
Benchmark library with statistics for C++.
Loading...
Searching...
No Matches
escape_for_file_name.cpp
Go to the documentation of this file.
1/*
2 * Copyright 2025 MusicScience37 (Kenta Kabashima)
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
21
22#include <array>
23#include <cstddef>
24#include <cstdint>
25#include <string>
26#include <string_view>
27
28namespace stat_bench {
29namespace util {
30
31namespace {
32
38constexpr std::string_view safe_chars =
39 "!+-"
40 "0123456789"
41 "@"
42 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
43 "^_"
44 "abcdefghijklmnopqrstuvwxyz"
45 "{}~";
46
48constexpr std::size_t num_8bit_chars = 256;
49
55[[nodiscard]] constexpr auto create_safe_char_table()
56 -> std::array<bool, num_8bit_chars> {
57 std::array<bool, num_8bit_chars> table{};
58 for (std::size_t i = 0; i < num_8bit_chars; ++i) {
59 table[i] = false;
60 }
61 for (const char c : safe_chars) {
62 table[static_cast<std::uint8_t>(c)] = true;
63 }
64 return table;
65}
66
74[[nodiscard]] auto is_safe_char(char c) -> bool {
75 static constexpr auto table = create_safe_char_table();
76 return table[static_cast<std::uint8_t>(c)];
77}
78
79} // namespace
80
82 std::string output;
83 for (const char c : input.str()) {
84 if (!is_safe_char(c)) {
85 output.push_back('%');
86 constexpr std::string_view hex_chars = "0123456789ABCDEF";
87 const auto byte =
88 static_cast<unsigned>(static_cast<std::uint8_t>(c));
89 constexpr unsigned mask = 0xFU;
90 output.push_back(hex_chars[(byte >> 4U) & mask]);
91 output.push_back(hex_chars[byte & mask]);
92 } else {
93 output.push_back(c);
94 }
95 }
96 return Utf8String(output);
97}
98
99} // namespace util
100} // namespace stat_bench
Class of UTF-8 encoded string.
Definition utf8_string.h:35
Declaration of escape_for_file_name function.
Namespace of utility functions and classes.
auto escape_for_file_name(const Utf8String &input) -> Utf8String
Escape a string for a file name.
Namespace of stat_bench source codes.