-
Notifications
You must be signed in to change notification settings - Fork 1
/
buffer.cpp
107 lines (87 loc) · 2.31 KB
/
buffer.cpp
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
#include "buffer.h"
Buffer::Buffer() : readPosition_(0), writePosition_(0) { }
Buffer::Buffer(const QByteArray& data)
: readPosition_(0), writePosition_(0), data_(data) { }
unsigned char Buffer::readByte()
{
if (bytesAvailable() < 1) {
throw new EOFException();
}
return data_.constData()[readPosition_++];
}
short Buffer::readShort()
{
if ((uint) bytesAvailable() < sizeof(short)) {
throw new EOFException();
}
short ret = *(short*)&data_.constData()[readPosition_];
readPosition_ += sizeof(short);
return ret;
}
int Buffer::readInt()
{
if ((uint) bytesAvailable() < sizeof(int)) {
throw new EOFException();
}
int ret = *(int*)&data_.constData()[readPosition_];
readPosition_ += sizeof(int);
return ret;
}
float Buffer::readFloat()
{
if ((uint)bytesAvailable() < sizeof(float)) {
throw new EOFException();
}
float ret = *(float*)&data_.constData()[readPosition_];
readPosition_ += sizeof(float);
return ret;
}
double Buffer::readDouble()
{
if ((uint) bytesAvailable() < sizeof(double)) {
throw new EOFException();
}
double ret = *(double*)&data_.constData()[readPosition_];
readPosition_ += sizeof(double);
return ret;
}
QByteArray Buffer::read(const int maxLength)
{
int numRead = 0;
if ((numRead = bytesAvailable()) > maxLength) {
numRead = maxLength;
}
QByteArray ret = data_.mid(readPosition_, numRead);
readPosition_ += ret.size();
return ret;
}
void Buffer::writeByte(const unsigned char value)
{
data_ += value;
writePosition_++;
}
void Buffer::writeShort(const short value)
{
data_ += QByteArray::fromRawData((const char*)&value, sizeof(short));
writePosition_ += sizeof(short);
}
void Buffer::writeInt(const int value)
{
data_ += QByteArray::fromRawData((const char*)&value, sizeof(int));
writePosition_ += sizeof(int);
}
void Buffer::writeFloat(const float value)
{
data_ += QByteArray::fromRawData((const char*)&value, sizeof(float));
writePosition_ += sizeof(float);
}
void Buffer::writeDouble(const double value)
{
data_ += QByteArray::fromRawData((const char*)&value, sizeof(double));
writePosition_ += sizeof(double);
}
void Buffer::write(const QByteArray& value)
{
data_ += value;
writePosition_ += value.size();
}