forked from hse-project/hse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.c
101 lines (77 loc) · 1.87 KB
/
utils.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/* SPDX-License-Identifier: Apache-2.0 OR MIT
*
* SPDX-FileCopyrightText: Copyright 2022 Micron Technology, Inc.
*/
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sysexits.h>
#include <bsd/string.h>
#include <cjson/cJSON.h>
#include <hse/error/merr.h>
#include <hse/util/assert.h>
merr_t
flatten(cJSON * const in, const char * const prefix, cJSON * const out)
{
merr_t err = 0;
char *tmp = NULL;
INVARIANT(in);
INVARIANT(cJSON_IsObject(out));
if (!cJSON_IsObject(in))
return 0;
for (cJSON *n = in->child; n; n = n->next) {
const size_t len = (prefix ? strlen(prefix) : 0) + strlen(n->string) + 2;
tmp = malloc(len);
if (!tmp)
return merr(ENOMEM);
if (!prefix || strlen(prefix) == 0) {
strlcpy(tmp, n->string, len);
} else {
snprintf(tmp, len, "%s.%s", prefix, n->string);
}
err = flatten(n, tmp, out);
if (err)
goto end;
if (cJSON_IsObject(n))
goto end;
if (!cJSON_AddItemToObject(out, tmp, cJSON_Duplicate(n, cJSON_False))) {
err = merr(ENOMEM);
goto out;
}
end:
free(tmp);
if (err)
goto out;
}
out:
return err;
}
char *
rawify(cJSON * const node)
{
char *printed;
size_t len;
printed = cJSON_PrintUnformatted(node);
if (cJSON_IsString(node)) {
len = strlen(printed) - 2;
/* Remove double quote from each end.
*/
memmove(printed, printed + 1, len);
printed[len] = '\000';
}
return printed;
}
unsigned int
strchrrep(char * const str, const char old, const char new)
{
char *ix = str;
unsigned int n = 0;
if (!str)
return 0;
while ((ix = strchr(ix, old))) {
*ix++ = new;
n++;
}
return n;
}