btllib: include/btllib/cstring.hpp Source File

btllib

cstring.hpp
1 #ifndef BTLLIB_CSTRING_HPP
2 #define BTLLIB_CSTRING_HPP
3
4 #include <cstdlib>
5 #include <cstring>
6 #include <string>
7
8 namespace btllib {
9
10 struct CString
11 {
12 static const size_t CSTRING_DEFAULT_CAP = 4096;
13
14 CString() { s[0] = '\0'; }
15
16 CString(const CString& cstring)
17 {
18 if (cstring.s_size > s_cap) {
19 s = (char*)std::realloc((char*)s, cstring.s_size); // NOLINT
20 s_cap = cstring.s_size;
21 }
22 s_size = cstring.s_size;
23 memcpy(s, cstring.s, s_size);
24 }
25
26 CString(CString&& cstring) noexcept
27 {
28 std::swap(s, cstring.s);
29 s_size = cstring.s_size;
30 cstring.clear();
31 std::swap(s_cap, cstring.s_cap);
32 }
33
34 CString(const std::string& str)
35 {
36 if (str.size() + 1 > s_cap) {
37 s_cap = str.size() + 1;
38 s = (char*)std::realloc((char*)s, s_cap); // NOLINT
39 }
40 s_size = str.size();
41 memcpy(s, str.c_str(), s_size + 1);
42 }
43
44 CString& operator=(const CString& cstring)
45 {
46 if (this == &cstring) {
47 return *this;
48 }
49 if (cstring.s_size > s_cap) {
50 s = (char*)std::realloc((char*)s, cstring.s_size); // NOLINT
51 s_cap = cstring.s_size;
52 }
53 s_size = cstring.s_size;
54 memcpy(s, cstring.s, s_size);
55 return *this;
56 }
57
58 CString& operator=(CString&& cstring) noexcept
59 {
60 std::swap(s, cstring.s);
61 s_size = cstring.s_size;
62 cstring.clear();
63 std::swap(s_cap, cstring.s_cap);
64 return *this;
65 }
66
67 CString& operator=(const std::string& str)
68 {
69 if (str.size() + 1 > s_cap) {
70 s_cap = str.size() + 1;
71 s = (char*)std::realloc((char*)s, s_cap); // NOLINT
72 }
73 s_size = str.size();
74 memcpy(s, str.c_str(), s_size + 1);
75 return *this;
76 }
77
78 ~CString() { free(s); } // NOLINT
79
80 void clear()
81 {
82 s[0] = '\0';
83 s_size = 0;
84 }
85 bool empty() const { return (ssize_t)s_size <= 0; }
86 size_t size() const { return s_size; }
87
88 operator char*() const { return s; }
89
90 char* s = (char*)std::malloc(CSTRING_DEFAULT_CAP); // NOLINT
91 size_t s_size = 0;
92 size_t s_cap = CSTRING_DEFAULT_CAP;
93 };
94
95 } // namespace btllib
96
97 #endif
btllib::CString
Definition: cstring.hpp:11