1
2
3
4
5
6 #include <soulng/util/MemoryWriter.hpp>
7 #include <stdexcept>
8
9 namespace soulng { namespace util {
10
11 MemoryWriter::MemoryWriter(uint8_t* ptr_, int64_t count_) : ptr(ptr_), pos(ptr), count(count_)
12 {
13 }
14
15 void MemoryWriter::Write(uint8_t x)
16 {
17 if (pos - ptr >= count)
18 {
19 throw std::runtime_error("memory writer: end of space");
20 }
21 *pos++ = x;
22 }
23
24 void MemoryWriter::Write(int8_t x)
25 {
26 Write(static_cast<uint8_t>(x));
27 }
28
29 void MemoryWriter::Write(uint16_t x)
30 {
31 uint8_t b0 = static_cast<uint8_t>(x >> 8u);
32 uint8_t b1 = static_cast<uint8_t>(x);
33 Write(b0);
34 Write(b1);
35 }
36
37 void MemoryWriter::Write(int16_t x)
38 {
39 Write(static_cast<uint16_t>(x));
40 }
41
42 void MemoryWriter::Write(uint32_t x)
43 {
44 uint8_t b0 = static_cast<uint8_t>(x >> 24u);
45 uint8_t b1 = static_cast<uint8_t>(x >> 16u);
46 uint8_t b2 = static_cast<uint8_t>(x >> 8u);
47 uint8_t b3 = static_cast<uint8_t>(x);
48 Write(b0);
49 Write(b1);
50 Write(b2);
51 Write(b3);
52 }
53
54 void MemoryWriter::Write(int32_t x)
55 {
56 Write(static_cast<uint32_t>(x));
57 }
58
59 void MemoryWriter::Write(uint64_t x)
60 {
61 uint8_t b0 = static_cast<uint8_t>(x >> 56u);
62 uint8_t b1 = static_cast<uint8_t>(x >> 48u);
63 uint8_t b2 = static_cast<uint8_t>(x >> 40u);
64 uint8_t b3 = static_cast<uint8_t>(x >> 32u);
65 uint8_t b4 = static_cast<uint8_t>(x >> 24u);
66 uint8_t b5 = static_cast<uint8_t>(x >> 16u);
67 uint8_t b6 = static_cast<uint8_t>(x >> 8u);
68 uint8_t b7 = static_cast<uint8_t>(x);
69 Write(b0);
70 Write(b1);
71 Write(b2);
72 Write(b3);
73 Write(b4);
74 Write(b5);
75 Write(b6);
76 Write(b7);
77 }
78
79 void MemoryWriter::Write(int64_t x)
80 {
81 Write(static_cast<uint64_t>(x));
82 }
83
84 void MemoryWriter::Write(const DateTime& dt)
85 {
86 Date date = dt.GetDate();
87 Write(date.Year());
88 Write(static_cast<int8_t>(date.GetMonth()));
89 Write(date.Day());
90 Write(dt.Seconds());
91 }
92
93 } }