summaryrefslogtreecommitdiff
path: root/userland/libc/tb/sb.c
blob: 7ba83af682d167cf76dd4c9883a1f2b0e4e409d0 (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
68
69
70
71
72
73
74
75
76
77
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <tb/sb.h>

void sb_init(struct sb *ctx, size_t starting_capacity) {
  ctx->string = malloc(starting_capacity);
  ctx->length = 0;
  ctx->capacity = starting_capacity;
}

void sb_free(struct sb *ctx) {
  ctx->length = 0;
  ctx->capacity = 0;
  free(ctx->string);
  ctx->string = NULL;
}

void sb_reset(struct sb *ctx) {
  ctx->length = 0;
}

int sb_isempty(const struct sb *ctx) {
  return (0 == ctx->length);
}

void sb_append_char(struct sb *ctx, char c) {
  if (1 > ctx->capacity - ctx->length) {
    ctx->capacity += 32;
    ctx->string = realloc(ctx->string, ctx->capacity);
  }
  memcpy(ctx->string + ctx->length, &c, 1);
  ctx->length++;
}

int sb_delete_right(struct sb *ctx, size_t n) {
  n = min(n, ctx->length);
  ctx->length -= n;
  return n;
}

void sb_append(struct sb *ctx, const char *s) {
  size_t l = strlen(s);
  if (l > ctx->capacity - ctx->length) {
    ctx->capacity += l;
    ctx->string = realloc(ctx->string, ctx->capacity);
  }
  memcpy(ctx->string + ctx->length, s, l);
  ctx->length += l;
}

void sb_prepend_sv(struct sb *ctx, struct sv sv) {
  sb_prepend_buffer(ctx, sv.s, sv.length);
}

void sb_prepend_buffer(struct sb *ctx, const char *buffer, size_t length) {
  if (length > ctx->capacity - ctx->length) {
    ctx->capacity += length;
    ctx->string = realloc(ctx->string, ctx->capacity);
  }
  memmove(ctx->string + length, ctx->string, ctx->length);
  memcpy(ctx->string, buffer, length);
  ctx->length += length;
}

void sb_append_buffer(struct sb *ctx, const char *buffer, size_t length) {
  if (length > ctx->capacity - ctx->length) {
    ctx->capacity += length;
    ctx->string = realloc(ctx->string, ctx->capacity);
  }
  memcpy(ctx->string + ctx->length, buffer, length);
  ctx->length += length;
}

void sb_append_sv(struct sb *ctx, struct sv sv) {
  sb_append_buffer(ctx, sv.s, sv.length);
}