1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
use crate::{
    common::*,
    file::{FileDumper, FileLoader, FilePath},
};

pub type Json5Path<T> = FilePath<T, Json5Dumper, Json5Loader>;

pub struct Json5Dumper {
    _private: [u8; 0],
}

impl<T> FileDumper<T> for Json5Dumper
where
    T: Serialize,
{
    type Error = anyhow::Error;

    fn dump<P>(p: P, value: &T) -> Result<(), Self::Error>
    where
        P: AsRef<Path>,
    {
        let text = json5::to_string(value)?;
        fs::write(p, &text)?;
        Ok(())
    }
}

pub struct Json5Loader {
    _private: [u8; 0],
}

impl<T> FileLoader<T> for Json5Loader
where
    T: DeserializeOwned,
{
    type Error = anyhow::Error;

    fn load<P>(p: P) -> Result<T, Self::Error>
    where
        P: AsRef<Path>,
    {
        let text = fs::read_to_string(p)?;
        let value = json5::from_str(&text)?;
        Ok(value)
    }
}