xdebug

next generation of mdebug (work in progress)
git clone http://frotz.net/git/xdebug.git
Log | Files | Refs | README

bytebuffer.inl.c (1418B)


      1 struct bytebuffer {
      2 	uint8_t *buf;
      3 	int len;
      4 	int cap;
      5 };
      6 
      7 static void bytebuffer_reserve(struct bytebuffer *b, int cap) {
      8 	if (b->cap >= cap) {
      9 		return;
     10 	}
     11 
     12 	// prefer doubling capacity
     13 	if (b->cap * 2 >= cap) {
     14 		cap = b->cap * 2;
     15 	}
     16 
     17 	uint8_t *newbuf = realloc(b->buf, cap);
     18 	b->buf = newbuf;
     19 	b->cap = cap;
     20 }
     21 
     22 static void bytebuffer_init(struct bytebuffer *b, int cap) {
     23 	b->cap = 0;
     24 	b->len = 0;
     25 	b->buf = 0;
     26 
     27 	if (cap > 0) {
     28 		b->cap = cap;
     29 		b->buf = malloc(cap); // just assume malloc works always
     30 	}
     31 }
     32 
     33 static void bytebuffer_free(struct bytebuffer *b) {
     34 	if (b->buf)
     35 		free(b->buf);
     36 }
     37 
     38 static void bytebuffer_clear(struct bytebuffer *b) {
     39 	b->len = 0;
     40 }
     41 
     42 static void bytebuffer_append(struct bytebuffer *b, const char *data, int len) {
     43 	bytebuffer_reserve(b, b->len + len);
     44 	memcpy(b->buf + b->len, data, len);
     45 	b->len += len;
     46 }
     47 
     48 static void bytebuffer_puts(struct bytebuffer *b, const char *str) {
     49 	bytebuffer_append(b, str, strlen(str));
     50 }
     51 
     52 static void bytebuffer_resize(struct bytebuffer *b, int len) {
     53 	bytebuffer_reserve(b, len);
     54 	b->len = len;
     55 }
     56 
     57 static void bytebuffer_flush(struct bytebuffer *b, int fd) {
     58 	if (write(fd, b->buf, b->len) != b->len) { /* suppress warning */ }
     59 	bytebuffer_clear(b);
     60 }
     61 
     62 static void bytebuffer_truncate(struct bytebuffer *b, int n) {
     63 	if (n <= 0)
     64 		return;
     65 	if (n > b->len)
     66 		n = b->len;
     67 	const int nmove = b->len - n;
     68 	memmove(b->buf, b->buf+n, nmove);
     69 	b->len -= n;
     70 }