aboutsummaryrefslogtreecommitdiff
path: root/src/types/str.c
blob: 4b257cb2b00494dd75954e6737b055676cb7baa1 (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
#include "str.h"
#include "../lua.h"
#include "../util.h"

#define alloc_buffer 64

str* str_initl(const char* init, size_t len){

  str* s = malloc(sizeof * s);
  s->_bytes = len + 1 + alloc_buffer;
  s->c = malloc(s->_bytes);
  if(s->c == NULL) p_fatal("failed to allocate string\n");
  s->len = len ;
  
  memcpy(s->c, init, (len + 1) * sizeof * init);
  return s;
}

str* str_init(const char* init){
  return str_initl(init, strlen(init));
}

void str_free(str* s){
  free(s->c);
  return free(s);
}

void str_push(str* s, const char* insert){
  s->len += strlen(insert);
  if(s->len + 1 >= s->_bytes)
    s->c = realloc(s->c, s->_bytes = s->len + 1 + alloc_buffer);
  strcat(s->c, insert);
}

void str_pushl(str* s, const char* insert, size_t l){
  if(s->len + l >= s->_bytes)
    s->c = realloc(s->c, s->_bytes = s->len + l + alloc_buffer);
  //strcat(s->c, insert);
  for(int i = 0; i != l; i++){
    s->c[i + s->len] = insert[i];
  }
  s->len += l;
  s->c[s->len] = '\0';
}

void str_clear(str* s){
  memset(s->c, 0, s->len);

  s->len = 0;
}

void str_popf(str* s, int len){
  memmove(s->c, s->c + len, s->len -= len);
  s->c[s->len] = 0;
}

void str_popb(str* s, int len){
  s->len -= len;
  s->c[s->len] = 0;
}