Skip to main content

file_example/
file_example.rs

1// Copyright (c) 2026 CyberNestSticks LLC
2// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
3// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
4// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
5// option. This file may not be copied, modified, or distributed
6// except according to those terms.
7
8// Author: Lawrence (Larry) Foard
9#[cfg(all(feature = "serde_json", feature = "std"))]
10use serde::{Deserialize, Serialize};
11use std::collections::HashMap;
12use std::path::PathBuf;
13use zcstring::{serde_json_from_zcstring, ZCString};
14
15#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
16pub enum Status {
17    #[serde(rename = "active")]
18    Active,
19    #[serde(rename = "inactive")]
20    Inactive,
21    #[serde(rename = "maintenance")]
22    Maintenance,
23    #[serde(rename = "warning")]
24    Warning,
25}
26
27#[derive(Clone, Debug, Deserialize, Serialize)]
28struct State {
29    population: u64,
30    state_bird: ZCString,
31    capital: ZCString,
32    sensor_id: ZCString,
33    temp_c: f64,
34    status: Status,
35}
36
37#[derive(Debug, Deserialize, Serialize)]
38struct Country {
39    states: HashMap<ZCString, State>,
40}
41
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}