locus_lib/
json.rs

1use std::{
2    fs,
3    io::{Error, ErrorKind},
4    path::PathBuf,
5};
6
7use serde::{de::DeserializeOwned, Serialize};
8
9/// Trait for types that can be converted to and from JSON.
10pub trait Jsonable: Serialize + DeserializeOwned {
11    /// Encodes the type as JSON.
12    fn to_json(&self) -> String {
13        serde_json::to_string(self).unwrap()
14    }
15
16    /// Decodes the type from JSON.
17    fn from_json(path: &PathBuf) -> Result<Self, Error> {
18        let storage_json = match fs::read_to_string(&path) {
19            Ok(json) => json,
20            Err(e) => {
21                return Err(Error::new(
22                    ErrorKind::Other,
23                    format!("Could not load storage. err:{e:?}, file_name: {path:?}"),
24                ))
25            }
26        };
27
28        match serde_json::from_str(&storage_json) {
29            Ok(storage) => Ok(storage),
30            Err(e) => return Err(Error::new(ErrorKind::Unsupported, e.to_string())),
31        }
32    }
33}