#include "mstring.h"
#include "mdebug.h"

string_obj* string_new(char* str)
{
    string_obj* result;
    
    result = MALLOC(sizeof(string_obj));
    result->mStr = STRDUP(str);
    result->mLen = strlen(str);

    return result;
}

void string_delete(string_obj* str)
{
    FREE(str->mStr);
    
    FREE(str);
}

int string_length(string_obj* obj)
{
    return obj->mLen;
}

char* string_c_str(string_obj* obj)
{
    return obj->mStr;
}

void string_insert(string_obj* obj, int pos, char* str)
{
    char* new_str;
    const int str_len = strlen(str);
    
    new_str = MALLOC(obj->mLen + str_len + 1);

    memcpy(new_str, obj->mStr, pos);
    memcpy(new_str + pos, str, str_len);
    strcpy(new_str + pos + str_len, obj->mStr + pos);

    FREE(obj->mStr);

    obj->mStr = new_str;
    obj->mLen = strlen(new_str);
}

void string_erase(string_obj* obj, int pos, int len)
{
//    strcpy(obj->mStr + pos, obj->mStr+pos+len);
    memmove(obj->mStr + pos, obj->mStr+pos+len, obj->mLen-pos-len+1);

    obj->mLen-=len;
}

void string_push_back(string_obj* self, char key)
{
    char* old = self->mStr;
    
    self->mLen++;
    self->mStr = MALLOC(sizeof(char)*self->mLen+1);
    strcpy(self->mStr, old);
    self->mStr[self->mLen-1] = key;
    self->mStr[self->mLen] = 0;

    FREE(old);
}

void string_put(string_obj* self, char* str)
{
    FREE(self->mStr);
    self->mStr = STRDUP(str);
    self->mLen = strlen(str);
}
