1 // =================================
 2 // Copyright (c) 2021 Seppo Laakko
 3 // Distributed under the MIT license
 4 // =================================
 5 
 6 namespace System
 7 {
 8     public class MemoryWriter
 9     {
10         public nothrow MemoryWriter(byte* ptr_long count_) : ptr(ptr_)pos(ptr)count(count_)
11         {
12         }
13         public void Write(byte x)
14         {
15             if (pos - ptr >= count)
16             {
17                 throw Exception("memory writer: end of space");
18             }
19             *pos++ = x;
20         }
21         public void Write(sbyte x)
22         {
23             Write(cast<byte>(x));
24         }
25         public void Write(ushort x)
26         {
27             byte b0 = cast<byte>(x >> 8u);
28             byte b1 = cast<byte>(x);
29             Write(b0);
30             Write(b1);
31         }
32         public void Write(short x)
33         {
34             Write(cast<ushort>(x));
35         }
36         public void Write(uint x)
37         {
38             byte b0 = cast<byte>(x >> 24u);
39             byte b1 = cast<byte>(x >> 16u);
40             byte b2 = cast<byte>(x >> 8u);
41             byte b3 = cast<byte>(x);
42             Write(b0);
43             Write(b1);
44             Write(b2);
45             Write(b3);
46         }
47         public void Write(int x)
48         {
49             Write(cast<uint>(x));
50         }
51         public void Write(ulong x)
52         {
53             byte b0 = cast<byte>(x >> 56u);
54             byte b1 = cast<byte>(x >> 48u);
55             byte b2 = cast<byte>(x >> 40u);
56             byte b3 = cast<byte>(x >> 32u);
57             byte b4 = cast<byte>(x >> 24u);
58             byte b5 = cast<byte>(x >> 16u);
59             byte b6 = cast<byte>(x >> 8u);
60             byte b7 = cast<byte>(x);
61             Write(b0);
62             Write(b1);
63             Write(b2);
64             Write(b3);
65             Write(b4);
66             Write(b5);
67             Write(b6);
68             Write(b7);
69         }
70         public void Write(long x)
71         {
72             Write(cast<ulong>(x));
73         }
74         public void Write(const DateTime& dt)
75         {
76             Date d = dt.GetDate();
77             Write(d.Year());
78             Write(cast<sbyte>(d.GetMonth()));
79             Write(d.Day());
80             Write(dt.Seconds());
81         }
82         public void Write(const string& s)
83         {
84             for (char c : s)
85             {
86                 Write(cast<byte>(c));
87             }
88             Write(cast<byte>(0u));
89         }
90         private byte* ptr;
91         private byte* pos;
92         private long count;
93     }
94 }