aboutsummaryrefslogtreecommitdiff
path: root/src/common/better_string.c
blob: 7863da0c24bef70e0b8ecb226b393fadd549cfda (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
#include "../include/better_string.h"
#include "../include/helpers.h"
#include <stdlib.h>
#include <string.h>

string_t *init_string(const char *src) {
  string_t *s = safe_calloc(1, sizeof(string_t));
  size_t len = src ? strlen(src) : DEFAULT_STR_SIZE;
  size_t size = len * 2;
  s->buf = safe_calloc(size, sizeof(char));
  s->buf[0] = '\0';

  if (src)
    strcpy(s->buf, src);
  s->len = len;
  s->size = size;
  return s;
}

void string_push(string_t *s, char c) {
  if (s->len >= s->size - 3) {
    s->size *= 2;
    s->buf = safe_realloc(s->buf, s->size);
  }
  s->buf[s->len] = c;
  s->buf[s->len + 1] = '\0';
  s->len++;
}

char string_pop(string_t *s) {
  char c = s->buf[s->len];
  s->len--;
  return c;
}

void string_concat_const(string_t *s1, const char *s2) {
  for (int i = 0; i < strlen(s2); i++)
    string_push(s1, s2[i]);
}

void string_concat(string_t *s1, string_t *s2) {
  for (int i = 0; i < s2->len; i++) {
    string_push(s1, s2->buf[i]);
  }
}

void string_free(void *x) {
  string_t *s = x;

  if (!x)
    return;

  free(s->buf);
  free(s);
}