Debian Codegraph @

test/uuid.c

raw
1 // SPDX-License-Identifier: LGPL-2.1-or-later
2 /**
3 * This file is part of libnvme.
4 * Copyright (c) 2022 Daniel Wagner, SUSE Software Solutions
5 */
6
7 #include <string.h>
8 #include <stdlib.h>
9
10 #include <ccan/array_size/array_size.h>
11
12 #include <libnvme.h>
13
14 static int test_rc;
15
16 struct test_data {
17 unsigned char uuid[NVME_UUID_LEN];
18 const char *str;
19 };
20
21 static struct test_data test_data[] = {
22 { { 0 }, "00000000-0000-0000-0000-000000000000" },
23 { { [0 ... 15] = 0xff }, "ffffffff-ffff-ffff-ffff-ffffffffffff" },
24 { { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
25 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0f, 0x10 },
26 "00010203-0405-0607-0809-0a0b0c0d0f10" },
27 };
28
29 static void check_str(const char *exp, const char *res)
30 {
31 if (!strcmp(res, exp))
32 return;
33
34 printf("ERROR: got '%s', expected '%s'\n", res, exp);
35
36 test_rc = 1;
37 }
38
39 static void print_uuid_hex(const unsigned char uuid[NVME_UUID_LEN])
40 {
41 for (int i = 0; i < NVME_UUID_LEN; i++)
42 printf("%02x", uuid[i]);
43 }
44
45 static void check_uuid(unsigned char exp[NVME_UUID_LEN],
46 unsigned char res[NVME_UUID_LEN])
47 {
48 if (!memcmp(exp, res, NVME_UUID_LEN))
49 return;
50
51 printf("ERROR: got '");
52 print_uuid_hex(exp);
53 printf("', expected '");
54 print_uuid_hex(res);
55 printf("'\n");
56 }
57
58 static void tostr_test(struct test_data *test)
59 {
60 char str[NVME_UUID_LEN_STRING];
61
62 if (nvme_uuid_to_string(test->uuid, str)) {
63 test_rc = 1;
64 printf("ERROR: nvme_uuid_to_string() failed\n");
65 return;
66 }
67 check_str(test->str, str);
68 }
69
70 static void fromstr_test(struct test_data *test)
71 {
72
73 unsigned char uuid[NVME_UUID_LEN];
74
75 if (nvme_uuid_from_string(test->str, uuid)) {
76 test_rc = 1;
77 printf("ERROR: nvme_uuid_from_string() failed\n");
78 return;
79 }
80 check_uuid(test->uuid, uuid);
81 }
82
83 static void random_uuid_test(void)
84 {
85 unsigned char uuid1[NVME_UUID_LEN], uuid2[NVME_UUID_LEN];
86 char str1[NVME_UUID_LEN_STRING], str2[NVME_UUID_LEN_STRING];
87
88 if (nvme_uuid_random(uuid1) || nvme_uuid_random(uuid2)) {
89 test_rc = 1;
90 printf("ERROR: nvme_uuid_random() failed\n");
91 return;
92 }
93
94 if (!memcmp(uuid1, uuid2, NVME_UUID_LEN)) {
95 test_rc = 1;
96 printf("ERROR: generated random numbers are equal\n");
97 return;
98 }
99
100 if (nvme_uuid_to_string(uuid1, str1) ||
101 nvme_uuid_to_string(uuid2, str2)) {
102 test_rc = 1;
103 printf("ERROR: could not stringify randomly generated UUID\n");
104 return;
105 }
106 printf("PASS: generated UUIDs %s %s\n", str1, str2);
107 }
108
109 int main(void)
110 {
111 for (int i = 0; i < ARRAY_SIZE(test_data); i++)
112 tostr_test(&test_data[i]);
113
114 for (int i = 0; i < ARRAY_SIZE(test_data); i++)
115 fromstr_test(&test_data[i]);
116
117 random_uuid_test();
118
119 return test_rc ? EXIT_FAILURE : EXIT_SUCCESS;
120 }