Skip to main content

day_part_preferences/
lib.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! day-part-preferences: a headless cross-platform persistent key/value store. No UI; any Rust code can
5//! depend on this crate and call [`set`] / [`get`] / [`remove`] / [`contains`] to persist small
6//! strings across launches through the platform's native preferences facility.
7//!
8//! ```no_run
9//! day_part_preferences::set("greeting", "hello");
10//! assert_eq!(day_part_preferences::get("greeting").as_deref(), Some("hello"));
11//! assert!(day_part_preferences::contains("greeting"));
12//! day_part_preferences::remove("greeting");
13//! ```
14//!
15//! Platform selection is purely `#[cfg(target_os)]`/`#[cfg(target_env)]` (persistence is an OS
16//! concern, not a widget-toolkit one): macOS and iOS share one `NSUserDefaults` file, Android uses
17//! `SharedPreferences` (via a Java shim staged by `day build`), and Linux / Windows / HarmonyOS
18//! share a file-backed store under the per-user config directory. Values persist until removed and
19//! survive process restarts. Platforms without any store fall back to a no-op that always reports
20//! failure/absence.
21//!
22//! This is a small **string** store for user settings and lightweight app state, not a database.
23//! Keep values modest; large blobs belong in a file. See docs/prefs.md for the per-platform matrix.
24
25mod typed;
26pub use typed::{
27    MemoryStore, NativeStore, Pref, PrefValue, Store, install_store, persistence_failures,
28};
29
30/// Persist `value` under `key`, overwriting any previous value. Returns `true` when the write was
31/// committed. On Apple platforms this always succeeds; on Android it reflects
32/// `SharedPreferences.Editor.commit()`; on the file-backed platforms it reflects whether the store
33/// file could be written (a missing config directory or a read-only home yields `false`).
34pub fn set(key: &str, value: &str) -> bool {
35    imp::set(key, value)
36}
37
38/// Read the string stored under `key`, or `None` if it is absent (or no store is available on the
39/// platform). A stored empty string is `Some("")`, distinct from an absent key.
40#[must_use]
41pub fn get(key: &str) -> Option<String> {
42    imp::get(key)
43}
44
45/// Delete the value stored under `key`. Returns `true` if a value existed and was removed, `false`
46/// if the key was already absent (or the delete could not be committed).
47pub fn remove(key: &str) -> bool {
48    imp::remove(key)
49}
50
51/// Whether a value is currently stored under `key`.
52#[must_use]
53pub fn contains(key: &str) -> bool {
54    imp::contains(key)
55}
56
57/// Two-way-bind a signal to a stored preference: seed the signal from the store now (when a
58/// stored value exists and parses as `T`), then persist every later change. Call it right
59/// after creating the signal, before anything reads it. The write-back lives in the current
60/// reactive scope, so it stops with the page that created the signal.
61///
62/// ```no_run
63/// let count = day_reactive::Signal::new(0i64);
64/// day_part_preferences::bind("controls.count", count);
65/// ```
66pub fn bind<T>(key: &str, signal: day_reactive::Signal<T>)
67where
68    T: std::str::FromStr + ToString + Clone + 'static,
69{
70    if let Some(stored) = get(key)
71        && let Ok(v) = stored.parse::<T>()
72    {
73        signal.set(v);
74    }
75    let key = key.to_string();
76    day_reactive::watch(
77        move || signal.get(),
78        move |v, _| {
79            let _ = set(&key, &v.to_string());
80        },
81    );
82}
83
84// ---------------------------------------------------------------------------
85// Per-OS implementations. Each exposes:
86//   fn set(&str, &str) -> bool
87//   fn get(&str) -> Option<String>
88//   fn remove(&str) -> bool
89//   fn contains(&str) -> bool
90// ---------------------------------------------------------------------------
91
92// The `memory` feature (what `day`'s headless `mock` backend turns on) replaces every platform
93// store with an in-process map, so tests start empty and never touch the user's preferences.
94#[cfg(feature = "memory")]
95#[path = "memory.rs"]
96mod imp;
97
98// The file store, which the `memory` store hands off to when `DAY_PREFS_DIR` names a directory.
99#[cfg(feature = "memory")]
100#[path = "file.rs"]
101mod file;
102
103// macOS + iOS share one NSUserDefaults impl.
104#[cfg(all(not(feature = "memory"), any(target_os = "macos", target_os = "ios")))]
105#[path = "apple.rs"]
106mod imp;
107
108// Android rides day-platform-android's JVM/Context to reach SharedPreferences via a bundled Java shim.
109#[cfg(all(not(feature = "memory"), target_os = "android"))]
110#[path = "android.rs"]
111mod imp;
112
113// Linux, Windows, and HarmonyOS (also `target_os = "linux"`, with `target_env = "ohos"`) all use the
114// same file-backed store; file.rs resolves the per-OS config directory internally.
115#[cfg(all(
116    not(feature = "memory"),
117    any(target_os = "linux", target_os = "windows")
118))]
119#[path = "file.rs"]
120mod imp;
121
122// The web (web-dom, docs/web.md): localStorage through the day-toolkit-dom shim's imports.
123#[cfg(all(not(feature = "memory"), target_arch = "wasm32"))]
124#[path = "web.rs"]
125mod imp;
126
127// Any other platform: no persistent store.
128#[cfg(not(any(
129    feature = "memory",
130    target_os = "macos",
131    target_os = "ios",
132    target_os = "android",
133    target_os = "linux",
134    target_os = "windows",
135    target_arch = "wasm32"
136)))]
137mod imp {
138    pub fn set(_key: &str, _value: &str) -> bool {
139        false
140    }
141    pub fn get(_key: &str) -> Option<String> {
142        None
143    }
144    pub fn remove(_key: &str) -> bool {
145        false
146    }
147    pub fn contains(_key: &str) -> bool {
148        false
149    }
150}
151
152#[cfg(test)]
153mod tests {
154    // A full round-trip on platforms with a usable store in a plain test process (Apple
155    // NSUserDefaults / the desktop file store). Android and iOS need a device runtime + Context, so
156    // they are excluded here. The values contain `=` and a newline to exercise the file store's
157    // escaping.
158    #[cfg(any(
159        feature = "memory",
160        target_os = "macos",
161        all(target_os = "linux", not(target_env = "ohos")),
162        target_os = "windows"
163    ))]
164    #[test]
165    fn round_trip() {
166        let key = "day-part-preferences::test::round_trip";
167        // Start from a clean slate regardless of a prior aborted run.
168        let _ = super::remove(key);
169        assert!(!super::contains(key));
170        assert_eq!(super::get(key), None);
171
172        assert!(super::set(key, "hello=day\nsecond line"));
173        assert!(super::contains(key));
174        assert_eq!(super::get(key).as_deref(), Some("hello=day\nsecond line"));
175
176        // Overwrite.
177        assert!(super::set(key, "again"));
178        assert_eq!(super::get(key).as_deref(), Some("again"));
179
180        // Remove, then removing again reports "was already absent".
181        assert!(super::remove(key));
182        assert!(!super::contains(key));
183        assert_eq!(super::get(key), None);
184        assert!(!super::remove(key));
185    }
186
187    // Reading or probing a missing key must never panic on any platform.
188    #[test]
189    fn missing_key_does_not_panic() {
190        let absent = "day-part-preferences::test::definitely-absent-key";
191        let _ = super::get(absent);
192        let _ = super::contains(absent);
193    }
194}