1
2
3
4
5
6 #include <soulng/util/MemoryReader.hpp>
7 #include <stdexcept>
8
9 namespace soulng { namespace util {
10
11 MemoryReader::MemoryReader(uint8_t* ptr_, int64_t count_) : ptr(ptr_), pos(ptr), count(count_)
12 {
13 }
14
15 uint8_t MemoryReader::ReadByte()
16 {
17 if (pos - ptr >= count)
18 {
19 throw std::runtime_error("memory reader: unexpected end of data");
20 }
21 return *pos++;
22 }
23
24 int8_t MemoryReader::ReadSByte()
25 {
26 return static_cast<int8_t>(ReadByte());
27 }
28
29 uint16_t MemoryReader::ReadUShort()
30 {
31 uint8_t b0 = ReadByte();
32 uint8_t b1 = ReadByte();
33 return (static_cast<uint16_t>(b0) << 8u) | static_cast<uint16_t>(b1);
34 }
35
36 int16_t MemoryReader::ReadShort()
37 {
38 return static_cast<int16_t>(ReadUShort());
39 }
40
41 uint32_t MemoryReader::ReadUInt()
42 {
43 uint8_t b0 = ReadByte();
44 uint8_t b1 = ReadByte();
45 uint8_t b2 = ReadByte();
46 uint8_t b3 = ReadByte();
47 return (static_cast<uint32_t>(b0) << 24u) | (static_cast<uint32_t>(b1) << 16u) | (static_cast<uint32_t>(b2) << 8u) | static_cast<uint32_t>(b3);
48 }
49
50 int32_t MemoryReader::ReadInt()
51 {
52 return static_cast<int32_t>(ReadUInt());
53 }
54
55 uint64_t MemoryReader::ReadULong()
56 {
57 uint8_t b0 = ReadByte();
58 uint8_t b1 = ReadByte();
59 uint8_t b2 = ReadByte();
60 uint8_t b3 = ReadByte();
61 uint8_t b4 = ReadByte();
62 uint8_t b5 = ReadByte();
63 uint8_t b6 = ReadByte();
64 uint8_t b7 = ReadByte();
65 return (static_cast<uint64_t>(b0) << 56u) | (static_cast<uint64_t>(b1) << 48u) | (static_cast<uint64_t>(b2) << 40u) | (static_cast<uint64_t>(b3) << 32u) |
66 (static_cast<uint64_t>(b4) << 24u) | (static_cast<uint64_t>(b5) << 16u) | (static_cast<uint64_t>(b6) << 8u) | static_cast<uint64_t>(b7);
67 }
68
69 int64_t MemoryReader::ReadLong()
70 {
71 return static_cast<int64_t>(ReadULong());
72 }
73
74 DateTime MemoryReader::ReadDateTime()
75 {
76 int16_t year = ReadShort();
77 Month month = static_cast<Month>(ReadSByte());
78 int8_t day = ReadSByte();
79 Date date(year, month, day);
80 int32_t secs = ReadInt();
81 DateTime dt(date, secs);
82 return dt;
83 }
84
85 } }