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
|
#include <string.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include "String.h"
#include "util.h"
String::String() {
this->set("");
}
String & String::operator = (const String & other) {
this->set(other.data(), other.size());
return *this;
}
String::String(const String & other) {
this->set(other.data(), other.size());
}
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;
}
|