aboutsummaryrefslogtreecommitdiff
path: root/tests/main.cpp
blob: 0521e5018ec8ee91d274184828ef12a3fd857eb5 (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
#include <cstdio>
#include <cstdlib>
#include <sibs/SafeSerializer.hpp>
#include <sibs/SafeDeserializer.hpp>
#include <cstdint>

#define REQUIRE(statement) do { if(!(statement)) { fprintf(stderr, "Assertion failed:\n%s\n", #statement); exit(1); } } while(0)
#define FAIL(str) do { fprintf(stderr, "Failed:\n%s\n", (str)); exit(1); } while(0)

struct TestStruct
{
    uint32_t a;
    uint8_t b;
};

static TestStruct expectedTestStruct;

void testDeserialize(sibs::SafeSerializer &serializer)
{
    sibs::SafeDeserializer deserializer(serializer.getBuffer().data(), serializer.getBuffer().size());
    REQUIRE(deserializer.extract<uint32_t>() == 3563634);
    REQUIRE(deserializer.extract<uint64_t>() == 204232532533423632);
    REQUIRE(deserializer.extract<uint8_t>() == 2);
    deserializer.skip(4);
    char str[6];
    str[5] = '\0';
    deserializer.extract((uint8_t*)str, 5);
    REQUIRE(strcmp(str, "hello") == 0);
    TestStruct actualTestStruct = deserializer.extract<TestStruct>();
    REQUIRE(actualTestStruct.a == expectedTestStruct.a && actualTestStruct.b == expectedTestStruct.b);
    REQUIRE(deserializer.empty());

    try
    {
        deserializer.extract<uint8_t>();
        FAIL("Expected extract to fail since we have extracted all data");
    }
    catch (sibs::DeserializeException &e)
    {

    }
}

int main()
{
#if BYTE_ORDER == BIG_ENDIAN
    const char *endianessStr = "big";
#elif BYTE_ORDER == LITTLE_ENDIAN
    const char *endianessStr = "little";
#else
    const char *endianessStr = "Unknown";
#endif
    printf("System endianess: %s\n", endianessStr);

    expectedTestStruct.a = 0x38956326;
    expectedTestStruct.b = 0x34;

    sibs::SafeSerializer serializer;
    serializer.add((uint32_t)3563634);
    serializer.add((uint64_t)204232532533423632);
    serializer.add((uint8_t)2);
    serializer.add("skip", 4);
    serializer.add((uint8_t*)"hello", 5);
    serializer.add(expectedTestStruct);
    REQUIRE(serializer.getBuffer().size() == 22 + sizeof(expectedTestStruct));

    testDeserialize(serializer);
    sibs::SafeSerializer movedSerializer(std::move(serializer));
    REQUIRE(serializer.getBuffer().empty());
    testDeserialize(movedSerializer);

    return 0;
}