import config

class String:
    int allocated, used
    char *pointer

String *def string_new():
    String *s = ALLOCATE0(sizeof *s)
    s->pointer = ALLOCATE0(1)
    s->used = 1
    s->allocated = 1
    return s

def string_add(String *s, char c):
    s->used++
    if s->used > s->allocated:
        s->allocated *= 2
        s->pointer = REALLOCATE(s->pointer, s->allocated)
    s->pointer[s->used - 2] = c
    s->pointer[s->used - 1] = '\0'

char *def string_c(String *s):
    return s->pointer

def string_clear(String *s):
    s->used = 1
    s->pointer[0] = '\0'

def string_lstrip(String *s):
    """
    Examples:
    "" -> ""
    " " -> ""
    "  a" -> "a"
    """
    int first = 0
    while 1:
        char c = s->pointer[first]
        if not c: break
        if c == ' ' or c == '\t':
            first++
        else:
            break
    s->used -= first
    memmove(s->pointer, s->pointer + first, s->used)

def string_rstrip(String *s):
    """
    Examples:
    "" -> ""
    " " -> ""
    "a  " -> "a"
    """
    while s->used > 1:
        char c = s->pointer[s->used - 2]
        if c == ' ' or c == '\t':
            s->used--
            s->pointer[s->used - 1] = '\0'
        else:
            break

def string_strip(String *s):
    string_rstrip(s)
    string_lstrip(s)

int def string_char(String *s, int i):
    if i >= 0:
        if i >= s->used: return 0
        return s->pointer[i]
    else:
        if -i >= s->used: return 0
        return s->pointer[s->used + i - 1]

bool def string_is_same_c(String *s, char const *c):
    return ! strcmp(s->pointer, c)

bool def string_is_empty(String *s):
    return s->used == 1