| 1 |
/* SPDX-License-Identifier: LGPL-2.1-or-later */ |
| 2 |
|
| 3 |
#include <stdio.h> |
| 4 |
#include <stdlib.h> |
| 5 |
#include <string.h> |
| 6 |
|
| 7 |
#include "fileio.h" |
| 8 |
#include "ordered-set.h" |
| 9 |
#include "strv.h" |
| 10 |
|
| 11 |
int ordered_set_ensure_allocated(OrderedSet **s, const struct hash_ops *ops) { |
| 12 |
assert(s); |
| 13 |
|
| 14 |
if (*s) |
| 15 |
return 0; |
| 16 |
|
| 17 |
*s = ordered_set_new(ops); |
| 18 |
if (!*s) |
| 19 |
return -ENOMEM; |
| 20 |
|
| 21 |
return 0; |
| 22 |
} |
| 23 |
|
| 24 |
int ordered_set_ensure_put(OrderedSet **s, const struct hash_ops *ops, void *p) { |
| 25 |
int r; |
| 26 |
|
| 27 |
assert(s); |
| 28 |
|
| 29 |
r = ordered_set_ensure_allocated(s, ops); |
| 30 |
if (r < 0) |
| 31 |
return r; |
| 32 |
|
| 33 |
return ordered_set_put(*s, p); |
| 34 |
} |
| 35 |
|
| 36 |
int ordered_set_consume(OrderedSet *s, void *p) { |
| 37 |
int r; |
| 38 |
|
| 39 |
r = ordered_set_put(s, p); |
| 40 |
if (r <= 0) |
| 41 |
free(p); |
| 42 |
|
| 43 |
return r; |
| 44 |
} |
| 45 |
|
| 46 |
int ordered_set_put_strdup_full(OrderedSet **s, const struct hash_ops *hash_ops, const char *p) { |
| 47 |
char *c; |
| 48 |
int r; |
| 49 |
|
| 50 |
assert(s); |
| 51 |
assert(p); |
| 52 |
|
| 53 |
r = ordered_set_ensure_allocated(s, hash_ops); |
| 54 |
if (r < 0) |
| 55 |
return r; |
| 56 |
|
| 57 |
if (ordered_set_contains(*s, p)) |
| 58 |
return 0; |
| 59 |
|
| 60 |
c = strdup(p); |
| 61 |
if (!c) |
| 62 |
return -ENOMEM; |
| 63 |
|
| 64 |
return ordered_set_consume(*s, c); |
| 65 |
} |
| 66 |
|
| 67 |
int ordered_set_put_strdupv_full(OrderedSet **s, const struct hash_ops *hash_ops, char **l) { |
| 68 |
int r, ret = 0; |
| 69 |
|
| 70 |
assert(s); |
| 71 |
|
| 72 |
STRV_FOREACH(i, l) { |
| 73 |
r = ordered_set_put_strdup_full(s, hash_ops, *i); |
| 74 |
if (r < 0) |
| 75 |
return r; |
| 76 |
|
| 77 |
ret = ret || r > 0; |
| 78 |
} |
| 79 |
|
| 80 |
return ret; |
| 81 |
} |
| 82 |
|
| 83 |
int ordered_set_put_string_set_full(OrderedSet **s, const struct hash_ops *hash_ops, OrderedSet *l) { |
| 84 |
int r, ret = 0; |
| 85 |
char *p; |
| 86 |
|
| 87 |
assert(s); |
| 88 |
|
| 89 |
/* Like ordered_set_put_strv, but for an OrderedSet of strings */ |
| 90 |
|
| 91 |
ORDERED_SET_FOREACH(p, l) { |
| 92 |
r = ordered_set_put_strdup_full(s, hash_ops, p); |
| 93 |
if (r < 0) |
| 94 |
return r; |
| 95 |
|
| 96 |
ret = ret || r > 0; |
| 97 |
} |
| 98 |
|
| 99 |
return ret; |
| 100 |
} |
| 101 |
|
| 102 |
void ordered_set_print(FILE *f, const char *field, OrderedSet *s) { |
| 103 |
bool space = false; |
| 104 |
char *p; |
| 105 |
|
| 106 |
assert(f); |
| 107 |
assert(field); |
| 108 |
|
| 109 |
if (ordered_set_isempty(s)) |
| 110 |
return; |
| 111 |
|
| 112 |
fputs(field, f); |
| 113 |
|
| 114 |
ORDERED_SET_FOREACH(p, s) |
| 115 |
fputs_with_separator(f, p, NULL, &space); |
| 116 |
|
| 117 |
fputc('\n', f); |
| 118 |
} |