abacus/abacus-core/src/save_file.rs

46 lines
1.2 KiB
Rust

use std::fmt::Display;
use serde::{Deserialize, Serialize};
#[derive(Clone, Deserialize, Serialize, Debug)]
pub struct SaveBlock {
pub name: String,
pub content: String,
}
impl SaveBlock {
pub fn new<S: Display>(name: &str, content: S) -> Self {
Self {
name: name.to_string(),
content: content.to_string(),
}
}
}
#[derive(Clone, Deserialize, Serialize, Debug)]
pub struct SaveFile {
#[serde(skip)]
pub filepath: String,
pub blocks: Vec<SaveBlock>,
}
impl SaveFile {
pub fn new(filepath: String, blocks: Vec<SaveBlock>) -> Self {
Self { filepath, blocks }
}
pub fn open(filepath: &str) -> Result<Self, std::io::Error> {
let data = std::fs::read_to_string(filepath)?;
let mut slf = serde_json::from_str::<Self>(&data)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()))?;
slf.filepath = filepath.to_string();
Ok(slf)
}
pub fn save(&self) -> Result<(), std::io::Error> {
let s = serde_json::to_vec_pretty(&self)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()))?;
std::fs::write(&self.filepath, s)
}
}