#include #include #include #include #include "String.h" #include "util.h" String::String() { this->set(""); } 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::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(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(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; }