1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
|
#include <string.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include "String.h"
#include "util.h"
String::String() {
this->set("");
}
String::String(const String & other) {
this->set(other.data(), other.size());
}
String & String::operator = (const String & other) {
if (this == &other) return *this;
this->set(other.data(), other.size());
return *this;
}
String::String(String && other) {
this->_data = other._data;
this->_data_len = other._data_len;
}
String & String::operator = (String && other) {
if (this == &other) return *this;
safe_free(&this->_data);
this->_data = other._data;
this->_data_len = other._data_len;
other._data = nullptr;
other._data_len = 0;
return *this;
}
String::String(const char * c_str) {
if (c_str == nullptr) c_str = "";
this->set(c_str);
}
String::String(const char * data, size_t size) {
this->set(data, size);
}
String String::fmt(const char * fmt, ...) {
va_list args;
va_start(args, fmt);
String out = String::va_fmt(args, fmt);
va_end(args);
return out;
}
String String::va_fmt(va_list args, const char * fmt) {
String out;
va_list args_copy;
va_copy(args_copy, args);
out._data_len = vsnprintf(NULL, 0, fmt, args_copy);
va_end(args_copy);
safe_free(&out._data);
out._data = static_cast<char *>(malloc(out._data_len + 1));
vsnprintf(out._data, out._data_len + 1, fmt, args);
return out;
}
String::~String() {
safe_free(&this->_data);
}
void String::set(const char * data) {
this->set(data, strlen(data));
}
void String::set(const char * data, size_t data_len) {
safe_free(&this->_data);
this->_data = static_cast<char *>(malloc(data_len + 1));
this->_data_len = data_len;
memcpy(this->_data, data, data_len);
this->_data[this->_data_len] = '\0';
}
const char * String::c_str() const {
return this->_data;
}
char * String::data() const {
return this->_data;
}
size_t String::size() const {
return this->_data_len;
}
bool String::empty() const {
return this->_data_len == 0;
}
bool operator == (const String & a, const String & b) {
return strncmp(a._data, b._data, min(a._data_len, b._data_len)) == 0;
}
bool operator != (const String & a, const String & b) {
return !(a == b);
}
|