Zane Shelley | d26298b | 2021-01-28 16:49:19 -0600 | [diff] [blame] | 1 | #include <util/bin_stream.hpp> |
| 2 | |
| 3 | #include "gtest/gtest.h" |
| 4 | |
| 5 | enum RegisterId_t : uint32_t; // Defined in hei_types.hpp |
| 6 | |
| 7 | namespace util |
| 8 | { |
| 9 | |
| 10 | /** @brief Extracts big-endian data to host RegisterId_t. */ |
| 11 | template <> |
| 12 | inline BinFileReader& BinFileReader::operator>>(RegisterId_t& r) |
| 13 | { |
| 14 | // A register ID is only 3 bytes, but there isn't a 3-byte integer type. |
| 15 | // So extract 3 bytes to a uint32_t and drop the unused byte. |
| 16 | uint32_t tmp = 0; |
| 17 | read(&tmp, 3); |
| 18 | r = static_cast<RegisterId_t>(be32toh(tmp) >> 8); |
| 19 | return *this; |
| 20 | } |
| 21 | |
| 22 | /** @brief Inserts host RegisterId_t to big-endian data. */ |
| 23 | template <> |
| 24 | inline BinFileWriter& BinFileWriter::operator<<(RegisterId_t r) |
| 25 | { |
| 26 | // A register ID is only 3 bytes, but there isn't a 3-byte integer type. |
| 27 | // So extract 3 bytes to a uint32_t and drop the unused byte. |
| 28 | uint32_t tmp = htobe32(static_cast<uint32_t>(r) << 8); |
| 29 | write(&tmp, 3); |
| 30 | return *this; |
| 31 | } |
| 32 | |
| 33 | } // namespace util |
| 34 | |
| 35 | TEST(BinStream, TestSet1) |
| 36 | { |
| 37 | uint8_t w1 = 0x11; |
| 38 | uint16_t w2 = 0x1122; |
| 39 | uint32_t w3 = 0x11223344; |
| 40 | uint64_t w4 = 0x1122334455667788; |
| 41 | RegisterId_t w5 = static_cast<RegisterId_t>(0x123456); |
| 42 | |
| 43 | { |
| 44 | // need scope so the writer is closed before the reader opens |
| 45 | util::BinFileWriter w{"bin_stream_test.bin"}; |
| 46 | ASSERT_TRUE(w.good()); |
| 47 | |
| 48 | w << w1 << w2 << w3 << w4 << w5; |
| 49 | ASSERT_TRUE(w.good()); |
| 50 | } |
| 51 | |
| 52 | uint8_t r1; |
| 53 | uint16_t r2; |
| 54 | uint32_t r3; |
| 55 | uint64_t r4; |
| 56 | RegisterId_t r5; |
| 57 | |
| 58 | { |
| 59 | util::BinFileReader r{"bin_stream_test.bin"}; |
| 60 | ASSERT_TRUE(r.good()); |
| 61 | |
| 62 | r >> r1 >> r2 >> r3 >> r4 >> r5; |
| 63 | ASSERT_TRUE(r.good()); |
| 64 | } |
| 65 | |
| 66 | ASSERT_EQ(w1, r1); |
| 67 | ASSERT_EQ(w2, r2); |
| 68 | ASSERT_EQ(w3, r3); |
| 69 | ASSERT_EQ(w4, r4); |
| 70 | ASSERT_EQ(w5, r5); |
| 71 | } |