comparison include/core/byte_stream.h @ 364:99c961c91809

core: refactor out byte stream into its own file easy dubs
author Paper <paper@paper.us.eu.org>
date Tue, 16 Jul 2024 21:15:59 -0400
parents
children
comparison
equal deleted inserted replaced
363:f10507d8f686 364:99c961c91809
1 #ifndef MINORI_CORE_BYTE_STREAM_H_
2 #define MINORI_CORE_BYTE_STREAM_H_
3
4 #include "core/endian.h"
5
6 #include <string>
7 #include <vector>
8 #include <cstdint>
9 #include <type_traits>
10
11 struct ByteStream {
12 public:
13 enum class ByteOrder {
14 Little,
15 Big,
16 };
17
18 ByteStream(std::uint8_t *bytes, std::size_t size);
19
20 void ResetOffset();
21 void SetEndianness(ByteOrder endian);
22
23 template<typename T>
24 bool ReadBinary(T& ret) {
25 if (offset_ + sizeof(T) >= size_)
26 return false;
27
28 ret = *reinterpret_cast<T*>(bytes_ + offset_);
29 Advance(sizeof(T));
30 return true;
31 }
32
33 template<typename T>
34 bool ReadInt(T& ret) {
35 static_assert(std::is_integral<T>::value);
36
37 if (!ReadBinary<T>(ret))
38 return false;
39
40 switch (endian_) {
41 case ByteOrder::Little:
42 if constexpr (std::is_unsigned<T>::value) {
43 ret = Endian::byteswap_little_to_host(ret);
44 } else {
45 ret = Endian::signed_byteswap_little_to_host(ret);
46 }
47 break;
48 case ByteOrder::Big:
49 if constexpr (std::is_unsigned<T>::value) {
50 ret = Endian::byteswap_big_to_host(ret);
51 } else {
52 ret = Endian::signed_byteswap_big_to_host(ret);
53 }
54 break;
55 default:
56 /* can't know for sure. punt */
57 return false;
58 }
59
60 return true;
61 }
62
63 bool ReadString(std::string& str, std::size_t size);
64 bool Advance(std::size_t amount);
65
66 private:
67 /* raw data */
68 std::uint8_t *bytes_ = nullptr;
69 std::size_t offset_ = 0;
70 std::size_t size_ = 0;
71
72 ByteOrder endian_ = ByteOrder::Little;
73 };
74
75 #endif /* MINORI_CORE_BYTE_STREAM_H_ */