sulhyd/
conf.rs

1use serde::{Deserialize, Serialize};
2
3use crate::res::RFile;
4
5pub trait Config {
6    type Stur;
7    fn write_to(&self);
8    fn read_from(&self) -> Self::Stur;
9    fn from_path(content: Self::Stur, path: &str) -> Self;
10}
11
12
13#[derive(Clone)]
14pub struct JsonConfig<S>
15where
16    for<'a> S: Clone + Serialize + Deserialize<'a>,
17{
18    pub content: S,
19    pub path: String,
20}
21
22impl<S> Config for JsonConfig<S>
23where
24    for<'a> S: Clone + Serialize + Deserialize<'a>,
25{
26    type Stur = S;
27
28    fn write_to(&self) {
29        RFile::new(&self.path).write_str(
30            serde_json::to_string(&self.content.clone())
31                .unwrap()
32                .as_str(),
33        );
34    }
35
36    fn read_from(&self) -> Self::Stur {
37        serde_json::from_str::<S>(RFile::new(&self.path).read_str().unwrap().as_str()).unwrap()
38    }
39
40    fn from_path(content: S, path: &str) -> Self {
41        Self {
42            content: content.clone(),
43            path: path.to_string(),
44        }
45    }
46}
47
48#[derive(Clone)]
49pub struct YamlConfig<S>
50where
51    for<'a> S: Clone + Serialize + Deserialize<'a>,
52{
53    pub content: S,
54    pub path: String,
55}
56
57impl<S> Config for YamlConfig<S>
58where
59    for<'a> S: Clone + Serialize + Deserialize<'a>,
60{
61    type Stur = S;
62
63    fn write_to(&self) {
64        RFile::new(&self.path).write_str(
65            serde_yaml::to_string(&self.content.clone())
66                .unwrap()
67                .as_str(),
68        );
69    }
70
71    fn read_from(&self) -> Self::Stur {
72        serde_yaml::from_str::<S>(RFile::new(&self.path).read_str().unwrap().as_str()).unwrap()
73    }
74
75    fn from_path(content: S, path: &str) -> Self {
76        Self {
77            content: content.clone(),
78            path: path.to_string(),
79        }
80    }
81}