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
|
/*
This file is part of jellything (https://codeberg.org/metamuffin/jellything)
which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
Copyright (C) 2026 metamuffin <metamuffin.org>
*/
use crate::{Object, Registry, types::*};
use serde_json::{Map, Value};
pub fn object_to_json(reg: &Registry, ob: Object<'_>) -> Value {
let mut o = Map::new();
let mut nonexhaustive = false;
for (i, tag) in ob.keys().enumerate() {
let Some(info) = reg.info(tag) else {
nonexhaustive = true;
continue;
};
let Some(ty) = info.r#type else {
nonexhaustive = true;
continue;
};
let key = info.name.to_string();
match ty {
x if x == STR => {
let val = ob.get_typed::<&str>(i).unwrap().to_string().into();
multi_insert(&mut o, key, val);
}
x if x == OBJECT => {
let val = object_to_json(reg, ob.get_typed::<Object>(i).unwrap());
multi_insert(&mut o, key, val);
}
x if x == U32 => {
let val = ob.get_typed::<u32>(i).unwrap().to_string().into();
multi_insert(&mut o, key, val);
}
x if x == U64 => {
let val = ob.get_typed::<u64>(i).unwrap().to_string().into();
multi_insert(&mut o, key, val);
}
x if x == F64 => {
let val = ob.get_typed::<f64>(i).unwrap().to_string().into();
multi_insert(&mut o, key, val);
}
_ => {
nonexhaustive = true;
}
};
}
if nonexhaustive {
o.insert("_nonexhaustive".to_owned(), Value::Bool(true));
}
Value::Object(o)
}
fn multi_insert(m: &mut Map<String, Value>, key: String, val: Value) {
if let Some(cur) = m.get_mut(&key) {
if let Some(cur) = cur.as_array_mut() {
cur.push(val);
} else {
*cur = Value::Array(vec![cur.clone(), val])
}
} else {
m.insert(key, val);
}
}
|