-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathByteArraySerialization.cpp
More file actions
66 lines (50 loc) · 1.98 KB
/
ByteArraySerialization.cpp
File metadata and controls
66 lines (50 loc) · 1.98 KB
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
/*******************************************************************************
* Rohan data serialization library.
* Byte array serialization
*
* © 2016—2024, Sauron
******************************************************************************/
#include <cstring>
#include "ByteArraySerialization.hpp"
using namespace rohan;
using std::vector;
/******************************************************************************/
ByteArrayReader::ByteArrayReader(const char * data) :
data(data), length(strlen(data)), offset(0) {}
ByteArrayReader::ByteArrayReader(const void * data, size_t length) :
data(data), length(length), offset(0) {}
ByteArrayReader::ByteArrayReader(const vector<uint8_t> &buffer,
size_t offset) : data(buffer.data()), length(buffer.size()), offset(offset) {}
size_t ByteArrayReader::read(void * to, size_t length) {
if (available()<length)
length=available();
memcpy(to, reinterpret_cast<const uint8_t *>(data)+offset, length);
offset+=length;
return length;
}
size_t ByteArrayReader::skip(size_t length) {
size_t skipped=available()<length?available():length;
offset+=skipped;
return skipped;
}
size_t ByteArrayReader::available() const {
return length-offset;
}
/******************************************************************************/
static void appendTo(vector<uint8_t> &buffer, const void * from, size_t length) {
size_t oldSize=buffer.size();
buffer.resize(oldSize+length);
memcpy(&buffer[oldSize], from, length);
}
ByteArrayWriter::ByteArrayWriter(size_t capacity) {
buffer.reserve(capacity);
}
void ByteArrayWriter::write(const void * from, size_t length) {
appendTo(buffer, from, length);
}
/*******************************************************************************/
ByteArrayRefWriter::ByteArrayRefWriter(vector<uint8_t> &buffer) :
buffer(buffer) {}
void ByteArrayRefWriter::write(const void * from, size_t length) {
appendTo(buffer, from, length);
}