-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.c
More file actions
109 lines (89 loc) · 2.51 KB
/
example.c
File metadata and controls
109 lines (89 loc) · 2.51 KB
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
102
103
104
105
106
107
108
109
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include "djevko.h"
typedef struct {
char** colors;
Size len;
} FavColors;
typedef struct {
char* name;
int age;
Bool is_cool;
FavColors fav_colors;
} Person;
// converting a Djevko into an array
FavColors Djevko_as_fav_colors(Djevko* j) {
Djevko_check_suffix_empty(j);
Size len = j->len;
char** colors = (char**)malloc(len * sizeof(char*));
for (Index i = 0; i < len; ++i) {
Djevko_check_prefix_empty(j, i);
colors[i] = Djevko_as_str(j->subs[i]);
}
return (FavColors){colors,len};
}
// converting a Djevko into a struct
Person Djevko_as_Person(Djevko* j) {
Djevko_check_suffix_empty(j);
Person p = {0,0,0,0};
char seen_keys[4] = {0};
for (Index i = 0; i < j->len; ++i) {
Slice s = j->prefixes[i];
if (Slice_equals_key(s, "name", seen_keys, 0)) {
// converting a Djevko into a string
p.name = Djevko_as_str(j->subs[i]);
} else if (Slice_equals_key(s, "age", seen_keys, 1)) {
// converting a Djevko into an integer
p.age = Djevko_as_long(j->subs[i]);
} else if (Slice_equals_key(s, "is cool", seen_keys, 2)) {
// converting a Djevko into a boolean
p.is_cool = Djevko_as_bool(j->subs[i]);
} else if (Slice_equals_key(s, "fav colors", seen_keys, 3)) {
// converting a Djevko into a custom value
p.fav_colors = Djevko_as_fav_colors(j->subs[i]);
}
}
return p;
}
Person Person_parse(Str str) {
Djevko* j = Djevko_parse(str);
Person p = Djevko_as_Person(j);
Djevko_delete(&j);
return p;
}
void Person_free(Person p) {
free(p.name);
for (Index i = 0; i < p.fav_colors.len; ++i) {
free(p.fav_colors.colors[i]);
}
free(p.fav_colors.colors);
}
void Person_print(Person p, FILE* f) {
// assume p.name doesn't contain special characters [`] -- otherwise we'd have to escape(p.name)
fprintf(f, "name [%s]\n", p.name);
fprintf(f, "age [%d]\n", p.age);
fprintf(f, "is cool [%s]\n", Bool_as_str(p.is_cool));
fprintf(f, "fav colors [\n");
for (Index i = 0; i < p.fav_colors.len; ++i) {
char* color = p.fav_colors.colors[i];
// assume color doesn't contain special characters [`] -- otherwise we'd have to escape(color)
fprintf(f, " [%s]\n", color);
}
fprintf(f, "]\n");
}
int main() {
const char* str =
"name [ Jon Wąpierz 😀 ]"
"age [32]"
"is cool [true]"
"fav colors ["
"[red]"
"[green]"
"[blue]"
"]";
Person p = Person_parse(str);
Person_print(p, stdout);
Person_free(p);
return 0;
}