aboutsummaryrefslogtreecommitdiff
path: root/sibs/SafeSerializer.hpp
blob: 72ef5a3bdd94d135626fe8a04e4a67ee825e5002 (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
#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(){}
        
        template <typename T>
        void add(const T &data)
        {
            usize offset = buffer.size();
            buffer.resize(buffer.size() + sizeof(T));
            #ifdef LITTLE_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
            memcpy(&buffer[offset], &data, sizeof(T));
            #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;
    };
}