stylo_config/
lib.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::collections::HashMap;
6use std::sync::{LazyLock, RwLock};
7
8static PREFS: LazyLock<Preferences> = LazyLock::new(Preferences::default);
9
10#[derive(Debug, Default)]
11pub struct Preferences {
12    bool_prefs: RwLock<HashMap<String, bool>>,
13    i32_prefs: RwLock<HashMap<String, i32>>,
14}
15
16impl Preferences {
17    pub fn get_bool(&self, key: &str) -> bool {
18        let prefs = self.bool_prefs.read().expect("RwLock is poisoned");
19        *prefs.get(key).unwrap_or(&false)
20    }
21
22    pub fn get_i32(&self, key: &str) -> i32 {
23        let prefs = self.i32_prefs.read().expect("RwLock is poisoned");
24        *prefs.get(key).unwrap_or(&0)
25    }
26
27    pub fn set_bool(&self, key: &str, value: bool) {
28        let mut prefs = self.bool_prefs.write().expect("RwLock is poisoned");
29
30        // Avoid cloning the key if it exists.
31        if let Some(pref) = prefs.get_mut(key) {
32            *pref = value;
33        } else {
34            prefs.insert(key.to_owned(), value);
35        }
36    }
37
38    pub fn set_i32(&self, key: &str, value: i32) {
39        let mut prefs = self.i32_prefs.write().expect("RwLock is poisoned");
40
41        // Avoid cloning the key if it exists.
42        if let Some(pref) = prefs.get_mut(key) {
43            *pref = value;
44        } else {
45            prefs.insert(key.to_owned(), value);
46        }
47    }
48}
49
50pub fn get_bool(key: &str) -> bool {
51    PREFS.get_bool(key)
52}
53
54pub fn get_i32(key: &str) -> i32 {
55    PREFS.get_i32(key)
56}
57
58pub fn set_bool(key: &str, value: bool) {
59    PREFS.set_bool(key, value)
60}
61
62pub fn set_i32(key: &str, value: i32) {
63    PREFS.set_i32(key, value)
64}
65
66#[test]
67fn test() {
68    let prefs = Preferences::default();
69
70    // Prefs have default values when unset.
71    assert_eq!(prefs.get_bool("foo"), false);
72    assert_eq!(prefs.get_i32("bar"), 0);
73
74    // Prefs can be set and retrieved.
75    prefs.set_bool("foo", true);
76    prefs.set_i32("bar", 1);
77    assert_eq!(prefs.get_bool("foo"), true);
78    assert_eq!(prefs.get_i32("bar"), 1);
79    prefs.set_bool("foo", false);
80    prefs.set_i32("bar", 2);
81    assert_eq!(prefs.get_bool("foo"), false);
82    assert_eq!(prefs.get_i32("bar"), 2);
83
84    // Each value type currently has an independent namespace.
85    prefs.set_i32("foo", 3);
86    prefs.set_bool("bar", true);
87    assert_eq!(prefs.get_i32("foo"), 3);
88    assert_eq!(prefs.get_bool("foo"), false);
89    assert_eq!(prefs.get_bool("bar"), true);
90    assert_eq!(prefs.get_i32("bar"), 2);
91}