Skip to main content

serde_json_from_zcstring

Function serde_json_from_zcstring 

Source
pub fn serde_json_from_zcstring<T>(json: ZCString) -> Result<T, Box<dyn Error>>
where T: for<'de> Deserialize<'de>,
Expand description

Parses a JSON string into type T while using the provided ZCString as the context for any zero-copy deserialization.

Requires the serde feature.

Examples found in repository?
examples/simple_example.rs (line 80)
48fn main() -> Result<(), Box<dyn Error>> {
49    // ZCString creation
50    println!("From str: {:?}", ZCString::from("str"));
51    #[cfg(feature = "std")]
52    println!("From String: {:?}", ZCString::from(String::from("str")));
53    println!("New ZCString: {:?}", ZCString::new());
54
55    // how big is a ZCString member in a structure as compared &str?
56
57    // we expect the same size. Why? &str is a fat pointer and
58    // ZString is a Substr which is a thin pointer to an ArcStr plus
59    // a range consisting of two u32s
60    println!("size_of &str: {}", size_of::<&str>());
61    println!("size_of ZCString: {}", size_of::<ZCString>());
62
63    #[cfg(feature = "serde")]
64    {
65        // example JSON data feed
66        let input = [
67            literal!(r#"{"level": "error", "message": "Connection lost"}"#),
68            literal!(r#"{"level": "warning", "message": "Cat on keyboard"}"#),
69            literal!(r#"{"level": "info", "message": "Crow pecked camera"}"#),
70            literal!(r#"{"level": "error", "message": "Raven pecked camera, now offline"}"#),
71            // in this case the address of message should not fall within
72            // the memory address range of the raw json
73            literal!(r#"{"level": "error", "message": "Escaped \" "}"#),
74        ];
75
76        let items = input
77            .into_iter()
78            .map(|line| -> Result<LogEntry, Box<dyn Error>> {
79                // our special wrapper for JSON parsing
80                let entry = serde_json_from_zcstring::<LogEntry>(ZCString::from(line.clone()))?;
81
82                // show values and memory layout
83                println!("------");
84
85                println!("Log Line: {}", line);
86                println!(
87                    "  Log Line Location: 0x{:x} - 0x{:x}",
88                    line.as_ptr() as usize,
89                    line.as_ptr() as usize + line.len(),
90                );
91
92                show("level", &line, &entry.level);
93                show("message", &line, &entry.message);
94
95                // now serialize - Ok we could do a zero-alloc deserialize but
96                //                 not right now...
97                println!("  Serialized: {}", serde_json::to_string(&entry)?);
98                println!("");
99
100                Ok(entry)
101            })
102            .collect::<Result<Vec<LogEntry>, _>>()?;
103
104        println!("items size: {}\n", items.len());
105    }
106
107    Ok(())
108}