add version information
[ecparse.git] / GrowingBuffer.cpp
1 /**
2  * © 2008 by David ‘Bombe’ Roden <bombe@pterodactylus.net>
3  */
4
5 #include <stdlib.h>
6 #include <string.h>
7 #include "GrowingBuffer.h"
8
9 GrowingBuffer::GrowingBuffer(size_t initialSize) {
10         this->data = malloc(1024);
11         this->size = 1024;
12         this->limit = 0;
13         this->position = 0;
14 }
15
16 GrowingBuffer::~GrowingBuffer() {
17         if (this->data) {
18                 free(this->data);
19         }
20 }
21
22 size_t GrowingBuffer::getPosition() {
23         return position;
24 }
25
26 size_t GrowingBuffer::getLimit() {
27         return limit;
28 }
29
30 size_t GrowingBuffer::getSize() {
31         return size;
32 }
33
34 void GrowingBuffer::seek(size_t position) {
35         this->position = (position > limit) ? limit : position;
36 }
37
38 void* GrowingBuffer::read(void* buffer, size_t length) {
39         size_t bytesToCopy = (length > (limit - position)) ? (limit - position) : length;
40         memcpy(buffer, (char*) data + position, bytesToCopy);
41         position += bytesToCopy;
42         return buffer;
43 }
44
45 void GrowingBuffer::write(const void* buffer, size_t length) {
46         if (length > (size - position)) {
47                 int newSize = size;
48                 do {
49                         newSize *= 2;
50                 } while (length > (newSize - position));
51                 void* newData = malloc(newSize);
52                 memcpy(newData, data, position);
53                 free(data);
54                 data = newData;
55         }
56         memcpy((char*) data + position, buffer, length);
57 }
58
59 void GrowingBuffer::truncate() {
60         limit = position;
61 }
62
63 void GrowingBuffer::clear() {
64         position = 0;
65         limit = 0;
66 }
67
68 void GrowingBuffer::resize(double factor) {
69         if (factor < 1.0) {
70                 factor = 1.0;
71         }
72         if (size != (limit * factor)) {
73                 void* newData = malloc((size_t) (limit * factor));
74                 memcpy(newData, data, limit);
75                 free(data);
76                 data = newData;
77         }
78 }
79