-
Notifications
You must be signed in to change notification settings - Fork 0
/
bytestream.h
157 lines (125 loc) · 2.98 KB
/
bytestream.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
#ifndef BYTESTREAM_H
#define BYTESTREAM_H
#include <QtGlobal>
#include <QByteArray>
#include <QString>
class ByteStream
{
QByteArray::iterator curr;
QByteArray::iterator end;
quint64 space;
void expand(quint64 add)
{
data.resize(data.size() + add);
end = data.end();
space += add;
curr = data.begin() + data.size()-space;
}
public:
QByteArray data;
ByteStream(quint64 size = 0)
{
space = size;
data.resize(size);
curr = data.begin();
end = data.end();
}
ByteStream(const QByteArray& _data)
{
space = _data.size();
data = _data;
curr = data.begin();
end = data.end();
}
void skip(quint64 bytes)
{
if(space < bytes)
expand(bytes-space);
curr += bytes;
space -= bytes;
}
quint64 remaining(){return space;}
template <class T>
T readNumber()
{
quint64 buff = 0;
for(int i=0, shift = 0; i<sizeof(T); i++, curr++, shift+=8)
{
buff |= ((*curr) << shift);
}
space -= sizeof(T);
return *((T*)(&buff));
}
template <class T>
void writeNumber(T number)
{
if(space < sizeof(T))
expand(sizeof(T) - space);
for(int i=0; i<sizeof(T); i++, curr++, number>>=8)
{
*curr = number&0xFF;
}
space -= sizeof(T);
}
QString readString(quint32 len)
{
QByteArray out;
if(len > 0)
{
out.resize(len);
for(auto& c : out)
c = *(curr++);
}
else
{
do
{
out.push_back(*curr);
}while(*(curr++) != 0);
}
space -= len;
return out;
}
void writeString(QString str, qint32 len)
{
if(space < len)
expand(len - space);
str = str.left(len);
for(const auto& c : str.toLatin1())
{
writeNumber<quint8>(c);
}
len -= str.size();
while(len-- > 0)
writeNumber<quint8>(0);
}
QString readWString(qint32 len)
{
wchar_t* arr = new wchar_t[len];
wchar_t* iter = arr;
for(int i=0; i<len; i++, iter++)
{
*iter = readNumber<wchar_t>();
}
QString out = QString::fromWCharArray(arr);
delete[] arr;
space -= len*sizeof(wchar_t);
return out;
}
void writeWString(QString str, quint32 len)
{
int bytes = len * sizeof(wchar_t);
if(space < bytes) expand(bytes - space);
str = str.left(len);
wchar_t* arr = new wchar_t[str.size()];
wchar_t* iter = arr;
str.toWCharArray(arr);
for(int i=0; i<str.size(); i++, iter++)
writeNumber(*iter);
len -= str.size();
while(len-- > 0)
writeNumber<wchar_t>(0);
delete[] arr;
}
};
#endif // BYTESTREAM_H