quilt-save 0.6.0

Quilt Save — .qzt file format, save/load cells
Documentation
//! quilt-save — .qzt file format, save/load cells

use quilt_cell::Cell;
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Qzt {
    pub version: String,
    pub kind: String,
    pub name: String,
    pub description: String,
    pub cells: Vec<Cell>,
    pub edges: Vec<(String, String, f64)>,
}

impl Qzt {
    pub fn new(name: &str) -> Self {
        Self {
            version: "1.0".to_string(),
            kind: "quilt-zip-target".to_string(),
            name: name.to_string(),
            description: "".to_string(),
            cells: vec![],
            edges: vec![],
        }
    }
    pub fn add_cell(&mut self, cell: Cell) { self.cells.push(cell); }
    pub fn add_edge(&mut self, from: &str, to: &str, weight: f64) {
        self.edges.push((from.to_string(), to.to_string(), weight));
    }
    pub fn save(&self, path: &str) -> std::io::Result<()> {
        std::fs::write(path, serde_json::to_string_pretty(self).unwrap())
    }
    pub fn load(path: &str) -> std::io::Result<Self> {
        let data = std::fs::read_to_string(path)?;
        Ok(serde_json::from_str(&data).unwrap_or_else(|_| Qzt::new("loaded")))
    }
    pub fn cell_count(&self) -> usize { self.cells.len() }
    pub fn edge_count(&self) -> usize { self.edges.len() }
}

pub const MAGIC: &str = "QUILT-ZIP-TARGET";
pub const VERSION: &str = "1.0";

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn test_qzt() {
        let mut q = Qzt::new("test");
        q.add_cell(Cell::new("a"));
        q.add_cell(Cell::new("b"));
        q.add_edge("a", "b", 1.0);
        assert_eq!(q.cell_count(), 2);
        assert_eq!(q.edge_count(), 1);
    }
}