]> git.xonotic.org Git - xonotic/netradiant.git/blob - libs/util/buffer.h
9ce31d62a472b0242cff24137c1b7c5bf409cca1
[xonotic/netradiant.git] / libs / util / buffer.h
1 #ifndef INCLUDED_BUFFER_H
2 #define INCLUDED_BUFFER_H
3
4 namespace u {
5
6     using byte = char;
7
8     using cstring = const char *;
9
10     namespace details {
11         struct Reference {
12         private:
13             int m_size;
14             byte *m_data;
15         public:
16             Reference(int m_size, byte *m_data)
17                     : m_size(m_size), m_data(m_data) {}
18
19             int size() const {
20                 return m_size;
21             }
22
23             const byte *data() const {
24                 return m_data;
25             }
26
27             byte *data() {
28                 return m_data;
29             }
30         };
31
32         template<int sz>
33         struct Value {
34             byte m_data[sz];
35
36             int size() const {
37                 return sz;
38             }
39
40             const byte *data() const {
41                 return m_data;
42             }
43
44             byte *data() {
45                 return m_data;
46             }
47         };
48     }
49
50     template<class Self>
51     class IBuffer : Self {
52         using Self::Self;
53     public:
54         operator const IBuffer<details::Reference>() const {
55             return IBuffer<details::Reference>{this->size(), const_cast<byte *>(this->data())};
56         }
57
58         cstring c_str() const {
59             return this->data();
60         }
61
62         operator byte *() {
63             return this->data();
64         }
65     };
66
67     template<int sz>
68     using BufferVal = IBuffer<details::Value<sz>>;
69
70     using Buffer = IBuffer<details::Reference>;
71
72     template<int sz>
73     BufferVal<sz> buffer() {
74         return BufferVal<sz>();
75     }
76
77 }
78
79 #endif