unsigned char array

Dependents:   MGC3130 SmartLabXBeeCore

BufferedArray.cpp

Committer:
yangcq88517
Date:
2015-11-12
Revision:
1:77c1ea04eb5a
Parent:
0:b35da77c40ca
Child:
2:765da30c4d9b

File content as of revision 1:77c1ea04eb5a:

#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(position - max + 1);

    data[position] = value;
}

void BufferedArray::set(unsigned char value)
{
    set(index, value);
    index++;
}

void BufferedArray::sets(const unsigned char * value, int offset, int length)
{
    if (length <= 0)
        return;

    sets(index, value, offset, length);
    index += length;
}

void BufferedArray::sets(int position, const unsigned char * value, int offset, int length)
{
    if (position < 0)
        return;

    if (length <= 0)
        return;

    if (position + length > max)
        expandSpace(position + length - max);

    memcpy(data + position, value, length);
}