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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
use std::{
    fmt::{Debug, Formatter},
    fs,
    marker::PhantomData,
    path::PathBuf,
};

use serde::{de::DeserializeOwned, Serialize};

use crate::{file::File, platform::Platform};

pub trait Wrappable: Serialize + DeserializeOwned + Send + Default {}
impl<T: Serialize + DeserializeOwned + Send + Default> Wrappable for T {}

fn executable_name() -> String {
    std::env::current_exe()
        .expect("Failed to get std::env::current_exe()")
        .file_name()
        .expect("Failed to get executable name")
        .to_string_lossy()
        .into()
}

fn storage_dir() -> PathBuf {
    if Platform::MOBILE {
        dirs::document_dir()
    } else {
        dirs::home_dir()
    }
    .expect("Failed to get home directory")
    .join(".".to_owned() + &executable_name())
}

fn set_value<T: Serialize>(value: T, key: &str) {
    let json = serde_json::to_string(&value).expect("Failed to serialize data");
    let dir = storage_dir();
    File::mkdir(&dir).unwrap();
    fs::write(dir.join(key), json).expect("Failed to write to file");
}

fn get_value<T: Wrappable>(key: &str) -> T {
    let dir = storage_dir();
    let path = dir.join(key);

    File::mkdir(&dir).unwrap();

    if !path.exists() {
        let new = T::default();
        set_value(&new, key);
        return new;
    }
    let json = fs::read_to_string(path).expect("Failed to read file");
    serde_json::from_str(&json).expect("Failet to parse json")
}

pub struct Stored<T: Wrappable> {
    name: &'static str,
    _p:   PhantomData<T>,
}

impl<T: Wrappable> Stored<T> {
    pub const fn new(name: &'static str) -> Self {
        Self {
            name,
            _p: PhantomData,
        }
    }

    pub fn set(&self, val: impl Into<T>) {
        let val = val.into();
        set_value(val, self.name)
    }

    pub fn get(&self) -> T {
        get_value(self.name)
    }

    pub fn reset(&self) {
        self.set(T::default())
    }
}

impl<T: Wrappable + Debug> Debug for Stored<T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        self.get().fmt(f)
    }
}

#[cfg(test)]
mod test {
    use anyhow::Result;
    use tokio::spawn;

    use crate::{
        file::File,
        random::Random,
        stored::{executable_name, storage_dir},
        Stored,
    };

    static STORED: Stored<i32> = Stored::new("stored_test");

    fn check_send<T: Send>(_send: &T) {}
    fn check_sync<T: Sync>(_sync: &T) {}

    #[tokio::test]
    async fn stored() -> Result<()> {
        File::rm(storage_dir())?;

        check_send(&STORED);
        check_sync(&STORED);

        STORED.set(10);
        STORED.reset();
        assert_eq!(STORED.get(), i32::default());

        for _ in 0..10 {
            let rand = i32::random();

            spawn(async move {
                STORED.set(rand);
            })
            .await?;

            spawn(async move {
                assert_eq!(STORED.get(), rand);
                assert_eq!(format!("{rand}"), format!("{STORED:?}"));
            })
            .await?;
        }

        Ok(())
    }

    #[test]
    fn paths() {
        assert!(executable_name().starts_with("rtools"));
    }
}