#include <stdlib.h>
#include <string.h>
+#include <stddef.h>
#include "GrowingBuffer.h"
GrowingBuffer::GrowingBuffer(size_t initialSize) {
- this->data = malloc(1024);
- this->size = 1024;
+ this->data = malloc(initialSize);
+ this->size = initialSize;
this->limit = 0;
this->position = 0;
}
void* GrowingBuffer::read(void* buffer, size_t length) {
size_t bytesToCopy = (length > (limit - position)) ? (limit - position) : length;
- memcpy(buffer, (char*) data + position, bytesToCopy);
+ memcpy(buffer, (ptrdiff_t*) data + position, bytesToCopy);
position += bytesToCopy;
return buffer;
}
void GrowingBuffer::write(const void* buffer, size_t length) {
- if (length > (size - position)) {
+ if (length > (size - limit)) {
int newSize = size;
do {
newSize *= 2;
- } while (length > (newSize - position));
+ } while (length > (newSize - limit));
void* newData = malloc(newSize);
memcpy(newData, data, position);
free(data);
data = newData;
}
- memcpy((char*) data + position, buffer, length);
+ memcpy((ptrdiff_t*) data + limit, buffer, length);
+ limit += length;
+}
+
+void GrowingBuffer::cut() {
+ memcpy(data, (ptrdiff_t*) data + position, position);
+ limit = position;
+ position = 0;
}
void GrowingBuffer::truncate() {