This repository has been archived by the owner on Apr 18, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
/
data_reader.cc
80 lines (67 loc) · 1.73 KB
/
data_reader.cc
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
// Copyright 2009 Daniel Erat <dan@erat.org>
// All rights reserved.
#include "data_reader.h"
#include <arpa/inet.h>
using std::string;
namespace xsettingsd {
DataReader::DataReader(const char* buffer, size_t buf_len)
: buffer_(buffer),
buf_len_(buf_len),
bytes_read_(0),
reverse_bytes_(false) {
}
bool DataReader::ReadBytes(string* out, size_t size) {
if (bytes_read_ + size > buf_len_ ||
bytes_read_ + size < bytes_read_) {
return false;
}
if (out)
out->assign(buffer_ + bytes_read_, size);
bytes_read_ += size;
return true;
}
bool DataReader::ReadInt8(int8_t* out) {
if (bytes_read_ + sizeof(int8_t) > buf_len_ ||
bytes_read_ + sizeof(int8_t) < bytes_read_) {
return false;
}
if (out)
*out = *reinterpret_cast<const int8_t*>(buffer_ + bytes_read_);
bytes_read_ += sizeof(int8_t);
return true;
}
bool DataReader::ReadInt16(int16_t* out) {
if (bytes_read_ + sizeof(int16_t) > buf_len_ ||
bytes_read_ + sizeof(int16_t) < bytes_read_) {
return false;
}
if (out) {
*out = *reinterpret_cast<const int16_t*>(buffer_ + bytes_read_);
if (reverse_bytes_) {
if (IsLittleEndian())
*out = ntohs(*out);
else
*out = htons(*out);
}
}
bytes_read_ += sizeof(int16_t);
return true;
}
bool DataReader::ReadInt32(int32_t* out) {
if (bytes_read_ + sizeof(int32_t) > buf_len_ ||
bytes_read_ + sizeof(int32_t) < bytes_read_) {
return false;
}
if (out) {
*out = *reinterpret_cast<const int32_t*>(buffer_ + bytes_read_);
if (reverse_bytes_) {
if (IsLittleEndian())
*out = ntohl(*out);
else
*out = htonl(*out);
}
}
bytes_read_ += sizeof(int32_t);
return true;
}
} // namespace xsettingsd