aboutsummaryrefslogtreecommitdiff
path: root/sibs/SafeDeserializer.hpp
blob: 57d2eeea55ae5856d947e7f481e01e1369278317 (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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#pragma once

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

namespace sibs
{
    class DeserializeException : public std::runtime_error
    {
    public:
        DeserializeException(const std::string &errMsg) : std::runtime_error(errMsg) {}
    };
    
    /**
     * Endian independent deserializer
     */
    class SafeDeserializer
    {
    public:
        SafeDeserializer(const u8 *_data, usize _size) : 
            data(_data),
            size(_size)
        {
            
        }
        
        /*
         * Throws DeserializeException on failure
         */
        template <typename T>
        T extract()
        {
            constexpr usize typeSize = sizeof(T);
            verifyExtractSize(typeSize);
            size -= typeSize;
            T result;
            memmove(&result, data, typeSize);
            #if BYTE_ORDER == BIG_ENDIAN
            std::reverse((char*)&result, (char*)&result + typeSize);
            #endif
            data += typeSize;
            return result;
        }
        
        /*
         * Throws DeserializeException on failure
         */
        void extract(u8 *destination, usize destinationSize)
        {
            if(destinationSize > 0)
            {
                verifyExtractSize(destinationSize);
                size -= destinationSize;
                memmove(destination, data, destinationSize);
                data += destinationSize;
            }
        }
        
        bool empty() const
        {
            return size == 0;
        }
        
        const u8* getBuffer()
        {
            return data;
        }
        
        usize getSize() const
        {
            return size;
        }

        void skip(usize bytesToSkip)
        {
            bytesToSkip = bytesToSkip < size ? bytesToSkip : size;
            size -= bytesToSkip;
            data += bytesToSkip;
        }
    private:
        void verifyExtractSize(usize typeSize) const
        {
            if(typeSize > size)
            {
                std::string errMsg = "Unable to extract ";
                errMsg += std::to_string(typeSize);
                errMsg += " bytes, only ";
                errMsg += std::to_string(size);
                errMsg += " bytes left in buffer";
                throw DeserializeException(errMsg);
            }
        }
    private:
        const u8 *data;
        usize size;
    };
}