#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::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(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; } 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); }