# misc/localstorage (vanilla-engine 0.4.0)

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

Local storage.
- A port of the original misc/localstorage.js. A set of static functions that persistently store string values under string keys.
- Where it is stored:
  Web (wasm32): window.localStorage as in the original. (separate per origin, keys used as is)
  Desktop: a single localstorage.json in the app folder. (a JSON object of key → string value, saved immediately on every write)
    Windows   %APPDATA%\{app name}\localstorage.json
    Mac       $HOME/Library/Application Support/{app name}/localstorage.json
    Linux     $XDG_DATA_HOME/{app name}/localstorage.json (if missing, $HOME/.local/share/{app name}/...)
    If the environment variables cannot be read, it goes under the temp folder (std::env::temp_dir).
  The app name defaults to the executable name. Change it with set_application_name or set_application_name_from_engine(EngineConfiguration.title).
  The folder can also be set directly with set_storage_directory. (tests, portable games)
- Differences from the original:
  Numbers are f64 like the original (JS number). Conversion to text is exactly the original String(number). (shortest notation, exponents like 1e+21 for 1e21 and above and 1e-7 and below, NaN, Infinity, -0 → "0")
    Reading is exactly the original Number(text). (trims JS whitespace, empty text is 0, 0x, 0o, 0b notation, "1.", ".5", exponents, Infinity, anything else is NaN)
  Desktop storage is held per thread and then written to the file. (the engine runs on one thread)
- Swapping the storage: passing a LocalStorageBackend to set_backend uses it instead of the default storage above. (such as a platform SDK's storage)
  The trait takes the place of the original setBackend object ({ getItem, setItem, removeItem, getKeys, clear }). Exceptions in the original are reported as Err.
  The passed storage is put in `Rc<RefCell>`. get_backend returns that Rc, and the caller borrows it with borrow / borrow_mut.
- Does not crash when blocked: if there is no storage (a blocked localStorage on the web) or writing fails (full, folder cannot be created, Err from the swapped storage),
  values are kept in memory instead for as long as this run lives. (is_memory_fallback, gone after a restart)
- Reads (get_string, get_boolean, get_number, get_json) do not write the default value for missing keys. (same as the original)
- Unpaired surrogates: the original localStorage holds JS strings (UTF-16), so it stores values containing unpaired surrogates (such as cut emoji) and
  JSON that writes them as \ud83d. Rust String cannot hold such text, so they appear as the replacement character (U+FFFD) on the Rust side,
  and writing a read value back unmodified (set_item, set_string, set_json) writes the original UTF-16 units as they were. (misc/storagetext.rs)
  If the original units are needed, get_item_code_units and set_item_code_units read and write the JS string as is.
  Keys are the same. Two keys that differ only by unpaired surrogates (different keys in the original) look like the same text as Rust strings but are stored separately in the storage.
  get_keys_code_units returns all keys in their original units, and get_item_by_key_code_units, set_item_by_key_code_units,
  remove_item_by_key_code_units and contains_key_code_units distinguish both key and value by original units. (exactly the original localStorage functions)
  A Rust string key points to the key with exactly that text if it exists, otherwise to the first unpaired surrogate key that appears as that text. (keys received from get_keys can be used)
  The web writes JS strings as is to the browser localStorage, and the desktop file writes such values and keys as \udXXX like the original JSON.stringify.
  A swapped storage (LocalStorageBackend) exchanges Rust strings, so values are exactly the text that storage holds. (keys are also given as the displayed text)

## LocalStorageBackend (trait)

Swappable storage backend. (the object passed to the original setBackend)
- get_keys and clear are optional. Without get_keys, the key list (get_keys, clear_by_prefix) only shows what was kept in memory instead,
  and without clear, the keys from get_keys are removed one by one.
- Calling LocalStorage again inside these functions uses the default storage. (the swapped backend is borrowed during the call)
  Calling LocalStorage while still borrowing the backend taken with get_backend also uses the default storage.

Example: Swap in your own storage

```rust
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::rc::Rc;
use vanilla::{LocalStorage, LocalStorageBackend};

struct MemoryBackend {
	item_map: Rc<RefCell<BTreeMap<String, String>>>,
}

impl LocalStorageBackend for MemoryBackend {
	fn get_item(&self, key: &str) -> Result<Option<String>, String> {
		Ok(self.item_map.borrow().get(key).cloned())
	}

	fn set_item(&mut self, key: &str, value: &str) -> Result<(), String> {
		self.item_map.borrow_mut().insert(key.to_string(), value.to_string());
		Ok(())
	}

	fn remove_item(&mut self, key: &str) -> Result<(), String> {
		self.item_map.borrow_mut().remove(key);
		Ok(())
	}

	fn get_keys(&self) -> Result<Vec<String>, String> {
		Ok(self.item_map.borrow().keys().cloned().collect())
	}
}

let item_map = Rc::new(RefCell::new(BTreeMap::new()));
LocalStorage::set_backend(Some(Box::new(MemoryBackend { item_map: item_map.clone() })));
LocalStorage::set_string("profile.name", "Player");
assert_eq!(item_map.borrow().get("profile.name").map(|value| value.as_str()), Some("Player"));
assert_eq!(LocalStorage::get_keys(), vec!["profile.name"]);
LocalStorage::set_backend(None);
assert!(LocalStorage::get_backend().is_none());
```

- `fn get_item(&self, key: &str) -> Result<Option<String>, String>` (method, since 0.4.0): Reads a value. (Ok(None) if missing)
  - `key` &str: Key.
  - returns Result<Option<String>, String>: The stored text. Ok(None) if missing, Err(reason) if unreadable. (LocalStorage reads Err as missing)
- `fn set_item(&mut self, key: &str, value: &str) -> Result<(), String>` (method, since 0.4.0): Writes a value.
  - `key` &str: Key.
  - `value` &str: Text to write.
  - returns Result<(), String>: Ok(()) if written. Err(reason) if it could not write. (LocalStorage keeps that value in memory instead)
- `fn remove_item(&mut self, key: &str) -> Result<(), String>` (method, since 0.4.0): Removes a value.
  - `key` &str: Key to remove.
  - returns Result<(), String>: Ok(()) if removed. Err(reason) if it could not remove. (LocalStorage reports it and moves on)
- `fn get_keys(&self) -> Result<Vec<String>, String>` (method, since 0.4.0): All keys. (an empty list by default)
  - returns Result<Vec<String>, String>: All keys. Err(reason) if unreadable. (LocalStorage treats it as an empty list)
- `fn clear(&mut self) -> Result<(), String>` (method, since 0.4.0): Removes everything. (by default removes the keys from get_keys one by one)
  - returns Result<(), String>: Ok(()) if everything was removed. Err(reason) if it could not remove. (LocalStorage reports it and moves on)

## LocalStorage (struct)

Local storage. (a set of static functions)

Example: Save and read a score and settings

```rust
use vanilla::LocalStorage;

let storage_directory_path = std::env::temp_dir().join(format!("vanillaLocalStorageExample-{}", std::process::id()));
LocalStorage::set_storage_directory(Some(storage_directory_path.clone()));
LocalStorage::set_number("example.bestScore", 1200.0);
LocalStorage::set_boolean("example.isMuted", true);
LocalStorage::set_json("example.settings", &serde_json::json!({ "volume": 0.8, "language": "en" }));
let best_score = LocalStorage::get_number("example.bestScore", 0.0);
let is_muted = LocalStorage::get_boolean("example.isMuted", false);
let settings = LocalStorage::get_json("example.settings", serde_json::json!({}));
assert_eq!(best_score, 1200.0);
assert!(is_muted);
assert_eq!(settings["volume"], 0.8);
assert!(LocalStorage::contains_key("example.bestScore"));
assert_eq!(LocalStorage::clear_by_prefix("example."), 3);
assert!(!LocalStorage::is_memory_fallback());
let _ = std::fs::remove_dir_all(&storage_directory_path);
```

- `pub fn set_application_name(application_name: &str)` (static, since 0.3.2): Sets the app name. (the desktop save folder name. Unused on the web, which is separate per origin)
  - `application_name` &str: App name. (characters not allowed in folder names are replaced with '_', "vanilla" if empty)
- `pub fn set_application_name_from_engine(engine: &Engine)` (static, since 0.3.2): Uses the window title from the engine configuration as the app name. (EngineConfiguration.title)
  - `engine` &Engine: Engine to read the window title (EngineConfiguration.title) from.
- `pub fn set_storage_directory(storage_directory_path: Option<PathBuf>)` (static, since 0.3.2): Sets the save folder directly. (None uses the default folder derived from the app name. Unused on the web)
  - `storage_directory_path` Option<PathBuf>: Folder to hold localstorage.json. (None means the default folder decided by the app name)
- `pub fn get_storage_file_path() -> Option<PathBuf>` (static, since 0.3.2): Save file path. (desktop only, None on the web)
  - returns Option<PathBuf>: Storage file path. (always Some on desktop, None on the web)
- `pub fn set_backend(backend: Option<Box<dyn LocalStorageBackend>>)` (static, since 0.4.0): Swaps the storage backend. (None returns to the default storage. Values kept in memory instead are discarded)
  - `backend` Option<Box<dyn LocalStorageBackend>>: Storage to swap in. (None means the default storage)
- `pub fn get_backend() -> Option<Rc<RefCell<Box<dyn LocalStorageBackend>>>>` (static, since 0.4.0): Returns the swapped backend. (None if none, use borrow / borrow_mut to borrow it)
  - returns Option<Rc<RefCell<Box<dyn LocalStorageBackend>>>>: The swapped-in storage. None if none.
- `pub fn is_memory_fallback() -> bool` (static, since 0.4.0): Whether values were ever kept in memory because the storage could not be used.
  - returns bool: True if memory has ever been used instead. (returns to false when set_backend is called)
- `pub fn get_item(key: &str) -> Option<String>` (static, since 0.4.0): Reads one value. (None if missing or unreadable. Values kept in memory instead take precedence. Unpaired surrogates appear as the replacement character)
  - `key` &str: Key.
  - returns Option<String>: The stored text. None if missing or unreadable.
- `pub fn get_item_code_units(key: &str) -> Option<Vec<u16>>` (static, since 0.4.0): Reads one value as the original UTF-16 units. (the original JS string as is, unpaired surrogates included)
  - `key` &str: Key.
  - returns Option<Vec<u16>>: UTF-16 units of the stored text. None if missing or unreadable.
- `pub fn set_item(key: &str, value: &str) -> bool` (static, since 0.4.0): Writes one value. (true if written to the storage, false if kept in memory instead because it could not be written)
  - Writing back an unmodified value containing unpaired surrogates read from this key writes the original units.
  - `key` &str: Key.
  - `value` &str: Text to write.
  - returns bool: True if written to the storage. False if kept in memory instead.
- `pub fn set_item_code_units(key: &str, code_units: &[u16]) -> bool` (static, since 0.4.0): Writes one value as UTF-16 units. (the original JS string as is, unpaired surrogates written as they are)
  - `key` &str: Key.
  - `code_units` &[u16]: UTF-16 units of the text to write.
  - returns bool: True if written to the storage. False if kept in memory instead.
- `pub fn remove_item(key: &str)` (static, since 0.4.0): Removes one value. (also removes the value kept in memory instead)
  - `key` &str: Key to remove.
- `pub fn get_item_by_key_code_units(key_code_units: &[u16]) -> Option<Vec<u16>>` (static, since 0.4.0): Reads with both key and value in UTF-16 units. (exactly the original localStorage.getItem, also distinguishes two keys that differ only by unpaired surrogates)
  - `key_code_units` &[u16]: UTF-16 units of the key.
  - returns Option<Vec<u16>>: UTF-16 units of the stored text. None if missing or unreadable.
- `pub fn set_item_by_key_code_units(key_code_units: &[u16], value_code_units: &[u16]) -> bool` (static, since 0.4.0): Writes with both key and value in UTF-16 units. (exactly the original localStorage.setItem, true if written to the storage)
  - `key_code_units` &[u16]: UTF-16 units of the key.
  - `value_code_units` &[u16]: UTF-16 units of the text to write.
  - returns bool: True if written to the storage. False if kept in memory instead.
- `pub fn remove_item_by_key_code_units(key_code_units: &[u16])` (static, since 0.4.0): Removes by a UTF-16 unit key. (exactly the original localStorage.removeItem)
  - `key_code_units` &[u16]: UTF-16 units of the key to remove.
- `pub fn contains_key_code_units(key_code_units: &[u16]) -> bool` (static, since 0.4.0): Whether a UTF-16 unit key exists.
  - `key_code_units` &[u16]: UTF-16 units of the key to look for.
  - returns bool: True if a value exists.
- `pub fn clear()` (static, since 0.3.2): Removes all.
- `pub fn set_string(key: &str, string_value: &str)` (static, since 0.3.2): Sets a string value.
  - `key` &str: Key.
  - `string_value` &str: Text to write.
- `pub fn set_boolean(key: &str, boolean_value: bool)` (static, since 0.3.2): Sets a boolean value. (stored as "true" / "false")
  - `key` &str: Key.
  - `boolean_value` bool: Value to write. (written as the text "true" or "false")
- `pub fn set_number(key: &str, number_value: f64)` (static, since 0.3.2): Sets a number value. (stored in the original String(number) form)
  - `key` &str: Key.
  - `number_value` f64: Value to write. (converted to text in the original String(number) form)
- `pub fn remove(key: &str)` (static, since 0.3.2): Removes a value.
  - `key` &str: Key to remove.
- `pub fn get_string(key: &str, default_string_value: &str) -> String` (static, since 0.3.2): Returns a string value. (the default value if missing. Not written to the storage)
  - `key` &str: Key.
  - `default_string_value` &str: Value returned when missing.
  - returns String: The stored text. The default value if missing.
- `pub fn get_boolean(key: &str, default_boolean_value: bool) -> bool` (static, since 0.3.2): Returns a boolean value. (the default value if missing or an empty string, not written to the storage. Only "true" is true)
  - `key` &str: Key.
  - `default_boolean_value` bool: Value returned when missing or empty.
  - returns bool: True if the stored text is "true". The default value if missing or empty.
- `pub fn get_number(key: &str, default_number_value: f64) -> f64` (static, since 0.3.2): Returns a number value. (the default value if missing or an empty string, not written to the storage. NaN if not a number, original Number(text))
  - `key` &str: Key.
  - `default_number_value` f64: Value returned when missing or empty.
  - returns f64: The stored text converted like the original Number(text). (the default value if missing or empty, NaN if not a number)
- `pub fn clear_by_prefix(prefix: &str) -> usize` (static, since 0.3.2): Removes all keys starting with a prefix at once. (for wiping a game namespace's saves entirely, the number of removed keys)
  - Compares by the displayed text. Keys that differ only by unpaired surrogates are counted separately.
  - `prefix` &str: Prefix of the keys to remove. (removes nothing if empty)
  - returns usize: Number of removed keys.
- `pub fn contains_key(key: &str) -> bool` (static, since 0.3.2): Whether the key exists.
  - `key` &str: Key to look for.
  - returns bool: True if a value exists.
- `pub fn get_keys() -> Vec<String>` (static, since 0.3.2): Returns all keys. (sorted, includes keys kept in memory instead)
  - Keys containing unpaired surrogates appear with the replacement character. Keys with the same displayed text appear only once, so use get_keys_code_units to tell them all apart.
  - returns Vec<String>: Sorted list of the keys in the storage and in memory combined.
- `pub fn get_keys_code_units() -> Vec<Vec<u16>>` (static, since 0.4.0): Returns all keys in UTF-16 units. (exactly the strings of the original localStorage.key(i), sorted)
  - returns Vec<Vec<u16>>: List of all keys in UTF-16 units. (the keys in the storage and in memory combined and sorted)
- `pub fn get_json(key: &str, default_value: serde_json::Value) -> serde_json::Value` (static, since 0.4.0): Returns a JSON value. (the default value if missing or unparsable, not written to the storage)
  - Strings containing unpaired surrogates (like \ud83d from the original JSON.stringify) are read with the replacement character, and their positions are kept so set_json writes them back as they were.
  - `key` &str: Key.
  - `default_value` serde_json::Value: Value returned when missing, empty or unparsable.
  - returns serde_json::Value: The parsed value. The default value if missing or unparsable.
- `pub fn set_json(key: &str, value: &serde_json::Value) -> bool` (static, since 0.4.0): Sets a JSON value. (written as JSON text. true if written to the storage)
  - If strings containing unpaired surrogates read with get_json were not modified, writes them as \udXXX like the original JSON.stringify.
  - `key` &str: Key.
  - `value` &serde_json::Value: Value to write as JSON.
  - returns bool: True if written to the storage. (false if kept in memory instead)
