#include "String.h" #include #include #include namespace ecci { #ifdef TESTING /*static*/ size_t String::instanceCount = 0; #endif String::String(const char* text, size_t len) : length{ len != npos ? len : strlen(text) } , text{ (char*) malloc( (length + 1) * sizeof(char) ) } { assert(text); strncpy(this->text, text, this->length); std::cerr << "String(" << text << ", " << length << ")\n"; #ifdef TESTING ++instanceCount; #endif } String::String(char ch) : length{ ch ? static_cast(1) : static_cast(0) } , text{ (char*) malloc( (length + 1) * sizeof(char) ) } { assert(text); this->text[0] = ch; this->text[ this->length ] = '\0'; std::cerr << "StringCh('" << text << "', " << length << ")\n"; #ifdef TESTING ++instanceCount; #endif } String::String(size_t capacity) : length{ 0 } , text{ (char*) malloc( (capacity + 1) * sizeof(char) ) } { assert(text); this->text[0] = '\0'; std::cerr << "StringSz(" << capacity << ", " << length << ")\n"; #ifdef TESTING ++instanceCount; #endif } String::String(const String& other) : length{ other.length } , text{ (char*) malloc( (length + 1) * sizeof(char) ) } { strcpy(this->text, other.text); std::cerr << "StringCp(" << text << ", " << length << ")\n"; #ifdef TESTING ++instanceCount; #endif } String::String(String&& other) : length{ other.length } , text{ other.text } { other.length = 0; other.text = nullptr; std::cerr << "StringMv(" << text << ", " << length << ")\n"; #ifdef TESTING ++instanceCount; #endif } String::~String() { std::cerr << "~String(" << (text ? text : "") << ", " << length << ")\n"; free(text); #ifdef TESTING --instanceCount; #endif } String& String::operator=(const String& other) { if ( this != &other ) { this->length = other.length; this->text = (char*) realloc( this->text, (this->length + 1) * sizeof(char) ); assert(this->text); strcpy(this->text, other.text); } std::cerr << "operator=(" << text << ", " << length << ")\n"; return *this; } String& String::operator=(String&& other) { if ( this != &other ) { free(text); this->length = other.length; this->text = other.text; other.length = 0; other.text = nullptr; } std::cerr << "operator=Mv(" << text << ", " << length << ")\n"; return *this; } const String String::operator+(const String& other) const { size_t len = this->length + other.length; String result{ len }; strcpy( result.text, this->text ); strcpy( result.text + this->length, other.text ); result.length = len; return result; } } // namespace ecci