]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/ordered-set.c
ordered-set: make ordered_set_put_strdup() allocate OrderedSet object
[thirdparty/systemd.git] / src / basic / ordered-set.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include "fileio.h"
4 #include "ordered-set.h"
5 #include "strv.h"
6
7 int _ordered_set_ensure_allocated(OrderedSet **s, const struct hash_ops *ops HASHMAP_DEBUG_PARAMS) {
8 if (*s)
9 return 0;
10
11 *s = _ordered_set_new(ops HASHMAP_DEBUG_PASS_ARGS);
12 if (!*s)
13 return -ENOMEM;
14
15 return 0;
16 }
17
18 int _ordered_set_ensure_put(OrderedSet **s, const struct hash_ops *ops, void *p HASHMAP_DEBUG_PARAMS) {
19 int r;
20
21 r = _ordered_set_ensure_allocated(s, ops HASHMAP_DEBUG_PASS_ARGS);
22 if (r < 0)
23 return r;
24
25 return ordered_set_put(*s, p);
26 }
27
28 int ordered_set_consume(OrderedSet *s, void *p) {
29 int r;
30
31 r = ordered_set_put(s, p);
32 if (r <= 0)
33 free(p);
34
35 return r;
36 }
37
38 int _ordered_set_put_strdup(OrderedSet **s, const char *p HASHMAP_DEBUG_PARAMS) {
39 char *c;
40 int r;
41
42 assert(s);
43 assert(p);
44
45 r = _ordered_set_ensure_allocated(s, &string_hash_ops_free HASHMAP_DEBUG_PASS_ARGS);
46 if (r < 0)
47 return r;
48
49 if (ordered_set_contains(*s, p))
50 return 0;
51
52 c = strdup(p);
53 if (!c)
54 return -ENOMEM;
55
56 return ordered_set_consume(*s, c);
57 }
58
59 int _ordered_set_put_strdupv(OrderedSet **s, char **l HASHMAP_DEBUG_PARAMS) {
60 int n = 0, r;
61 char **i;
62
63 STRV_FOREACH(i, l) {
64 r = _ordered_set_put_strdup(s, *i HASHMAP_DEBUG_PASS_ARGS);
65 if (r < 0)
66 return r;
67
68 n += r;
69 }
70
71 return n;
72 }
73
74 int ordered_set_put_string_set(OrderedSet **s, OrderedSet *l) {
75 int n = 0, r;
76 char *p;
77
78 /* Like ordered_set_put_strv, but for an OrderedSet of strings */
79
80 ORDERED_SET_FOREACH(p, l) {
81 r = ordered_set_put_strdup(s, p);
82 if (r < 0)
83 return r;
84
85 n += r;
86 }
87
88 return n;
89 }
90
91 void ordered_set_print(FILE *f, const char *field, OrderedSet *s) {
92 bool space = false;
93 char *p;
94
95 if (ordered_set_isempty(s))
96 return;
97
98 fputs(field, f);
99
100 ORDERED_SET_FOREACH(p, s)
101 fputs_with_space(f, p, NULL, &space);
102
103 fputc('\n', f);
104 }