Implement src/buffer.c

This commit is contained in:
XANTRONIX Development 2015-09-17 23:25:30 -05:00 committed by XANTRONIX Industrial
parent 1666666e9d
commit 82d94fb5ad
3 changed files with 100 additions and 2 deletions

16
include/patty/buffer.h Normal file
View file

@ -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 */

View file

@ -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

81
src/buffer.c Normal file
View file

@ -0,0 +1,81 @@
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <errno.h>
#include <patty/buffer.h>
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;
}