#include "ByteBuffer.h" #include #include #include #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) { assert(zero <= size); assert(size <= capacity); } ByteBuffer &ByteBuffer::add8(uint8_t value) { checkAndUpdateSize(1); bytes[cursor++] = value; return *this; } ByteBuffer &ByteBuffer::add16le(uint16_t value) { checkAndUpdateSize(2); bytes[cursor++] = (uint8_t) (value & 0xff); bytes[cursor++] = (uint8_t) ((value >> 8) & 0xff); return *this; } uint8_t ByteBuffer::get8(size_t index) { canAccessIndex(index); return bytes[cursor]; } uint8_t ByteBuffer::get8() { canAccessIndex(cursor); return bytes[cursor++]; } uint16_t ByteBuffer::get16le() { canAccessIndex(cursor + 1); uint16_t value; value = bytes[cursor++]; value |= ((uint16_t) bytes[cursor++]) << 8; return value; } void ByteBuffer::copy(uint8_t *bytes, size_t length) { canAccessIndex(length); memcpy(bytes, &this->bytes[cursor], length); cursor += length; } ByteBuffer ByteBuffer::view(size_t length) { canAccessIndex(cursor + length); size_t s = cursor + length; return ByteBuffer(bytes, s, s, cursor); } void ByteBuffer::checkAndUpdateSize(size_t newBytes) { size_t newSize = 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)); } } std::string ByteBuffer::toString() const { stringstream s; for(size_t i = zero; i < size; i++) { s << hex << setfill('0') << setw(2) << (int) bytes[i] << " "; } return string(s.str()); }