jweinst1
10/24/2019 - 10:09 PM

A simple and robust buffer implementation in C

A simple and robust buffer implementation in C

#include <stido.h>
#include <stdlib.h>
#include <string.h>

/**
 * @file Basic buffer implementation.
 */

typedef struct {
    unsigned char* data;
    size_t len;
    size_t cap;
} buf_t;

int buf_init(buf_t* buf, size_t capacity)
{
    buf->data = malloc(sizeof(unsigned char) * capacity);
    if(buf->data == NULL)
        return 0;
    buf->cap = capacity;
    buf->len = 0;
    return 1;
}

int buf_expand(buf_t* buf, size_t amnt)
{
    buf->cap += amnt;
    buf->data = realloc(buf->data, buf->cap);
    if(buf->data == NULL)
        return 0;
    return 1;
}

int buf_append(buf_t* buf, unsigned char* apd, size_t size)
{
    if((buf-> cap - buf->len) < size) {
        if(!buf_expand(buf, size + 20))
            return 0;
    }
    memcpy(buf->data, apd, size);
    buf->len += size;
    return 1;
}
/**
 * Convenince macro for putting just one byte
 */
#define BUF_PUT(buf, byte) (buf->cap == buf->len ? buf_expand(buf, 10) && (buf->data[buf->len++] = byte) : buf->data[buf->len++] = byte)

int main(int agrc, char const* argv[])
{
    return 0;
}