readbuf.c 1.03 KB
Newer Older
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
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include "readbuf.h"

void resize_readbuf(preadbuf b, size_t newcapacity);

preadbuf init_readbuf(size_t capacity) {
  assert (capacity > 0);
  preadbuf buf;
  buf = (preadbuf) malloc(sizeof(t_readbuf));
  buf->capacity = capacity;
  buf->len = 0;
  buf->data = (char*) malloc(sizeof(char) * capacity);
  return buf;
}

void resize_readbuf(preadbuf b, size_t newcapacity) {
  b->data = (char*) realloc(b->data, sizeof(char) * newcapacity);
  b->capacity = newcapacity;
}

char* prepare_read(preadbuf b, size_t size) {
  if (b->len + size > b->capacity) {
     resize_readbuf(b, (b->capacity + size) * 2);
  }
  return b->data + b->len;
}

void have_read(preadbuf b, size_t size) {
  assert(b->capacity >= b->len + size);
  b->len += size;
}

void have_taken(preadbuf b, size_t size) {
  assert (size <= b->len);
  memcpy(b->data, b->data+size, b->len - size);
  b->len -= size;
}

void clear_readbuf(preadbuf b) {
  b->len = 0;
}

void free_readbuf(preadbuf b) {
  free(b->data);
  free(b);
}