aboutsummaryrefslogtreecommitdiff
path: root/sibs/SafeDeserializer.hpp
blob: 3d830420d1fa52925ab052eed0e3d98a8ee58745 (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
#pragma once

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

namespace sibs
{
    class DeserializeException : public std::runtime_error
    {
    public:
        DeserializeException(const std::string &errMsg) : std::runtime_error(errMsg) {}
    };
    
    /**
     * Endian independent deserializer
     */
    class SafeDeserializer
    {
        DISABLE_COPY(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;
            memcpy(&result, data, typeSize);
            data += typeSize;
            return std::move(result);
        }
        
        /*
         * Throws DeserializeException on failure
         */
        void extract(u8 *destination, usize destinationSize)
        {
            if(destinationSize > 0)
            {
                verifyExtractSize(destinationSize);
                size -= destinationSize;
                memcpy(destination, data, destinationSize);
                data += destinationSize;
            }
        }
        
        bool empty() const
        {
            return size == 0;
        }
        
        const u8* getBuffer()
        {
            return data;
        }
        
        usize getSize() const
        {
            return size;
        }
    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;
    };
}