/*
 * htwg_string.cpp
 *
 * Stark vereinfachte String-Klasse.
 *
 * Autor: H.Drachenfels
 * Erstellt am: 30.5.2024
 */
#include "htwg_string.h"
using namespace htwg;

#include <cstring>

// Konstruktoren
string::string()
{
    this->n = 0;
    this->s = new char[1];
    *this->s = '\0';
}

string::string(const char* s)
{
    this->n = std::strlen(s);
    this->s = new char[this->n + 1];
    std::strcpy(this->s, s);
}

// Rule-of-five-Memberfunktionen (Destruktor und Copy/Move)
string::~string()
{
    delete[] this->s;
}

string::string(const string& that)
{
    this->n = that.n;
    this->s = new char[this->n + 1];
    std::strcpy(this->s, that.s);
}

string::string(string&& that) : n(that.n), s(that.s)
{
    that.n = 0;
    that.s = nullptr;
}

string& string::operator=(const string& that)
{
    if (this != &that)
    {
        delete[] this->s;
        this->n = that.n;
        this->s = new char[this->n + 1];
        std::strcpy(this->s, that.s);
    }

    return *this;
}

string& string::operator=(string&& that)
{
    if (this != &that)
    {
        delete[] this->s;
        this->n = that.n;
        this->s = that.s;
        that.n = 0;
        that.s = nullptr;
    }

    return *this;
}

// String-Konkatenation
string& string::operator+=(const string& that)
{
    std::size_t m = this->n + that.n;
    char *t = new char[m + 1];
    std::strcpy(t, this->s);
    std::strcpy(t + this->n, that.s);
    delete[] this->s;
    this->n = m;
    this->s = t;

    return *this;
}

// Vergleich(e)
namespace htwg
{
    bool operator<(const string& lhs, const string& rhs)
    {
        return std::strcmp(lhs.s, rhs.s) < 0;
    }
}
 
// Datenabfragen
const char* string::c_str() const
{
    return this->s;
}

std::size_t string::length() const
{
    return this->n;
}

