86 lines
2.0 KiB
C
86 lines
2.0 KiB
C
/**
|
|
* This is a buffer to store bytes for reading and writing.
|
|
*
|
|
* copyright: see file COPYRIGHT
|
|
*
|
|
* Mark Koennecke, January 2009
|
|
*/
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <stdio.h>
|
|
#include "rwpuffer.h"
|
|
/*----------------------------------------------------------------------*/
|
|
typedef struct __RWBuffer {
|
|
char *data;
|
|
int length;
|
|
int startPtr;
|
|
int endPtr;
|
|
} RWBuffer;
|
|
/*----------------------------------------------------------------------*/
|
|
prwBuffer MakeRWPuffer(int size)
|
|
{
|
|
prwBuffer self = NULL;
|
|
|
|
self = malloc(sizeof(RWBuffer));
|
|
if (self == NULL) {
|
|
return NULL;
|
|
}
|
|
self->data = calloc(size, sizeof(char));
|
|
if (self->data == NULL) {
|
|
return NULL;
|
|
}
|
|
self->length = size;
|
|
self->startPtr = 0;
|
|
self->endPtr = 0;
|
|
return self;
|
|
}
|
|
|
|
/*------------------------------------------------------------------------*/
|
|
void KillRWBuffer(prwBuffer self)
|
|
{
|
|
if (self == NULL) {
|
|
return;
|
|
}
|
|
if (self->data != NULL) {
|
|
free(self->data);
|
|
}
|
|
free(self);
|
|
}
|
|
|
|
/*------------------------------------------------------------------------*/
|
|
int StoreRWBuffer(prwBuffer self, void *data, int count)
|
|
{
|
|
int length;
|
|
|
|
length = self->endPtr - self->startPtr;
|
|
if (count + length >= self->length ) {
|
|
printf("HELP: RWBuffer overrun!!!!\n");
|
|
return 0;
|
|
}
|
|
if (count + self->endPtr > self->length) {
|
|
memmove(self->data, self->data + self->startPtr, length);
|
|
self->startPtr = 0;
|
|
self->endPtr = length;
|
|
}
|
|
memcpy(self->data + self->endPtr, data, count);
|
|
self->endPtr += count;
|
|
return 1;
|
|
}
|
|
|
|
/*------------------------------------------------------------------------*/
|
|
void *GetRWBufferData(prwBuffer self, int *length)
|
|
{
|
|
*length = self->endPtr - self->startPtr;
|
|
return (void *) self->data + self->startPtr;
|
|
}
|
|
|
|
/*-------------------------------------------------------------------------*/
|
|
void RemoveRWBufferData(prwBuffer self, int count)
|
|
{
|
|
self->startPtr += count;
|
|
if (self->startPtr >= self->endPtr) {
|
|
self->startPtr = 0;
|
|
self->endPtr = 0;
|
|
}
|
|
}
|