blob: 957605358158bf336db1f64190a880e4e3e36e75 (
plain)
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
|
#pragma once
#include "endian.hpp"
#include "types.hpp"
#include "../utils.hpp"
#include <vector>
#include <cstring>
namespace sibs
{
/**
* Endian independent serializer
*/
class SafeSerializer
{
DISABLE_COPY(SafeSerializer);
public:
SafeSerializer(){}
SafeSerializer(SafeSerializer &&other)
{
buffer = std::move(other.buffer);
}
template <typename T>
void add(const T &data)
{
usize offset = buffer.size();
buffer.resize(buffer.size() + sizeof(T));
#if BYTE_ORDER == BIG_ENDIAN
switch(sizeof(T))
{
case 1:
*(T*)&buffer[offset] = data;
break;
case 2:
*(u16*)&buffer[offset] = byteswap(*(u16*)&data);
break;
case 4:
*(u32*)&buffer[offset] = byteswap(*(u32*)&data);
break;
case 8:
*(u64*)&buffer[offset] = byteswap(*(u64*)&data);
break;
default:
{
for(int i = 0; i < sizeof(T); ++i)
{
buffer[offset + i] = ((char*)&data)[sizeof(T) - 1 - i];
}
break;
}
}
#else
*(T*)&buffer[offset] = data;
#endif
}
void add(const u8 *data, usize size)
{
if(size > 0)
{
usize offset = buffer.size();
buffer.resize(buffer.size() + size);
memcpy(&buffer[offset], data, size);
}
}
std::vector<u8>& getBuffer()
{
return buffer;
}
private:
std::vector<u8> buffer;
};
}
|