| 21 | }; |
| 22 | |
| 23 | class StreamReader { |
| 24 | public: |
| 25 | // Constructor: takes memory address, length, and endianness |
| 26 | StreamReader(const uint8_t* data, size_t length, Endian endian = Endian::Little) |
| 27 | : data_(data), length_(length), pos_(0), endian_(endian) { |
| 28 | // Detect native endian |
| 29 | uint16_t test = 0x0001; |
| 30 | native_is_little_ = (*reinterpret_cast<uint8_t*>(&test) == 0x01); |
| 31 | |
| 32 | // Determine if we need to swap bytes |
| 33 | if (endian_ == Endian::Native) { |
| 34 | needs_swap_ = false; |
| 35 | } else { |
| 36 | bool data_is_little = (endian_ == Endian::Little); |
| 37 | needs_swap_ = (data_is_little != native_is_little_); |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | // Read n bytes into destination buffer |
| 42 | // Returns false on out-of-bounds or error |
| 43 | bool read(size_t n, uint8_t* dst) { |
| 44 | if (!dst || n == 0) { |
| 45 | return false; |
| 46 | } |
| 47 | if (pos_ + n > length_) { |
| 48 | return false; // Out of bounds |
| 49 | } |
| 50 | std::memcpy(dst, data_ + pos_, n); |
| 51 | pos_ += n; |
| 52 | return true; |
| 53 | } |
| 54 | |
| 55 | // Read 1 byte (uint8_t) |
| 56 | bool read1(uint8_t* dst) { |
| 57 | return read(1, dst); |
| 58 | } |
| 59 | |
| 60 | // Read 2 bytes (uint16_t) with endian swap if needed |
| 61 | bool read2(uint16_t* dst) { |
| 62 | if (!dst) { |
| 63 | return false; |
| 64 | } |
| 65 | uint8_t buf[2]; |
| 66 | if (!read(2, buf)) { |
| 67 | return false; |
| 68 | } |
| 69 | |
| 70 | if (needs_swap_) { |
| 71 | *dst = static_cast<uint16_t>(buf[1]) << 8 | |
| 72 | static_cast<uint16_t>(buf[0]); |
| 73 | } else { |
| 74 | std::memcpy(dst, buf, 2); |
| 75 | } |
| 76 | return true; |
| 77 | } |
| 78 | |
| 79 | // Read 4 bytes (uint32_t) with endian swap if needed |
| 80 | bool read4(uint32_t* dst) { |
nothing calls this directly
no outgoing calls
no test coverage detected