diff --git a/include/patty/buffer.h b/include/patty/buffer.h new file mode 100644 index 0000000..def1b6b --- /dev/null +++ b/include/patty/buffer.h @@ -0,0 +1,16 @@ +#ifndef _PATTY_BUFFER_H +#define _PATTY_BUFFER_H + +typedef struct _patty_buffer patty_buffer; + +patty_buffer *patty_buffer_new(size_t size); + +void patty_buffer_destroy(patty_buffer *buffer); + +void *patty_buffer_data(patty_buffer *buffer); + +ssize_t patty_buffer_fill(patty_buffer *buffer, void *data, size_t len); + +void patty_buffer_flush(patty_buffer *buffer, size_t len); + +#endif /* _PATTY_BUFFER_H */ diff --git a/src/Makefile b/src/Makefile index 9de3dc8..d06d56b 100644 --- a/src/Makefile +++ b/src/Makefile @@ -7,10 +7,11 @@ CC = $(CROSS)cc CFLAGS = $(CGFLAGS) -fPIC -Wall -O2 -I$(INCLUDE_PATH) LDFLAGS = -HEADERS = kiss.h ax25.h ax25/if.h ax25/macros.h ax25/proto.h \ +HEADERS = buffer.h kiss.h ax25.h ax25/if.h ax25/macros.h ax25/proto.h \ ax25/address.h ax25/frame.h list.h hash.h dict.h -OBJS = kiss.o ax25.o if.o address.o frame.o list.o hash.o dict.o +OBJS = buffer.o kiss.o ax25.o if.o address.o frame.o \ + list.o hash.o dict.o EXAMPLES = iflist decode diff --git a/src/buffer.c b/src/buffer.c new file mode 100644 index 0000000..9d0f1bc --- /dev/null +++ b/src/buffer.c @@ -0,0 +1,81 @@ +#include +#include +#include +#include + +#include + +struct _patty_buffer { + void * data; + size_t size; + size_t len; +}; + +patty_buffer *patty_buffer_new(size_t size) { + patty_buffer *buffer; + + if ((buffer = malloc(sizeof(*buffer))) == NULL) { + goto error_malloc_buffer; + } + + if ((buffer->data = malloc(size)) == NULL) { + goto error_malloc_buffer_data; + } + + buffer->size = size; + buffer->len = 0; + + return buffer; + +error_malloc_buffer_data: + free(buffer); + +error_malloc_buffer: + return NULL; +} + +void patty_buffer_destroy(patty_buffer *buffer) { + free(buffer->data); + free(buffer); +} + +void *patty_buffer_data(patty_buffer *buffer) { + return buffer->data; +} + +ssize_t patty_buffer_fill(patty_buffer *buffer, void *data, size_t len) { + if (len == 0) { + return 0; + } + + if (len > buffer->size - buffer->len) { + errno = EIO; + + goto error_io; + } + + memcpy(((unsigned char *)buffer->data) + buffer->len, data, len); + + buffer->len += len; + + return len; + +error_io: + return -1; +} + +void patty_buffer_flush(patty_buffer *buffer, size_t len) { + /* + * Move everything from the buffer not processed up to this point, to the + * beginning of the buffer. + */ + memmove(buffer->data, + ((unsigned char *)buffer->data) + len, + buffer->len - len); + + /* + * Then, decrement the buffer length by the number of bytes already + * processed. + */ + buffer->len -= len; +}