# misc/persistedstore (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/misc/persistedstore/

Persistent store.
- A port of the original misc/persistedstore.js. Saves a state object as JSON under one key and notifies subscribers when it changes.
- If the version number (version) differs or parsing fails, it falls back to the defaults.
- Saving uses LocalStorage. The save format ({"version":1,"state":{...}}) is the same as the original, so on the web it reads the original game's saves as is.
  set_storage_backend can put only this store somewhere else (LocalStorageBackend, such as a platform's storage).
  The passed storage is put in `Rc<RefCell>`. get_storage_backend returns that Rc, and the caller borrows it with borrow / borrow_mut.
  (reading or writing this store while it is borrowed gives empty text for reads, and writes report it and move on)
- Usage:
  ```text
    let mut store = PersistedStore::new("game.settings", serde_json::json!({ "volume": 0.8, "is_muted": false }), 1);
    store.set(serde_json::json!({ "volume": 0.5 }));
    let volume = store.get()["volume"].as_f64();
  ```
- Merging is the same as the original Object.assign. Arrays are merged by index keys ("0", "1" ...) (even if the saved state is an array), and the key order puts index-like keys first from the smallest number, like JS objects.
- Differences from the original:
  The state object is serde_json::Value (an object). Values that are neither objects nor arrays are treated as an empty object. (the original Object.assign merges a string by character index keys)
  subscribe returns a subscription number (PersistedStoreSubscription) instead of an unsubscribe function, and unsubscribe(number) removes it.
  Rust String cannot hold unpaired surrogates, so such text saved by the original (like \ud83d from JSON.stringify) appears as the replacement character (U+FFFD) in the state from get.
  The original JS code units of that text are read with get_string_code_units and written with set_string_code_units. (the same form as LocalStorage *_code_units, the same value as the original string)
  Their places are remembered when reading, and writing back unmodified writes \udXXX like the original. (misc/storagetext.rs, saves from the original version are not lost when read and rewritten)

## PersistedStoreSubscription (struct) (Clone, Copy, Debug, PartialEq, Eq, Hash)

Subscription number. (pass it to unsubscribe)

Example: Ending only one subscription by its subscription number

```rust
use std::cell::Cell;
use std::rc::Rc;
use vanilla::{LocalStorage, PersistedStore, PersistedStoreSubscription};

let storage_directory_path = std::env::temp_dir().join(format!("vanillaPersistedStoreSubscriptionExample-{}", std::process::id()));
LocalStorage::set_storage_directory(Some(storage_directory_path.clone()));
let mut store = PersistedStore::new("example.progress", serde_json::json!({ "stage": 1 }), 1);
let notified_count = Rc::new(Cell::new(0));
let notified_count_for_first = notified_count.clone();
let notified_count_for_second = notified_count.clone();
let first_subscription: PersistedStoreSubscription = store.subscribe(move |_state| {
	notified_count_for_first.set(notified_count_for_first.get() + 1);
});
let second_subscription = store.subscribe(move |_state| {
	notified_count_for_second.set(notified_count_for_second.get() + 10);
});
assert_ne!(first_subscription, second_subscription);
store.unsubscribe(first_subscription);
store.set(serde_json::json!({ "stage": 3 }));
assert_eq!(notified_count.get(), 10);
let _ = std::fs::remove_dir_all(&storage_directory_path);
```

## PersistedStore (struct)

Persistent store.

Example: Save settings and get notified on change

```rust
use std::cell::Cell;
use std::rc::Rc;
use vanilla::{LocalStorage, PersistedStore};

let storage_directory_path = std::env::temp_dir().join(format!("vanillaPersistedStoreExample-{}", std::process::id()));
LocalStorage::set_storage_directory(Some(storage_directory_path.clone()));
let mut store = PersistedStore::new("example.settings", serde_json::json!({ "volume": 1, "language": "en" }), 1);
let changed_count = Rc::new(Cell::new(0));
let changed_count_for_subscriber = changed_count.clone();
let subscription = store.subscribe(move |state| {
	println!("changed {}", state["volume"]);
	changed_count_for_subscriber.set(changed_count_for_subscriber.get() + 1);
});
store.set(serde_json::json!({ "volume": 0.5 }));
let state = store.get();
assert_eq!(state["volume"], 0.5);
assert_eq!(state["language"], "en");
assert_eq!(changed_count.get(), 1);
let reloaded_store = PersistedStore::new("example.settings", serde_json::json!({ "volume": 1, "language": "en" }), 1);
assert_eq!(reloaded_store.get()["volume"], 0.5);
store.unsubscribe(subscription);
store.reset();
assert_eq!(store.get()["volume"], 1);
assert_eq!(changed_count.get(), 1);
let _ = std::fs::remove_dir_all(&storage_directory_path);
```

- `pub fn new(storage_key: &str, default_state: Value, version: i64) -> PersistedStore` (constructor, since 0.3.2): Constructor. (reads from the storage on creation)
  - `storage_key` &str: Storage key that holds the state.
  - `default_state` Value: Default state. (a copy is used when nothing is stored or the version differs)
  - `version` i64: Version number of the saved format. (falls back to the default state if it differs from the stored version)
  - returns PersistedStore: Persistent store with the state read from the storage.
- `pub fn get(&self) -> &Value` (method, since 0.3.2): Returns the state. (an object Value. Use set / replace to modify it)
  - returns &Value: The current state.
- `pub fn set(&mut self, partial_state: Value)` (method, since 0.3.2): Updates part of the state. (shallow merges, then saves and notifies the subscribers)
  - `partial_state` Value: Object with only the keys and values to change.
- `pub fn get_string_code_units(&self, path: &[JsonPathSegment]) -> Option<Vec<u16>>` (method, since 0.4.0): The JS code units of a string in the state. (UTF-16, unpaired surrogates exactly as in the original string, the same form as LocalStorage::get_item_code_units)
  - `path` &[JsonPathSegment]: The string's place from the state. (keys and array indices)
  - returns Option<Vec<u16>>: The UTF-16 units of the string at that place. (with the unpaired surrogates saved by the original if any, otherwise the string expanded to UTF-16) None if that place is not a string.

  Example: Read and write JS code units at a string place

  ```rust
  use serde_json::json;
  use vanilla::misc::storagetext::JsonPathSegment;
  use vanilla::{LocalStorage, PersistedStore};
  
  LocalStorage::set_storage_directory(Some(std::env::temp_dir().join("vanilla_doctest_persistedstore_code_units")));
  let mut store = PersistedStore::new("doctest.code_units", json!({ "name": "" }), 1);
  let name_path = [JsonPathSegment::Key(String::from("name"))];
  store.set_string_code_units(&name_path, &[0x61, 0xD83D]);
  assert_eq!(store.get()["name"], json!("a\u{fffd}"));
  assert_eq!(store.get_string_code_units(&name_path), Some(vec![0x61, 0xD83D]));
  assert_eq!(store.read_stored_text(), r#"{"version":1,"state":{"name":"a\ud83d"}}"#);
  ```

- `pub fn set_string_code_units(&mut self, path: &[JsonPathSegment], code_units: &[u16]) -> bool` (method, since 0.4.0): Writes a string in the state as JS code units. (unpaired surrogates are saved as \udXXX like the original, then it saves and notifies subscribers)
  - Missing keys are created as objects on the way down. It does not write if an array index is missing or it would pass through a value that is neither an object nor an array.
  - `path` &[JsonPathSegment]: The string's place from the state. (keys and array indices, nothing is written if empty)
  - `code_units` &[u16]: The UTF-16 units to write.
  - returns bool: true if it wrote.
- `pub fn replace(&mut self, next_state: Value)` (method, since 0.3.2): Replaces the whole state.
  - `next_state` Value: New state. (arrays are spread into an object with index keys, and anything that is neither an object nor an array is treated as an empty object)
- `pub fn reset(&mut self)` (method, since 0.3.2): Resets to the default value.
- `pub fn subscribe(&mut self, subscriber: impl FnMut(&Value) + 'static) -> PersistedStoreSubscription` (method, since 0.3.2): Subscribes. (returns the subscription number)
  - `subscriber` impl FnMut(&Value) + 'static: Function that receives the current state on every notification (set, replace, reset, set_storage_backend, notify).
  - returns PersistedStoreSubscription: Subscription number. (pass it to unsubscribe)
- `pub fn unsubscribe(&mut self, subscription: PersistedStoreSubscription)` (method, since 0.3.2): Unsubscribes. (in place of the unsubscribe function returned by the original subscribe)
  - `subscription` PersistedStoreSubscription: Subscription number returned by subscribe. (does nothing if unknown)
- `pub fn notify(&mut self)` (method, since 0.3.2): Notifies the subscribers. (in subscription order)
- `pub fn read_from_storage(&self) -> Value` (method, since 0.3.2): Reads from the storage. (overlays the saved state on the defaults. Keys not in the defaults are kept, and newly added default keys are filled with the defaults)
  - If state is not an object or an array, the defaults are used. (original typeof state === "object", arrays are merged with index keys)
  - returns Value: A new object with the stored state laid over the default state. (a copy of the default state if missing, a different version or unparsable)
- `pub fn write_to_storage(&self)` (method, since 0.3.2): Writes to the storage. ({"version": version number, "state": state})
- `pub fn read_stored_text(&self) -> String` (method, since 0.4.0): Reads the stored text. (empty text if missing or unreadable)
  - returns String: The stored JSON text. An empty string if missing or unreadable.
- `pub fn set_storage_backend(&mut self, storage_backend: Option<Box<dyn LocalStorageBackend>>)` (method, since 0.4.0): Swaps the backend used only by this store. (None uses LocalStorage. Rereads the state from there and notifies the subscribers)
  - `storage_backend` Option<Box<dyn LocalStorageBackend>>: Storage used only by this store. (LocalStorage if None)
- `pub fn get_storage_backend(&self) -> Option<Rc<RefCell<Box<dyn LocalStorageBackend>>>>` (method, since 0.4.0): Returns the backend used only by this store. (None if none, use borrow / borrow_mut to borrow it)
  - returns Option<Rc<RefCell<Box<dyn LocalStorageBackend>>>>: Storage used only by this store. None if none.
- `pub fn get_storage_key(&self) -> &str` (method, since 0.3.2): Returns the storage key.
  - returns &str: Storage key.
