unsigned char array

Dependents:   MGC3130 SmartLabXBeeCore

Revision:
0:b35da77c40ca
Child:
1:77c1ea04eb5a
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/BufferedArray.cpp	Wed Nov 11 18:33:41 2015 +0000
@@ -0,0 +1,122 @@
+#include "BufferedArray.h"
+
+BufferedArray::BufferedArray(int initialLength, int expandSize)
+{
+    this->expandSize = expandSize;
+    max = initialLength;
+    data = new unsigned char[initialLength];
+    index = 0;
+}
+
+BufferedArray::BufferedArray(BufferedArray * bufferedArray)
+{
+    if (bufferedArray != NULL) {
+        this->data = bufferedArray->data;
+        this->index = bufferedArray->index;
+        this->max = bufferedArray->max;
+        this->expandSize = bufferedArray->expandSize;
+    }
+}
+
+BufferedArray::~BufferedArray()
+{
+    if (data == NULL)
+        return;
+
+    delete[] data;
+}
+
+unsigned char * BufferedArray::gets()
+{
+    return data;
+}
+
+unsigned char * BufferedArray::gets(int position)
+{
+    return data + position;
+}
+
+unsigned char BufferedArray::get(int position)
+{
+    return *(data + position);
+}
+
+int BufferedArray::getPosition()
+{
+    return index;
+}
+
+void BufferedArray::setPosition(int position)
+{
+    if (this->index > max)
+        this->index = max;
+    else this->index = position;
+}
+
+void BufferedArray::allocate(int length)
+{
+    if (length <= 0)
+        return;
+
+    if (length > max) {
+        if (data != NULL)
+            delete[] data;
+        data = new unsigned char[length];
+    }
+
+    rewind();
+}
+
+void BufferedArray::rewind()
+{
+    index = 0;
+}
+
+void BufferedArray::expandSpace(int length)
+{
+    max += expandSize * (1 + length / expandSize);
+    unsigned char * temp = new unsigned char[max];
+    memcpy(temp, data, index);
+    delete[] data;
+    data = temp;
+}
+
+void BufferedArray::set(int position, unsigned char value)
+{
+    if (position < 0)
+        return;
+
+    if (position >= max)
+        expandSpace(1);
+
+    data[position] = value;
+}
+
+void BufferedArray::set(unsigned char value)
+{
+    set(index, value);
+    index++;
+}
+
+void BufferedArray::sets(const void * value, int length)
+{
+    if (length <= 0)
+        return;
+
+    sets(index, value, length);
+    index += length;
+}
+
+void BufferedArray::sets(int position, const void * value, int length)
+{
+    if (position < 0)
+        return;
+
+    if (length <= 0)
+        return;
+
+    if (position + length > max)
+        expandSpace(position + length - max);
+
+    memcpy(data + index, value, length);
+}
\ No newline at end of file