serializer.rs

1.9 kB · rust · 67 lines

1use super::models::Cell6d;2use super::{Orientation, Projection};3use crate::dim::serializer::parse;4use crate::two;5use mrlycore::errors::Result;6use mrlycore::json;78fn projection_name(p: Projection) -> &'static str {9    match p {10        Projection::Iso => "iso",11        Projection::Pro => "pro",12        Projection::Cut => "cut",13    }14}1516fn orientation_name(o: Orientation) -> &'static str {17    match o {18        Orientation::Horizontal => "horizontal",19        Orientation::Vertical => "vertical",20    }21}2223/// Serializes a cell and its projection metadata to JSON.24pub fn to_json(cell: &Cell6d) -> String {25    let mut data = parse(&two::to_json(&cell.cell)).unwrap();26    data["projection"] = json!(projection_name(cell.projection));27    data["orientation"] = json!(orientation_name(cell.orientation));28    data["start"] = json!(cell.start);29    data.to_string()30}3132/// Parses a cell from JSON, defaulting any missing projection metadata.33pub fn from_json(text: &str) -> Result<Cell6d> {34    let data = parse(text)?;35    let inner = two::from_json(text)?;36    let projection = match data37        .get("projection")38        .and_then(|v| v.as_str())39        .unwrap_or("iso")40    {41        "pro" => Projection::Pro,42        "cut" => Projection::Cut,43        _ => Projection::Iso,44    };45    let orientation = match data46        .get("orientation")47        .and_then(|v| v.as_str())48        .unwrap_or("vertical")49    {50        "horizontal" => Orientation::Horizontal,51        _ => Orientation::Vertical,52    };53    let start = data.get("start").and_then(|v| v.as_u64()).unwrap_or(1) as u8;54    Ok(Cell6d::new(inner, projection, orientation, start))55}5657#[cfg(test)]58mod tests {59    use super::*;60    use crate::six::designs::cut_design;61    #[test]62    fn json_round_trip() {63        let c = cut_design(23, 3, 1, 2).unwrap();64        let restored = from_json(&to_json(&c)).unwrap();65        assert_eq!(c, restored);66    }67}