pub fn serde_json_from_zcstring<T>(json: ZCString) -> Result<T, 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/file_example.rs (line 50)
42fn main() -> Result<(), Box<dyn std::error::Error>> {
43 // Construct a path relative to the project root
44 let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
45 path.push("examples");
46 // dummy test data
47 path.push("file_example.json");
48
49 let data = ZCString::from_file(path)?;
50 let country: Country = serde_json_from_zcstring(data)?;
51
52 let active: HashMap<_, _> = country
53 .states
54 .iter()
55 .filter(|(_, data)| data.status == Status::Active)
56 // k.clone() is zero-copy and still points back to 'data'
57 // as do CZStrings within State
58 .map(|(k, v)| (k.clone(), v.clone()))
59 .collect();
60
61 println!("{}", serde_json::to_string_pretty(&active)?);
62 Ok(())
63}More examples
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}