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
//! `persisted` is a library for persisting arbitrary values in your program so
//! they can easily be restored later. The main goals of the library are:
//!
//! - Explicitness: You define exactly what is persisted, and its types
//! - Ease of use: Thin wrappers make persisting values easy
//! - Flexible: `persisted` is data store-agnostic; use any persistence scheme
//! you want, including a database, key-value store, etc.
//!
//! `persisted` was designed originally for use in
//! [Slumber](https://crates.io/crates/slumber), a TUI HTTP client. As such, its
//! main use case is for persisting values between sessions in a user interface.
//! It is very flexible though, and could be used for persisting any type of
//! value in any type of context. `no_std` support means it can even be used in
//! embedded contexts.
//!
//! ## Concepts
//!
//! `persisted` serves as a middleman between your values and your data store.
//! You define your data structures and how your data should be saved,
//! and `persisted` makes sure the data is loaded and stored appropriately. The
//! key concepts are:
//!
//! - Data wrappers: [Persisted] and [PersistedLazy]
//! - These wrap your data to automatically restore and save values from/to
//! the store
//! - Data store: any implementor of [PersistedStore]
//! - Key: A unique identifier for a value in the store. Each persisted value
//! must have its own key. Key types must implement [PersistedKey].
//!
//! ## How Does It Work?
//!
//! `persisted` works by wrapping each persisted value in either [Persisted] or
//! [PersistedLazy]. The wrapper is created with a key and optionally a default
//! value. A request is made to the store to load the most recent value for the
//! key, and if present that value is used. Whenever the value is modified, the
//! store is notified of the new value so it can be saved (see either
//! [Persisted] or [PersistedLazy] for a stricter definition of "is modified").
//!
//! Because the store is accessed from constructors and destructors, it cannot
//! be passed around and must be reachable statically. The easiest way to do
//! this is with either a `static` or `thread_local` definition of your store.
//!
//! ## Example
//!
//! Here's an example of a very simple persistence scheme. The store keeps just
//! a single value.
//!
//! ```
//! use core::cell::Cell;
//! use persisted::{Persisted, PersistedKey, PersistedStore};
//!
//! /// Store index of the selected person
//! #[derive(Default)]
//! struct Store(Cell<Option<usize>>);
//!
//! impl Store {
//! thread_local! {
//! static INSTANCE: Store = Default::default();
//! }
//! }
//!
//! impl PersistedStore<SelectedIndexKey> for Store {
//! fn load_persisted(_key: &SelectedIndexKey) -> Option<usize> {
//! Self::INSTANCE.with(|store| store.0.get())
//! }
//!
//! fn store_persisted(_key: &SelectedIndexKey, value: &usize) {
//! Self::INSTANCE.with(|store| store.0.set(Some(*value)))
//! }
//! }
//!
//! /// Persist the selected value in the list by storing its index. This is simple
//! /// but relies on the list keeping the same items, in the same order, between
//! /// sessions.
//! #[derive(PersistedKey)]
//! #[persisted(usize)]
//! struct SelectedIndexKey;
//!
//! #[derive(Clone, Debug)]
//! #[allow(unused)]
//! struct Person {
//! name: String,
//! age: u32,
//! }
//!
//! /// A list of items, with one item selected
//! struct SelectList<T> {
//! values: Vec<T>,
//! selected_index: Persisted<Store, SelectedIndexKey>,
//! }
//!
//! impl<T> SelectList<T> {
//! fn new(values: Vec<T>) -> Self {
//! Self {
//! values,
//! selected_index: Persisted::new(SelectedIndexKey, 0),
//! }
//! }
//!
//! fn selected(&self) -> &T {
//! &self.values[*self.selected_index]
//! }
//! }
//!
//! let list = vec![
//! Person {
//! name: "Fred".into(),
//! age: 17,
//! },
//! Person {
//! name: "Susan".into(),
//! age: 29,
//! },
//! Person {
//! name: "Ulysses".into(),
//! age: 40,
//! },
//! ];
//!
//! let mut people = SelectList::new(list.clone());
//! *people.selected_index.get_mut() = 1;
//! println!("Selected: {}", people.selected().name);
//! // Selected: Susan
//!
//! let people = SelectList::new(list);
//! // The previous value was restored
//! assert_eq!(*people.selected_index, 1);
//! println!("Selected: {}", people.selected().name);
//! // Selected: Susan
//! ```
//!
//! ### Feature Flags
//!
//! `persisted` supports the following Cargo features:
//! - `derive` (default): Enable derive macros
pub use crate::;
/// Derive macro for [PersistedKey]
pub use PersistedKey;
/// A trait for any data store capable of persisting data. A store is the layer
/// that saves data. It could save it in memory, on disk, over the network, etc.
/// The generic parameter `K` defines which keys this store is capable of
/// saving. For example, if your storage mechanism involves stringifyin keys,
/// your implementation may look like:
///
/// ```ignore
/// struct Store;
///
/// impl<K: PersistedKey + Display> for Store {
/// ...
/// }
/// ```
///
/// This trait enforces three key requirements on all implementors:
///
/// - It is statically accessible, i.e. you can load and store data without a
/// reference to the store
/// - It does not return errors. This does **not** mean it is infallible; it
/// just means that if errors can occur during load/store, they are handled
/// within the implementation rather than propagated. For example, they could
/// be logged for debugging.
/// - Its is synchronous. `async` load and store operations are not supported.
///
/// All three of these requirements derive from how the store is accessed.
/// Values are loaded during initialization by [Persisted]/[PersistedLazy], and
/// saved by their respective guard's `Drop` implementations. In both cases,
/// there is no reference to the store available, and no way of propagating
/// errors or futures. For this reason, your store access should be _fast_, to
/// prevent latency in your program.
/// A unique key mapped to a persisted state value in your program. A key can
/// be any Rust value. Unit keys are useful for top-level fields that appear
/// only once in state. Keys can also carry additional data, such as an index or
/// identifier.
///
/// It's very uncommon that you need to implement this trait yourself. In most
/// cases you can use the derive macro (requires `derive` feature to be
/// enabled).
///
/// Regardless of the structure of your keys, you should ensure that each key
/// (not key *type*) appears only once in your state. More formally, for all
/// keys in your state, `key1 != key2`. If two identical keys exist, they will
/// conflict with each other for the same storage slot in the persistence store.
///
/// Some examples of keys:
///
/// ```
/// use persisted::PersistedKey;
///
/// #[derive(PersistedKey)]
/// #[persisted(u64)]
/// struct SelectedFrobnicatorKey;
///
/// #[derive(PersistedKey)]
/// #[persisted(bool)]
/// struct FrobnicatorEnabled(u64);
///
/// #[derive(PersistedKey)]
/// #[persisted(bool)]
/// enum FrobnicatorComponentEnabled {
/// Component1,
/// Component2,
/// }
/// ```