]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/test/test-strxcpyx.c
format-table: automatically show empty cells in grey
[thirdparty/systemd.git] / src / test / test-strxcpyx.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <stdio.h>
4 #include <string.h>
5
6 #include "string-util.h"
7 #include "strxcpyx.h"
8 #include "util.h"
9
10 static void test_strpcpy(void) {
11 char target[25];
12 char *s = target;
13 size_t space_left;
14
15 space_left = sizeof(target);
16 space_left = strpcpy(&s, space_left, "12345");
17 space_left = strpcpy(&s, space_left, "hey hey hey");
18 space_left = strpcpy(&s, space_left, "waldo");
19 space_left = strpcpy(&s, space_left, "ba");
20 space_left = strpcpy(&s, space_left, "r");
21 space_left = strpcpy(&s, space_left, "foo");
22
23 assert_se(streq(target, "12345hey hey heywaldobar"));
24 assert_se(space_left == 0);
25 }
26
27 static void test_strpcpyf(void) {
28 char target[25];
29 char *s = target;
30 size_t space_left;
31
32 space_left = sizeof(target);
33 space_left = strpcpyf(&s, space_left, "space left: %zu. ", space_left);
34 space_left = strpcpyf(&s, space_left, "foo%s", "bar");
35
36 assert_se(streq(target, "space left: 25. foobar"));
37 assert_se(space_left == 3);
38
39 /* test overflow */
40 s = target;
41 space_left = strpcpyf(&s, 12, "00 left: %i. ", 999);
42 assert_se(streq(target, "00 left: 99"));
43 assert_se(space_left == 0);
44 assert_se(target[12] == '2');
45 }
46
47 static void test_strpcpyl(void) {
48 char target[25];
49 char *s = target;
50 size_t space_left;
51
52 space_left = sizeof(target);
53 space_left = strpcpyl(&s, space_left, "waldo", " test", " waldo. ", NULL);
54 space_left = strpcpyl(&s, space_left, "Banana", NULL);
55
56 assert_se(streq(target, "waldo test waldo. Banana"));
57 assert_se(space_left == 1);
58 }
59
60 static void test_strscpy(void) {
61 char target[25];
62 size_t space_left;
63
64 space_left = sizeof(target);
65 space_left = strscpy(target, space_left, "12345");
66
67 assert_se(streq(target, "12345"));
68 assert_se(space_left == 20);
69 }
70
71 static void test_strscpyl(void) {
72 char target[25];
73 size_t space_left;
74
75 space_left = sizeof(target);
76 space_left = strscpyl(target, space_left, "12345", "waldo", "waldo", NULL);
77
78 assert_se(streq(target, "12345waldowaldo"));
79 assert_se(space_left == 10);
80 }
81
82 static void test_sd_event_code_migration(void) {
83 char b[100 * DECIMAL_STR_MAX(unsigned) + 1];
84 char c[100 * DECIMAL_STR_MAX(unsigned) + 1], *p;
85 unsigned i;
86 size_t l;
87 int o;
88
89 for (i = o = 0; i < 100; i++)
90 o += snprintf(&b[o], sizeof(b) - o, "%u ", i);
91
92 p = c;
93 l = sizeof(c);
94 for (i = 0; i < 100; i++)
95 l = strpcpyf(&p, l, "%u ", i);
96
97 assert_se(streq(b, c));
98 }
99
100 int main(int argc, char *argv[]) {
101 test_strpcpy();
102 test_strpcpyf();
103 test_strpcpyl();
104 test_strscpy();
105 test_strscpyl();
106
107 test_sd_event_code_migration();
108
109 return 0;
110 }