test_varint.c revision 9a690580
1/* Copyright (c) 2017 - 2020 LiteSpeed Technologies Inc.  See LICENSE. */
2#include <assert.h>
3#include <stddef.h>
4#include <stdint.h>
5
6#include "lsquic_varint.h"
7
8#define MAX_INPUT_SZ 8
9
10struct test_read_varint
11{
12    /* Input: */
13    unsigned char       input[MAX_INPUT_SZ];
14    size_t              in_sz;
15    /* Output: */
16    int                 rv;
17    uint64_t            val;
18};
19
20static const struct test_read_varint read_tests[] =
21{
22    {
23        .input = "\x25",
24        .in_sz = 0,
25        .rv = -1,
26    },
27    {
28        .input = "\x25",
29        .in_sz = 2,
30        .rv = 1,
31        .val = 0x25,
32    },
33    {
34        .input = "\x40\x25",
35        .in_sz = 1,
36        .rv = -1,
37    },
38    {
39        .input = "\x40\x25",
40        .in_sz = 2,
41        .rv = 2,
42        .val = 0x25,
43    },
44    {
45        .input = "\x9d\x7f\x3e\x7d",
46        .in_sz = 2,
47        .rv = -1,
48    },
49    {
50        .input = "\x9d\x7f\x3e\x7d",
51        .in_sz = 4,
52        .rv = 4,
53        .val = 494878333,
54    },
55    {
56        .input = "\xc2\x19\x7c\x5e\xff\x14\xe8\x8c",
57        .in_sz = 7,
58        .rv = -1,
59    },
60    {
61        .input = "\xc2\x19\x7c\x5e\xff\x14\xe8\x8c",
62        .in_sz = 8,
63        .rv = 8,
64        .val = 151288809941952652ull,
65    },
66};
67
68
69int
70main (void)
71{
72    const struct test_read_varint *test;
73    const struct test_read_varint *const end
74        = read_tests + sizeof(read_tests) / sizeof(read_tests[0]);
75    size_t input_sz, avail;
76    struct varint_read_state state;
77    const unsigned char *p, *endp;
78    int s;
79
80    for (test = read_tests; test < end; ++test)
81    {
82        uint64_t val;
83        const int rv = vint_read(test->input, test->input + test->in_sz, &val);
84        assert(rv == test->rv);
85        if (test->rv > 0)
86            assert(val == test->val);
87
88        /* Test non-blocking read */
89        for (input_sz = MAX_INPUT_SZ; input_sz > 0; --input_sz)
90        {
91            state.pos = 0;
92            p = test->input;
93            endp = p + test->in_sz;
94            while (p < endp)
95            {
96                avail = (uintptr_t) (endp - p);
97                if (avail > input_sz)
98                    avail = input_sz;
99                s = lsquic_varint_read_nb(&p, p + avail, &state);
100                if (0 == s)
101                {
102                    assert(state.val == test->val);
103                    assert(p <= endp);
104                    break;
105                }
106                else if (p == endp)
107                {
108                    assert(test->rv == -1);
109                    break;
110                }
111                else
112                {
113                    assert(p < endp);
114                }
115            }
116        }
117    }
118
119    return 0;
120}
121