pub fn serde_json_from_zcstring<T>(json: ZCString) -> Result<T, Box<dyn Error>>where
T: for<'de> Deserialize<'de>,Available on crate feature
serde_json only.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/json_example.rs (line 65)
47fn main() -> Result<(), Box<dyn Error>> {
48 #[cfg(feature = "serde_json")]
49 {
50 // example JSON data feed
51 let input = [
52 literal!(r#"{"level": "error", "message": "Connection lost"}"#),
53 literal!(r#"{"level": "warning", "message": "Cat on keyboard"}"#),
54 literal!(r#"{"level": "info", "message": "Crow pecked camera"}"#),
55 literal!(r#"{"level": "error", "message": "Raven pecked camera, now offline"}"#),
56 // in this case the address of message should not fall within
57 // the memory address range of the raw json
58 literal!(r#"{"level": "error", "message": "Escaped \" "}"#),
59 ];
60
61 let items = input
62 .into_iter()
63 .map(|line| -> Result<LogEntry, Box<dyn Error>> {
64 // our special wrapper for JSON parsing
65 let entry = serde_json_from_zcstring::<LogEntry>(ZCString::from(line.clone()))?;
66
67 // show values and memory layout
68 println!("------");
69
70 println!("Log Line: {}", line);
71 println!(
72 " Log Line Location: 0x{:x} - 0x{:x}",
73 line.as_ptr() as usize,
74 line.as_ptr() as usize + line.len(),
75 );
76
77 show("level", &line, &entry.level);
78 show("message", &line, &entry.message);
79
80 // now serialize - Ok we could do a zero-alloc deserialize but
81 // not right now...
82 println!(" Serialized: {}", serde_json::to_string(&entry)?);
83 println!("");
84
85 Ok(entry)
86 })
87 .collect::<Result<Vec<LogEntry>, _>>()?;
88
89 println!("items size: {}\n", items.len());
90 }
91
92 Ok(())
93}