aboutsummaryrefslogtreecommitdiff
path: root/sb.c
blob: 0353545e79bf5784e843aebb2ee3a4b8347555b4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <stdlib.h>
#include <string.h>
#include "sb.h"

struct node{ // linked list, but strings don't have to be max size
    size_t cap;
    size_t len;
    char* text;
    node* next;
};

// malloc might fail, but the entire program should just crash if it does
node* newsb(size_t cap){
    node* sb;
    sb = malloc(sizeof(node));
    sb->text = malloc(sizeof(char)*cap);
    sb->len = 0; sb->cap = cap;
    sb->next = NULL;
    return sb;
}

node* extendsb(node* tail){
    tail->next = newsb(tail->cap*2);
    return tail->next;
}

node* appendsb(node* tail, const char* str){
    for (int i=0; str[i] != '\0'; i++){
        if (tail->len == tail->cap) tail = extendsb(tail); // if full, extend
        *(tail->text + tail->len) = str[i]; // copy str[i] to last open spot
        tail->len++;
    }
    return tail;
}
///////// i want to prevent this duplication but cant figure out how :(

node* addchrsb(node* tail, char chr){
    if (tail->len == tail->cap) tail = extendsb(tail); // if full, extend
    *(tail->text + tail->len) = chr; // copy str[i] to last open spot
    tail->len++;
    return tail;
}

char* tostr(node* head){ // destructive; frees the whole chain
    int len;
    char* str;
    len = lensb(head);
    str = malloc((len+1)*sizeof(char)); // need +1 for null terminator
    str[len] = '\0';

    len = 0; //controls progression through str
    do {
        strncpy(str+len, head->text, head->len);
        len += head->len;
        head = head->next;
        free(head);
    } while ( head != NULL);
    return str;
}

int lensb(node* head){ // how much space do i need to concat all strings
    int len = 0;
    do {
        len += head->len;
    } while ( (head = head->next) != NULL);
    return len;
}