preferences_ron/
lib.rs

1//! *Read and write user-specific application data*
2//!
3//! This crate allows Rust developers to store and retrieve user-local preferences and other
4//! application data in a flexible and platform-appropriate way.
5//!
6//! Though it was originally inspired by Java's convenient
7//! [Preferences API](https://docs.oracle.com/javase/8/docs/api/java/util/prefs/Preferences.html),
8//! this crate is more flexible. *Any* struct or enum that implements
9//! [`serde`][serde-api]'s `Serialize` and `Deserialize`
10//! traits can be stored and retrieved as user data. Implementing those traits is
11//! trivial; just include the crate `serde_derive` (don't forget `#[macro_use]`!) and add
12//! `#[derive(Serialize, Deserialize)` to your struct definition. (See examples below.)
13//!
14//! # Usage
15//! For convenience, the type [`PreferencesMap<T>`](type.PreferencesMap.html) is provided. (It's
16//! actually just [`std::collections::HashMap<String, T>`][hashmap-api], where `T` defaults to
17//! `String`). This mirrors the Java API, which models user data as an opaque key-value store. As
18//! long as  `T` is serializable and deserializable, [`Preferences`](trait.Preferences.html)
19//! will be implemented for your map instance. This allows you to seamlessly save and load
20//! user data with the `save(..)` and `load(..)` trait methods from `Preferences`.
21//!
22//! # Basic example
23//! ```
24//! extern crate preferences_ron;
25//! use preferences_ron::{AppInfo, PreferencesMap, Preferences};
26//!
27//! const APP_INFO: AppInfo = AppInfo{name: "preferences", author: "Rust language community"};
28//!
29//! fn main() {
30//!
31//!     // Create a new preferences key-value map
32//!     // (Under the hood: HashMap<String, String>)
33//!     let mut faves: PreferencesMap<String> = PreferencesMap::new();
34//!
35//!     // Edit the preferences (std::collections::HashMap)
36//!     faves.insert("color".into(), "blue".into());
37//!     faves.insert("programming language".into(), "Rust".into());
38//!
39//!     // Store the user's preferences
40//!     let prefs_key = "tests/docs/basic-example";
41//!     let save_result = faves.save(&APP_INFO, prefs_key);
42//!     assert!(save_result.is_ok());
43//!
44//!     // ... Then do some stuff ...
45//!
46//!     // Retrieve the user's preferences
47//!     let load_result = PreferencesMap::<String>::load(&APP_INFO, prefs_key);
48//!     assert!(load_result.is_ok());
49//!     assert_eq!(load_result.unwrap(), faves);
50//!
51//! }
52//! ```
53//!
54//! # Using custom data types
55//! ```
56//! #[macro_use]
57//! extern crate serde_derive;
58//! extern crate preferences_ron;
59//! use preferences_ron::{AppInfo, Preferences};
60//!
61//! const APP_INFO: AppInfo = AppInfo{name: "preferences", author: "Rust language community"};
62//!
63//! // Deriving `Serialize` and `Deserialize` on a struct/enum automatically implements
64//! // the `Preferences` trait.
65//! #[derive(Serialize, Deserialize, PartialEq, Debug)]
66//! struct PlayerData {
67//!     level: u32,
68//!     health: f32,
69//! }
70//!
71//! fn main() {
72//!
73//!     let player = PlayerData{level: 2, health: 0.75};
74//!
75//!     let prefs_key = "tests/docs/custom-types";
76//!     let save_result = player.save(&APP_INFO, prefs_key);
77//!     assert!(save_result.is_ok());
78//!
79//!     // Method `load` is from trait `Preferences`.
80//!     let load_result = PlayerData::load(&APP_INFO, prefs_key);
81//!     assert!(load_result.is_ok());
82//!     assert_eq!(load_result.unwrap(), player);
83//!
84//! }
85//! ```
86//!
87//! # Using custom data types with `PreferencesMap`
88//! ```
89//! #[macro_use]
90//! extern crate serde_derive;
91//! extern crate preferences_ron;
92//! use preferences_ron::{AppInfo, PreferencesMap, Preferences};
93//!
94//! const APP_INFO: AppInfo = AppInfo{name: "preferences", author: "Rust language community"};
95//!
96//! #[derive(Serialize, Deserialize, PartialEq, Debug)]
97//! struct Point(f32, f32);
98//!
99//! fn main() {
100//!
101//!     let mut places = PreferencesMap::new();
102//!     places.insert("treasure".into(), Point(1.0, 1.0));
103//!     places.insert("home".into(), Point(-1.0, 6.6));
104//!
105//!     let prefs_key = "tests/docs/custom-types-with-preferences-map";
106//!     let save_result = places.save(&APP_INFO, prefs_key);
107//!     assert!(save_result.is_ok());
108//!
109//!     let load_result = PreferencesMap::load(&APP_INFO, prefs_key);
110//!     assert!(load_result.is_ok());
111//!     assert_eq!(load_result.unwrap(), places);
112//!
113//! }
114//! ```
115//!
116//! # Using custom data types with serializable containers
117//! ```
118//! #[macro_use]
119//! extern crate serde_derive;
120//! extern crate preferences_ron;
121//! use preferences_ron::{AppInfo, Preferences};
122//!
123//! const APP_INFO: AppInfo = AppInfo{name: "preferences", author: "Rust language community"};
124//!
125//! #[derive(Serialize, Deserialize, PartialEq, Debug)]
126//! struct Point(usize, usize);
127//!
128//! fn main() {
129//!
130//!     let square = vec![
131//!         Point(0,0),
132//!         Point(1,0),
133//!         Point(1,1),
134//!         Point(0,1),
135//!     ];
136//!
137//!     let prefs_key = "tests/docs/custom-types-in-containers";
138//!     let save_result = square.save(&APP_INFO, prefs_key);
139//!     assert!(save_result.is_ok());
140//!
141//!     let load_result = Vec::<Point>::load(&APP_INFO, prefs_key);
142//!     assert!(load_result.is_ok());
143//!     assert_eq!(load_result.unwrap(), square);
144//!
145//! }
146//! ```
147//!
148//! # Under the hood
149//! Data is written to flat files under the active user's home directory in a location specific to
150//! the operating system. This location is decided by the `app_dirs` crate with the data type
151//! `UserConfig`. Within the data directory, the files are stored in a folder hierarchy that maps
152//! to a sanitized version of the preferences key passed to `save(..)`.
153//!
154//! The data is stored in JSON format. This has several advantages:
155//!
156//! * Human-readable and self-describing
157//! * More compact than e.g. XML
158//! * Better adoption rates and language compatibility than e.g. TOML
159//! * Not reliant on a consistent memory layout like e.g. binary
160//!
161//! You could, of course, implement `Preferences` yourself and store your user data in
162//! whatever location and format that you wanted. But that would defeat the purpose of this
163//! library. &#128522;
164//!
165//! [hashmap-api]: https://doc.rust-lang.org/nightly/std/collections/struct.HashMap.html
166//! [serde-api]: https://crates.io/crates/serde
167
168#![warn(missing_docs)]
169
170extern crate app_dirs;
171extern crate ron;
172extern crate serde;
173
174use app_dirs::{get_app_dir, get_data_root, AppDataType};
175pub use app_dirs::{AppDirsError, AppInfo};
176use serde::de::DeserializeOwned;
177use serde::Serialize;
178use std::collections::HashMap;
179use std::ffi::OsString;
180use std::fmt;
181use std::fs::{create_dir_all, File};
182use std::io::{self, ErrorKind, Read, Write};
183use std::path::PathBuf;
184use std::string::FromUtf8Error;
185
186const DATA_TYPE: AppDataType = AppDataType::UserConfig;
187static PREFS_FILE_EXTENSION: &str = ".prefs.ron";
188static DEFAULT_PREFS_FILENAME: &str = "prefs.ron";
189
190/// Generic key-value store for user data.
191///
192/// This is actually a wrapper type around [`std::collections::HashMap<String, T>`][hashmap-api]
193/// (with `T` defaulting to `String`), so use the `HashMap` API methods to access and change user
194/// data in memory.
195///
196/// To save or load user data, use the methods defined for the trait
197/// [`Preferences`](trait.Preferences.html), which will be automatically implemented for
198/// `PreferencesMap<T>` as long as `T` is serializable. (See the
199/// [module documentation](index.html) for examples and more details.)
200///
201/// [hashmap-api]: https://doc.rust-lang.org/nightly/std/collections/struct.HashMap.html
202pub type PreferencesMap<T = String> = HashMap<String, T>;
203
204/// Error type representing the errors that can occur when saving or loading user data.
205#[derive(Debug)]
206pub enum PreferencesError {
207    /// An error occurred during JSON serialization or deserialization.
208    Serializer(ron::Error),
209    /// An error occurred during preferences file I/O.
210    Io(io::Error),
211    /// Couldn't figure out where to put or find the serialized data.
212    Directory(AppDirsError),
213}
214
215impl fmt::Display for PreferencesError {
216    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
217        use PreferencesError::*;
218        match *self {
219            Serializer(ref e) => e.fmt(f),
220            Io(ref e) => e.fmt(f),
221            Directory(ref e) => e.fmt(f),
222        }
223    }
224}
225
226impl std::error::Error for PreferencesError {
227    fn cause(&self) -> Option<&dyn std::error::Error> {
228        use PreferencesError::*;
229        Some(match *self {
230            Serializer(ref e) => e,
231            Io(ref e) => e,
232            Directory(ref e) => e,
233        })
234    }
235}
236
237impl From<ron::Error> for PreferencesError {
238    fn from(e: ron::Error) -> Self {
239        PreferencesError::Serializer(e)
240    }
241}
242
243impl From<FromUtf8Error> for PreferencesError {
244    fn from(_: FromUtf8Error) -> Self {
245        let kind = ErrorKind::InvalidData;
246        let msg = "Preferences file contained invalid UTF-8";
247        let err = io::Error::new(kind, msg);
248        PreferencesError::Io(err)
249    }
250}
251
252impl From<std::io::Error> for PreferencesError {
253    fn from(e: std::io::Error) -> Self {
254        PreferencesError::Io(e)
255    }
256}
257
258impl From<AppDirsError> for PreferencesError {
259    fn from(e: AppDirsError) -> Self {
260        PreferencesError::Directory(e)
261    }
262}
263
264/// Trait for types that can be saved & loaded as user data.
265///
266/// This type is automatically implemented for any struct/enum `T` which implements both
267/// `Serialize` and `Deserialize` (from `serde`). (Trivially, you can annotate the type
268/// with `#[derive(Serialize, Deserialize)`). It is encouraged to use the provided
269/// type, [`PreferencesMap`](type.PreferencesMap.html), to bundle related user preferences.
270///
271/// For the `app` parameter of `save(..)` and `load(..)`, it's recommended that you use a single
272/// `const` instance of `AppInfo` that represents your program:
273///
274/// ```
275/// use preferences_ron::AppInfo;
276/// const APP_INFO: AppInfo = AppInfo{name: "Awesome App", author: "Dedicated Dev"};
277/// ```
278///
279/// The `key` parameter of `save(..)` and `load(..)` should be used to uniquely identify different
280/// preferences data. It roughly maps to a platform-dependent directory hierarchy, with forward
281/// slashes used as separators on all platforms. Keys are sanitized to be valid paths; to ensure
282/// human-readable paths, use only letters, digits, spaces, hyphens, underscores, periods, and
283/// slashes.
284///
285/// # Example keys
286/// * `options/graphics`
287/// * `saves/quicksave`
288/// * `bookmarks/favorites`
289pub trait Preferences: Sized {
290    /// Saves the current state of this object. Implementation is platform-dependent, but the data
291    /// will be local to the active user.
292    ///
293    /// # Failures
294    /// If a serialization or file I/O error (e.g. permission denied) occurs.
295    fn save<S: AsRef<str>>(&self, app: &AppInfo, key: S) -> Result<(), PreferencesError>;
296    /// Loads this object's state from previously saved user data with the same `key`. This is
297    /// an instance method which completely overwrites the object's state with the serialized
298    /// data. Thus, it is recommended that you call this method immediately after instantiating
299    /// the preferences object.
300    ///
301    /// # Failures
302    /// If a deserialization or file I/O error (e.g. permission denied) occurs, or if no user data
303    /// exists at that `path`.
304    fn load<S: AsRef<str>>(app: &AppInfo, key: S) -> Result<Self, PreferencesError>;
305    /// Same as `save`, but writes the serialized preferences to an arbitrary writer.
306    fn save_to<W: Write>(&self, writer: &mut W) -> Result<(), PreferencesError>;
307    /// Same as `load`, but reads the serialized preferences from an arbitrary writer.
308    fn load_from<R: Read>(reader: &mut R) -> Result<Self, PreferencesError>;
309}
310
311fn compute_file_path<S: AsRef<str>>(app: &AppInfo, key: S) -> Result<PathBuf, PreferencesError> {
312    let mut path = get_app_dir(DATA_TYPE, app, key.as_ref())?;
313    let new_name = match path.file_name() {
314        Some(name) if !name.is_empty() => {
315            let mut new_name = OsString::with_capacity(name.len() + PREFS_FILE_EXTENSION.len());
316            new_name.push(name);
317            new_name.push(PREFS_FILE_EXTENSION);
318            new_name
319        }
320        _ => DEFAULT_PREFS_FILENAME.into(),
321    };
322    path.set_file_name(new_name);
323    Ok(path)
324}
325
326impl<T> Preferences for T
327where
328    T: Serialize + DeserializeOwned + Sized,
329{
330    fn save<S>(&self, app: &AppInfo, key: S) -> Result<(), PreferencesError>
331    where
332        S: AsRef<str>,
333    {
334        let path = compute_file_path(app, key.as_ref())?;
335        path.parent().map(create_dir_all);
336        let mut file = File::create(path)?;
337        self.save_to(&mut file)
338    }
339    fn load<S: AsRef<str>>(app: &AppInfo, key: S) -> Result<Self, PreferencesError> {
340        let path = compute_file_path(app, key.as_ref())?;
341        let mut file = File::open(path)?;
342        Self::load_from(&mut file)
343    }
344    fn save_to<W: Write>(&self, writer: &mut W) -> Result<(), PreferencesError> {
345        ron::ser::to_writer_pretty(writer, self, ron::ser::PrettyConfig::new()).map_err(Into::into)
346    }
347    fn load_from<R: Read>(reader: &mut R) -> Result<Self, PreferencesError> {
348        ron::de::from_reader(reader).map_err(Into::into)
349    }
350}
351
352/// Get full path to the base directory for preferences.
353///
354/// This makes no guarantees that the specified directory path actually *exists* (though you can
355/// easily use `std::fs::create_dir_all(..)`). Returns `None` if the directory cannot be determined
356/// or is not available on the current platform.
357pub fn prefs_base_dir() -> Option<PathBuf> {
358    get_data_root(AppDataType::UserConfig).ok()
359}
360
361#[cfg(test)]
362mod tests {
363    use {AppInfo, Preferences, PreferencesMap};
364    const APP_INFO: AppInfo = AppInfo {
365        name: "preferences",
366        author: "Rust language community",
367    };
368    const TEST_PREFIX: &str = "tests/module";
369    fn gen_test_name(name: &str) -> String {
370        TEST_PREFIX.to_owned() + "/" + name
371    }
372    fn gen_sample_prefs() -> PreferencesMap<String> {
373        let mut prefs = PreferencesMap::new();
374        prefs.insert("foo".into(), "bar".into());
375        prefs.insert("age".into(), "23".into());
376        prefs.insert("PI".into(), "3.14".into());
377        prefs.insert("offset".into(), "-9".into());
378        prefs
379    }
380    #[test]
381    fn test_save_load() {
382        let sample_map = gen_sample_prefs();
383        let sample_other: i32 = 4;
384        let name_map = gen_test_name("save-load-map");
385        let name_other = gen_test_name("save-load-other");
386        let save_map_result = sample_map.save(&APP_INFO, &name_map);
387        let save_other_result = sample_other.save(&APP_INFO, &name_other);
388        assert!(save_map_result.is_ok());
389        assert!(save_other_result.is_ok());
390        let load_map_result = PreferencesMap::load(&APP_INFO, &name_map);
391        let load_other_result = i32::load(&APP_INFO, &name_other);
392        assert!(load_map_result.is_ok());
393        assert!(load_other_result.is_ok());
394        assert_eq!(load_map_result.unwrap(), sample_map);
395        assert_eq!(load_other_result.unwrap(), sample_other);
396    }
397}