From b55df0b8e46f46fea4d69f98a729cd237d77a6ed Mon Sep 17 00:00:00 2001 From: Trygve Laugstøl Date: Tue, 10 Feb 2015 21:29:19 +0100 Subject: o wip. --- ByteBuffer.cpp | 54 +++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 39 insertions(+), 15 deletions(-) (limited to 'ByteBuffer.cpp') diff --git a/ByteBuffer.cpp b/ByteBuffer.cpp index 9714c8c..70b9a8e 100644 --- a/ByteBuffer.cpp +++ b/ByteBuffer.cpp @@ -1,38 +1,62 @@ #include "ByteBuffer.h" -#include +#include +#include using namespace std; -ByteBuffer::ByteBuffer(uint8_t *bytes, ssize_t size, ssize_t zero) : - bytes(bytes), size(size), ptr(zero), zero(zero) { +ByteBuffer::ByteBuffer(uint8_t *bytes, size_t capacity, size_t size, size_t zero) : + bytes(bytes), capacity(capacity), size(size), cursor(zero), zero(zero) { } ByteBuffer &ByteBuffer::add8(uint8_t value) { - canAccessNextBytes(1); - bytes[zero + ptr++] = value; + checkAndUpdateSize(1); + bytes[zero + cursor++] = value; return *this; } ByteBuffer &ByteBuffer::add16le(uint16_t value) { - canAccessNextBytes(2); - bytes[zero + ptr++] = (uint8_t) (value & 0xff); - bytes[zero + ptr++] = (uint8_t) ((value >> 8) & 0xff); + checkAndUpdateSize(2); + bytes[zero + cursor++] = (uint8_t) (value & 0xff); + bytes[zero + cursor++] = (uint8_t) ((value >> 8) & 0xff); return *this; } -uint8_t ByteBuffer::get8(ssize_t index) { +uint8_t ByteBuffer::get8(size_t index) { canAccessIndex(index); - return bytes[zero + ptr]; + return bytes[zero + cursor]; } -void ByteBuffer::canAccessNextBytes(ssize_t newBytes) { - if (zero + ptr + newBytes >= size) { - throw exception(); +uint8_t ByteBuffer::get8() { + canAccessIndex(cursor); + return bytes[zero + cursor++]; +} + +uint16_t ByteBuffer::get16le() { + canAccessIndex(cursor + 1); + uint16_t value; + value = bytes[zero + cursor++]; + value = ((uint16_t) bytes[zero + cursor++]) << 8; + return value; +} + +void ByteBuffer::copy(uint8_t *bytes, size_t length) { + canAccessIndex(cursor + length); + + memcpy(bytes, &this->bytes[zero + cursor], length); + cursor += length; +} + +void ByteBuffer::checkAndUpdateSize(size_t newBytes) { + size_t newSize = zero + cursor + newBytes; + if (newSize >= capacity) { + throw ByteBufferException(string("Out of bounds! zero=") + to_string(zero) + ", cursor=" + to_string(cursor) + ", size=" + to_string(size) + ", capacity=" + to_string(capacity) + ", newSize=" + to_string(newSize)); } + + size = max(newSize, size); } -void ByteBuffer::canAccessIndex(ssize_t index) { +void ByteBuffer::canAccessIndex(size_t index) { if (zero + index >= size) { - throw exception(); + throw ByteBufferException(string("Out of bounds! zero=") + to_string(zero) + ", index=" + to_string(index) + ", size=" + to_string(size)); } } -- cgit v1.2.3