to_object_unsafe/
to_object_unsafe.rs1use std::collections::HashMap;
4
5use simple_json_parser::{parse, JSONKey, RootJSONValue};
6
7fn main() -> Result<(), Box<dyn std::error::Error>> {
8 let path = std::env::args().nth(1).ok_or("Expected first argument")?;
9 let content = std::fs::read_to_string(path)?;
10
11 pub type Object = HashMap<String, Value>;
12
13 #[derive(Debug)]
14 #[allow(dead_code)]
15 pub enum Value {
16 Object(Object),
17 String(String),
18 Number(String),
19 Boolean(bool),
20 Null,
21 }
22
23 impl Value {
24 pub fn new_empty_object() -> Self {
25 Self::Object(HashMap::new())
26 }
27 }
28
29 let mut root = Object::new();
30
31 let _res = parse(&content, |keys, value| {
32 let [path @ .., end] = keys else {
33 unreachable!("empty key change")
34 };
35 let pointer = &mut root;
36
37 let mut to_add_to: *mut Object = pointer;
38
39 for key in path {
40 let name = match key {
41 JSONKey::Slice(s) => (*s).to_string(),
42 JSONKey::Index(i) => i.to_string(),
43 };
44 if let Some(Value::Object(ref mut obj)) =
45 unsafe { (to_add_to.as_mut().unwrap()).get_mut(&name) }
46 {
47 to_add_to = obj;
48 } else {
49 let value = unsafe {
50 (to_add_to.as_mut().unwrap())
51 .entry(name)
52 .or_insert_with(Value::new_empty_object)
53 };
54 if let Value::Object(ref mut obj) = value {
55 to_add_to = obj;
56 }
57 }
58 }
59 let name = match end {
60 JSONKey::Slice(s) => (*s).to_string(),
61 JSONKey::Index(i) => i.to_string(),
62 };
63 let value = match value {
64 RootJSONValue::String(s) => Value::String(s.to_string()),
65 RootJSONValue::Number(n) => Value::Number(n.to_string()),
66 RootJSONValue::Boolean(v) => Value::Boolean(v),
67 RootJSONValue::Null => Value::Null,
68 };
69 unsafe {
70 (to_add_to.as_mut().unwrap()).insert(name, value);
71 }
72 });
73
74 eprintln!("Parsed: {root:#?}");
75 Ok(())
76}