aboutsummaryrefslogtreecommitdiff
path: root/sibs/SafeSerializer.hpp
blob: 95e78079f50bfc78d32bf445c17e17a9ab524f28 (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
#pragma once

#include "endian.hpp"
#include "types.hpp"
#include "../utils.hpp"
#include <vector>
#include <cstring>
#include <algorithm>

namespace sibs
{
    /**
     * Endian independent serializer
     */
    class SafeSerializer
    {
    public:
        SafeSerializer(){}
        SafeSerializer(SafeSerializer &&other)
        {
            buffer = std::move(other.buffer);
        }
        
        template <typename T>
        void add(const T &data)
        {
            usize offset = buffer.size();
            (void)offset;
            buffer.insert(buffer.end(), (unsigned char*)&data, (unsigned char*)&data + sizeof(T));
            #if BYTE_ORDER == BIG_ENDIAN
            std::reverse((char*)&buffer[offset], (char*)&buffer[offset] + sizeof(T));
            #endif
        }
        
        void add(const u8 *data, usize size)
        {
            if(size > 0)
            {
                usize offset = buffer.size();
                buffer.resize(buffer.size() + size);
                memmove(&buffer[offset], data, size);
            }
        }

        void add(const char *data, usize size)
        {
            add((const u8*)data, size);
        }
        
        std::vector<u8>& getBuffer()
        {
            return buffer;
        }

        usize getSize() const
        {
            return buffer.size();
        }
    private:
        std::vector<u8> buffer;
    };
}