VoltMod
C++23 framework for CS2 server plugins
Loading...
Searching...
No Matches
CharBuf.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <algorithm>
4#include <cstddef>
5#include <cstring>
6#include <string>
7#include <string_view>
8
9namespace VoltMod
10{
11
12/**
13 * @brief A value for a fixed engine character array (`char m_name[N]`).
14 *
15 * Assignment truncates to N-1 characters, adds a NUL, and clears the unused tail. @ref View
16 * borrows this buffer; @ref Str returns a copy.
17 */
18template <size_t N>
19struct CharBuf
20{
21 static_assert(N > 1, "a CharBuf needs room for at least one character and a NUL");
22
23 char Value[N]{};
24
25 CharBuf() = default;
26 CharBuf(std::string_view text) noexcept { Assign(text); }
27
28 /** Supports direct construction from a literal without two user-defined conversions. */
29 CharBuf(const char* text) noexcept { Assign(text ? std::string_view(text) : std::string_view{}); }
30
31 CharBuf& operator=(std::string_view text) noexcept
32 {
33 Assign(text);
34 return *this;
35 }
36
37 /** Avoids ambiguous assignment from a string literal. */
38 CharBuf& operator=(const char* text) noexcept
39 {
40 Assign(text ? std::string_view(text) : std::string_view{});
41 return *this;
42 }
43
44 /** Contents before the first NUL, borrowed from this buffer. */
45 std::string_view View() const noexcept
46 {
47 size_t length = 0;
48 while (length < N && Value[length] != '\0')
49 {
50 ++length;
51 }
52 return {Value, length};
53 }
54
55 std::string Str() const { return std::string(View()); }
56
57 bool Empty() const noexcept { return Value[0] == '\0'; }
58
59 void Assign(std::string_view text) noexcept
60 {
61 const size_t length = std::min(text.size(), N - 1);
62 std::memset(Value, 0, N);
63 if (length > 0)
64 {
65 std::memcpy(Value, text.data(), length);
66 }
67 }
68};
69
70} // namespace VoltMod
static std::string ReadFile(const std::filesystem::path &path)
Definition Loader.cpp:56
A value for a fixed engine character array (char m_name[N]).
Definition CharBuf.hpp:20
std::string Str() const
Definition CharBuf.hpp:55
CharBuf & operator=(const char *text) noexcept
Definition CharBuf.hpp:38
CharBuf & operator=(std::string_view text) noexcept
Definition CharBuf.hpp:31
CharBuf(std::string_view text) noexcept
Definition CharBuf.hpp:26
void Assign(std::string_view text) noexcept
Definition CharBuf.hpp:59
CharBuf(const char *text) noexcept
Definition CharBuf.hpp:29
CharBuf()=default
bool Empty() const noexcept
Definition CharBuf.hpp:57
std::string_view View() const noexcept
Definition CharBuf.hpp:45