#include "ByteBuffer.h" #include #include using namespace std; 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) { checkAndUpdateSize(1); bytes[zero + cursor++] = value; return *this; } ByteBuffer &ByteBuffer::add16le(uint16_t value) { checkAndUpdateSize(2); bytes[zero + cursor++] = (uint8_t) (value & 0xff); bytes[zero + cursor++] = (uint8_t) ((value >> 8) & 0xff); return *this; } uint8_t ByteBuffer::get8(size_t index) { canAccessIndex(index); return bytes[zero + cursor]; } 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(size_t index) { if (zero + index >= size) { throw ByteBufferException(string("Out of bounds! zero=") + to_string(zero) + ", index=" + to_string(index) + ", size=" + to_string(size)); } }