forked from aligrudi/neatcc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mem.c
75 lines (64 loc) · 1.26 KB
/
mem.c
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
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "mem.h"
#define MEMSZ 512
static void mem_extend(struct mem *mem)
{
char *s = mem->s;
mem->sz = mem->sz ? mem->sz + mem->sz : MEMSZ;
mem->s = malloc(mem->sz);
if (mem->n)
memcpy(mem->s, s, mem->n);
free(s);
}
void mem_init(struct mem *mem)
{
memset(mem, 0, sizeof(*mem));
}
void mem_done(struct mem *mem)
{
free(mem->s);
memset(mem, 0, sizeof(*mem));
}
void mem_cut(struct mem *mem, int pos)
{
mem->n = pos < mem->n ? pos : mem->n;
}
void mem_cpy(struct mem *mem, int off, void *buf, int len)
{
memcpy(mem->s + off, buf, len);
}
void mem_put(struct mem *mem, void *buf, int len)
{
while (mem->n + len + 1 >= mem->sz)
mem_extend(mem);
mem_cpy(mem, mem->n, buf, len);
mem->n += len;
}
void mem_putc(struct mem *mem, int c)
{
if (mem->n + 2 >= mem->sz)
mem_extend(mem);
mem->s[mem->n++] = c;
}
void mem_putz(struct mem *mem, int sz)
{
while (mem->n + sz + 1 >= mem->sz)
mem_extend(mem);
memset(mem->s + mem->n, 0, sz);
mem->n += sz;
}
/* return a pointer to mem's buffer; valid as long as mem is not modified */
void *mem_buf(struct mem *mem)
{
if (!mem->s)
return "";
mem->s[mem->n] = '\0';
return mem->s;
}
int mem_len(struct mem *mem)
{
return mem->n;
}