xref: /freebsd/contrib/libcbor/test/array_encoders_test.c (revision f81cdf24ba5436367377f7c8e8f51f6df2a75ca7)
1 /*
2  * Copyright (c) 2014-2020 Pavel Kalvoda <me@pavelkalvoda.com>
3  *
4  * libcbor is free software; you can redistribute it and/or modify
5  * it under the terms of the MIT license. See LICENSE for details.
6  */
7 
8 #include "assertions.h"
9 #include "cbor.h"
10 
11 unsigned char buffer[512];
12 
13 static void test_embedded_array_start(void **_CBOR_UNUSED(_state)) {
14   assert_size_equal(1, cbor_encode_array_start(1, buffer, 512));
15   assert_memory_equal(buffer, ((unsigned char[]){0x81}), 1);
16 }
17 
18 static void test_array_start(void **_CBOR_UNUSED(_state)) {
19   assert_size_equal(5, cbor_encode_array_start(1000000, buffer, 512));
20   assert_memory_equal(buffer, ((unsigned char[]){0x9A, 0x00, 0x0F, 0x42, 0x40}),
21                       5);
22 }
23 
24 static void test_indef_array_start(void **_CBOR_UNUSED(_state)) {
25   assert_size_equal(1, cbor_encode_indef_array_start(buffer, 512));
26   assert_size_equal(0, cbor_encode_indef_array_start(buffer, 0));
27   assert_memory_equal(buffer, ((unsigned char[]){0x9F}), 1);
28 }
29 
30 static void test_indef_array_encoding(void **_CBOR_UNUSED(_state)) {
31   cbor_item_t *array = cbor_new_indefinite_array();
32   cbor_item_t *one = cbor_build_uint8(1);
33   cbor_item_t *two = cbor_build_uint8(2);
34   assert_true(cbor_array_push(array, one));
35   assert_true(cbor_array_push(array, two));
36 
37   assert_size_equal(4, cbor_serialize_array(array, buffer, 512));
38   assert_memory_equal(buffer, ((unsigned char[]){0x9F, 0x01, 0x02, 0xFF}), 4);
39 
40   cbor_decref(&array);
41   cbor_decref(&one);
42   cbor_decref(&two);
43 }
44 
45 int main(void) {
46   const struct CMUnitTest tests[] = {
47       cmocka_unit_test(test_embedded_array_start),
48       cmocka_unit_test(test_array_start),
49       cmocka_unit_test(test_indef_array_start),
50       cmocka_unit_test(test_indef_array_encoding)};
51   return cmocka_run_group_tests(tests, NULL, NULL);
52 }
53