group2 0.1.0
CSE 125 Group 2
Loading...
Searching...
No Matches
ServerName.hpp
Go to the documentation of this file.
1
3
4#pragma once
5
6#include <cstddef>
7#include <string>
8#include <string_view>
9
10namespace server_name
11{
12constexpr std::size_t k_maxBytes = 32;
13constexpr std::string_view k_default = "Server";
14
15inline std::string clampUtf8Bytes(std::string_view value)
16{
17 std::size_t i = 0;
18 std::size_t lastValid = 0;
19 while (i < value.size() && i < k_maxBytes) {
20 const auto c = static_cast<unsigned char>(value[i]);
21 std::size_t len = 1;
22 if (c < 0x80) {
23 len = 1;
24 } else if ((c & 0xE0) == 0xC0) {
25 len = 2;
26 } else if ((c & 0xF0) == 0xE0) {
27 len = 3;
28 } else if ((c & 0xF8) == 0xF0) {
29 len = 4;
30 } else {
31 break;
32 }
33
34 if (i + len > value.size() || i + len > k_maxBytes)
35 break;
36
37 bool validContinuation = true;
38 for (std::size_t j = 1; j < len; ++j) {
39 const auto next = static_cast<unsigned char>(value[i + j]);
40 if ((next & 0xC0) != 0x80) {
41 validContinuation = false;
42 break;
43 }
44 }
45 if (!validContinuation)
46 break;
47
48 i += len;
49 lastValid = i;
50 }
51
52 return std::string(value.substr(0, lastValid));
53}
54
55inline std::string sanitize(std::string_view value, std::string_view fallback = k_default)
56{
57 std::string result = clampUtf8Bytes(value);
58 if (!result.empty())
59 return result;
60
61 result = clampUtf8Bytes(fallback);
62 if (!result.empty())
63 return result;
64
65 return std::string(k_default);
66}
67} // namespace server_name
Definition ServerName.hpp:11
std::string clampUtf8Bytes(std::string_view value)
Definition ServerName.hpp:15
std::string sanitize(std::string_view value, std::string_view fallback=k_default)
Definition ServerName.hpp:55
constexpr std::size_t k_maxBytes
Definition ServerName.hpp:12
constexpr std::string_view k_default
Definition ServerName.hpp:13