Branch data Line data Source code
1 : : // Copyright 2011-2025 David Robillard <d@drobilla.net>
2 : : // SPDX-License-Identifier: ISC
3 : :
4 : : #undef NDEBUG
5 : :
6 : : #include <exess/exess.h>
7 : :
8 : : #include <assert.h>
9 : : #include <stdint.h>
10 : : #include <string.h>
11 : :
12 : : static void
13 : 6 : check_read(const char* const string,
14 : : const ExessStatus expected_status,
15 : : const uint16_t expected_value,
16 : : const size_t expected_count)
17 : : {
18 : 6 : uint16_t value = 0;
19 : :
20 : 6 : const ExessResult r = exess_read_ushort(string, &value);
21 [ - + ]: 6 : assert(value == expected_value);
22 [ - + ]: 6 : assert(r.status == expected_status);
23 [ - + ]: 6 : assert(r.count == expected_count);
24 : 6 : }
25 : :
26 : : static void
27 : 1 : test_read_ushort(void)
28 : : {
29 : : // Limits
30 : 1 : check_read("0", EXESS_SUCCESS, 0, 1);
31 : 1 : check_read("65535", EXESS_SUCCESS, UINT16_MAX, EXESS_MAX_USHORT_LENGTH);
32 : :
33 : : // Out of range
34 : 1 : check_read("65536", EXESS_OUT_OF_RANGE, 0, 5);
35 : :
36 : : // Garbage
37 : 1 : check_read("E", EXESS_EXPECTED_DIGIT, 0, 0);
38 : 1 : check_read("-1", EXESS_EXPECTED_ZERO, 0, 1);
39 : 1 : check_read("+", EXESS_EXPECTED_DIGIT, 0, 1);
40 : 1 : }
41 : :
42 : : static void
43 : 3 : check_write(const uint16_t value,
44 : : const ExessStatus expected_status,
45 : : const size_t buf_size,
46 : : const char* const expected_string)
47 : : {
48 : 3 : char buf[EXESS_MAX_USHORT_LENGTH + 1] = {1, 2, 3, 4, 5, 6};
49 : :
50 [ - + ]: 3 : assert(buf_size <= sizeof(buf));
51 : :
52 : 3 : const ExessResult r = exess_write_ushort(value, buf_size, buf);
53 [ - + ]: 3 : assert(r.status == expected_status);
54 [ + + ]: 3 : if (!r.status) {
55 [ - + ]: 2 : assert(!strcmp(buf, expected_string));
56 [ - + ]: 2 : assert(r.count == strlen(buf));
57 [ - + ]: 2 : assert(exess_write_ushort(value, 0, NULL).count == r.count);
58 : : }
59 : 3 : }
60 : :
61 : : static void
62 : 1 : test_write_ushort(void)
63 : : {
64 : 1 : check_write(0U, EXESS_SUCCESS, 2, "0");
65 : 1 : check_write(UINT16_MAX, EXESS_SUCCESS, 6, "65535");
66 : 1 : check_write(UINT16_MAX, EXESS_NO_SPACE, 5, "65535");
67 : 1 : }
68 : :
69 : : static void
70 : 1 : test_round_trip(void)
71 : : {
72 : 1 : uint16_t value = 0;
73 : 1 : char buf[EXESS_MAX_USHORT_LENGTH + 1] = {1, 2, 3, 4, 5, 6};
74 : :
75 [ + + ]: 65537 : for (uint32_t i = 0; i <= UINT16_MAX; ++i) {
76 [ - + ]: 65536 : assert(!exess_write_ushort((uint16_t)i, sizeof(buf), buf).status);
77 [ - + ]: 65536 : assert(!exess_read_ushort(buf, &value).status);
78 [ - + ]: 65536 : assert(value == i);
79 : : }
80 : 1 : }
81 : :
82 : : int
83 : 1 : main(void)
84 : : {
85 : 1 : test_read_ushort();
86 : 1 : test_write_ushort();
87 : 1 : test_round_trip();
88 : :
89 : 1 : return 0;
90 : : }
|