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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
extern crate ron;
#[allow(unused_imports)]
#[macro_use]
extern crate serde;
extern crate serde_json;

use std::error::Error;
use std::fs::{ File };
use std::io::{Read, Write};
use std::path::PathBuf;

use ron::de::from_str;
use serde::de::DeserializeOwned;

/// #
/// # Fetch
///
/// Simple trait that can be implemented on structs/enums for
/// serialisation to and from disk.
///
/// * deserialize_l: impl to pick specific
///
/// * serialize_l: ..
///
/// ```
/// use std::env;
/// use std::error::Error;
/// use std::path::PathBuf;
/// use serde::*;
/// use serde::de::DeserializeOwned;
/// use fetch_file::Fetchable;
///
/// #[derive(Deserialize, Serialize)]
/// pub struct Config {
///     setting1: usize,
///     setting2: usize
/// }
///
/// impl Default for Config {
///     fn default() -> Self {
///         Config {
///             setting1: 0,
///             setting2: 5,
///         }
///     }
/// }
///
/// impl Fetchable for Config {
///     fn deserialize_l<T>(f_path: &PathBuf) -> Result<T, Box<dyn Error>>
///         where T: DeserializeOwned + Default + Fetchable {
///         //Config::deserialize_ron(f_path)
///         //Config::deserialize_json(f_path)
///         Config::deserialize_bin(f_path)
///      }
///
///     fn serialize_l(&self) -> Result<Vec<u8>, Box<dyn Error>>
///         where Self: serde::Serialize + Fetchable {
///         //self.serialize_ron()
///         //self.serialize_json()
///         self.serialize_bin()
///     }
/// }
///
/// fn main() -> std::result::Result<(),  Box<dyn Error>> {
///     // Example directory
///     let mut path = env::current_dir()?;
///     // adding file name
///     path.push("config.bin");
///     // fetch or default will either open file from disk and deserialize
///     // or return the default for Config and a boolean indicating the
///     // config is default.
///     let config: (Config, bool) = Config::fetch_or_default(&path)?;
///     if config.1 {
///         //config.0.save(&path);
///     }
///     let config = config.0;
///     println!("Config: {}, {}", config.setting1, config.setting2);
///     Ok(())
/// }
///
/// ```
///
pub trait Fetchable {
    /// #
    ///
    /// # Parameters
    ///
    /// f_path: Path to file to open /path/to/your/file.txt
    ///
    /// Impl this method to define behavior.
    ///
    /// T::deserialize_json
    ///
    fn deserialize_l<T: DeserializeOwned + Default + Fetchable>(
        f_path: &PathBuf,
    ) -> Result<T, Box<dyn Error>>;

    /// #
    ///
    /// Deserialize from bincode format.
    ///
    /// # Parameters
    ///
    /// f_path: Path to file to open /path/to/your/file.txt
    ///
    /// # Panics
    ///
    /// If File::open fails
    ///
    fn deserialize_bin<T>(f_path: &PathBuf) -> Result<T, Box<dyn Error>>
        where T: DeserializeOwned + Default {
        let mut file = File::open(f_path)?;
        let mut buffer = Vec::new();
        file.read_to_end(&mut buffer)?;
        let item: T = match bincode::deserialize(&buffer) {
            Ok(item) => item,
            Err(_e) => T::default(),
        };
        buffer.clear();
        Ok(item)
    }

    /// #
    ///
    /// Deserialize from Json format.
    ///
    /// # Parameters
    ///
    /// f_path: Path to file to open /path/to/your/file.txt
    ///
    /// # Panics
    ///
    /// Panics if File::open fails
    ///
    fn deserialize_json<T>(f_path: &PathBuf) -> Result<T, Box<dyn Error>>
        where T: DeserializeOwned + Default {
        let mut file = File::open(f_path)?;
        let mut buffer = String::new();
        file.read_to_string(&mut buffer)?;
        let item: T = match serde_json::from_str(&buffer) {
            Ok(item) => item,
            Err(_e) => T::default(),
        };
        buffer.clear();
        Ok(item)
    }

    /// #
    ///
    /// Deserialize from ron format.
    ///
    /// # Parameters
    ///
    /// f_path: Path to file to open /home/$USER/folder/file.txt
    ///
    /// # Panics
    ///
    /// Panics if File::open fails
    ///
    fn deserialize_ron<T>(f_path: &PathBuf) -> Result<T, Box<dyn Error>>
        where T: DeserializeOwned + Default {
        let mut file = File::open(f_path)?;
        let mut buffer = String::new();
        file.read_to_string(&mut buffer)?;
        let item: T = match from_str(&buffer) {
            Ok(item) => item,
            Err(_e) => T::default(),
        };
        buffer.clear();
        Ok(item)
    }

    /// #
    ///
    /// # Impl method
    ///
    /// Impl this method to define behavior.
    ///
    fn serialize_l(&self) -> Result<Vec<u8>, Box<dyn Error>>
    where
        Self: serde::Serialize + Fetchable;

    /// #
    ///
    /// # Bin
    ///
    fn serialize_bin(&self) -> Result<Vec<u8>, Box<dyn Error>>
    where
        Self: serde::Serialize,
    {
        let mut buf = vec![];
        buf.clear();
        buf = bincode::serialize(self)?;
        Ok(buf)
    }

    /// #
    ///
    /// # RON
    ///
    fn serialize_ron(&self) -> Result<Vec<u8>, Box<dyn Error>>
    where
        Self: serde::Serialize,
    {
        Ok(
            ron::ser::to_string_pretty(&self, ron::ser::PrettyConfig::default())
                .expect("Failed pretty string.")
                .as_bytes()
                .to_vec(),
        )
    }

    /// #
    ///
    /// # Json
    ///
    fn serialize_json(&self) -> Result<Vec<u8>, Box<dyn Error>>
    where
        Self: serde::Serialize,
    {
        Ok(
            serde_json::ser::to_string_pretty(&self)
                .expect("Failed pretty string.")
                .as_bytes()
                .to_vec(),
        )
    }

    /// #
    ///
    /// # Save
    ///
    /// Use this version of save when container cannot be implemented.
    ///
    fn save(&self, path: &PathBuf) -> Result<(), Box<dyn Error>>
    where
        Self: serde::Serialize + Fetchable,
    {
        let mut f = File::create(&path)?;
        let content = self.serialize_l()?;
        f.write_all(content.as_slice())?;
        match f.sync_all() {
            Ok(_) => Ok(()),
            Err(e) => Err(Box::new(e)),
        }
    }

    /// #
    ///
    /// Fetch an item serialized to file
    ///
    /// # Parameters
    ///
    /// * `file_path` - Reference to path buffer of file of type T
    ///
    /// # Returns
    ///
    /// * `Result<(T, bool)>` - Returns tuple containing T and a bool value indicating if a config was retrieved or default. True for default config use.
    ///
    fn fetch_or_default<T>(file_path: &PathBuf) -> Result<(T, bool), Box<dyn Error>>
        where T: Default + DeserializeOwned + Fetchable {
        let path = file_path.to_path_buf();
        let result: (T, bool) = if path.exists() {
            match T::deserialize_l(&path) {
                Ok(t) => (t, false),
                Err(_) => (T::default(), true),
            }
        } else {
            (T::default(), true)
        };

        Ok(result)
    }
}