# misc/persistedstore (vanilla-engine 0.4.0)

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

지속 저장소.
- 원본 misc/persistedstore.js 를 옮긴 것이다. 키 하나에 상태 객체를 JSON 으로 저장하고, 바뀔 때 구독자에게 알린다.
- 판 번호(version)가 다르거나 해석에 실패하면 기본값으로 돌아간다.
- 저장은 LocalStorage 를 쓴다. 저장 꼴({"version":1,"state":{...}})이 원본과 같아서 웹에서는 원본 게임의 저장을 그대로 읽는다.
  set_storage_backend 로 이 저장소만 다른 곳(LocalStorageBackend, 플랫폼의 저장소 같은 것)에 둘 수 있다.
  넘긴 저장소는 `Rc<RefCell>` 에 담는다. get_storage_backend 는 그 Rc 를 돌려주고, 부르는 쪽은 borrow / borrow_mut 로 빌려 쓴다.
  (빌린 채로 이 저장소를 읽거나 쓰면 읽기는 빈 글, 쓰기는 알리고 넘어간다)
- 사용:
  ```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();
  ```
- 섞기는 원본 Object.assign 과 같다. 배열은 번호 키("0", "1" ...)로 섞고(저장된 state 가 배열이어도), 키 차례는 JS 객체처럼 번호 꼴 키를 작은 수부터 앞에 둔다.
- 원본과 다른 점:
  상태 객체는 serde_json::Value(객체)다. 객체도 배열도 아닌 값을 넘기면 빈 객체로 친다. (원본 Object.assign 은 글을 글자마다 번호 키로 섞는다)
  subscribe 는 해지 함수 대신 구독 번호(PersistedStoreSubscription)를 돌려주고, unsubscribe(번호) 로 푼다.
  러스트 String 은 짝 없는 서로게이트를 담지 못해, 원본이 저장한 그런 글(JSON.stringify 의 \ud83d 같은 것)은 get 의 상태에서 대체 문자(U+FFFD)로 보인다.
  그 글의 원래 JS 글 단위는 get_string_code_units 로 읽고 set_string_code_units 로 쓴다. (LocalStorage 의 *_code_units 와 같은 꼴, 원본 글과 같은 값)
  읽을 때 그 글의 자리를 남겨 두고, 고치지 않고 다시 쓰면 원본처럼 \udXXX 로 쓴다. (misc/storagetext.rs, 원본 판의 저장을 읽고 다시 써도 잃지 않는다)

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

구독 번호. (unsubscribe 에 넘긴다)

예제: 구독 번호로 한 구독만 풀기

```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)

지속 저장소.

예제: 설정을 저장하고 바뀔 때 알림 받기

```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): 생성. (만들면서 저장소에서 읽는다)
  - `storage_key` &str: 상태를 둘 저장소 키.
  - `default_state` Value: 기본 상태. (저장된 것이 없거나 판이 다르면 이것을 복사해 쓴다)
  - `version` i64: 저장 꼴의 판 번호. (저장된 판과 다르면 기본 상태로 되돌아간다)
  - returns PersistedStore: 저장소에서 상태를 읽어 둔 지속 저장소.
- `pub fn get(&self) -> &Value` (method, since 0.3.2): 상태 반환. (객체 Value. 고칠 때는 set / replace 를 쓴다)
  - returns &Value: 지금 상태.
- `pub fn set(&mut self, partial_state: Value)` (method, since 0.3.2): 상태 일부 갱신. (얕은 병합 뒤 저장하고 구독자에게 알린다)
  - `partial_state` Value: 바꿀 키와 값만 담은 객체.
- `pub fn get_string_code_units(&self, path: &[JsonPathSegment]) -> Option<Vec<u16>>` (method, since 0.4.0): 상태 안 글의 JS 글 단위. (UTF-16, 짝 없는 서로게이트도 원본 글 그대로, LocalStorage::get_item_code_units 와 같은 꼴)
  - `path` &[JsonPathSegment]: 상태에서부터의 글 자리. (키와 배열 차례)
  - returns Option<Vec<u16>>: 그 자리 글의 UTF-16 단위. (원본이 저장한 짝 없는 서로게이트가 있으면 그것, 아니면 글을 UTF-16 으로 편 것) 그 자리가 글이 아니면 None.

  예제: 글 자리의 JS 글 단위 읽고 쓰기

  ```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): 상태 안 글을 JS 글 단위로 쓰기. (짝 없는 서로게이트도 원본처럼 \udXXX 로 저장한다, 저장하고 구독자에게 알린다)
  - 없는 키는 객체로 만들며 내려간다. 배열 차례가 없거나 객체도 배열도 아닌 값을 지나야 하면 쓰지 않는다.
  - `path` &[JsonPathSegment]: 상태에서부터의 글 자리. (키와 배열 차례, 비면 쓰지 않는다)
  - `code_units` &[u16]: 쓸 UTF-16 단위.
  - returns bool: 썼으면 true.
- `pub fn replace(&mut self, next_state: Value)` (method, since 0.3.2): 상태 전체 교체.
  - `next_state` Value: 새 상태. (배열은 번호 키의 객체로 펴고, 객체도 배열도 아니면 빈 객체로 친다)
- `pub fn reset(&mut self)` (method, since 0.3.2): 기본값으로 초기화.
- `pub fn subscribe(&mut self, subscriber: impl FnMut(&Value) + 'static) -> PersistedStoreSubscription` (method, since 0.3.2): 구독. (구독 번호를 돌려준다)
  - `subscriber` impl FnMut(&Value) + 'static: 알릴 때마다(set, replace, reset, set_storage_backend, notify) 지금 상태를 받는 함수.
  - returns PersistedStoreSubscription: 구독 번호. (unsubscribe 에 넘긴다)
- `pub fn unsubscribe(&mut self, subscription: PersistedStoreSubscription)` (method, since 0.3.2): 구독 해지. (원본 subscribe 가 돌려준 해지 함수 자리)
  - `subscription` PersistedStoreSubscription: subscribe 가 돌려준 구독 번호. (모르는 것이면 아무것도 하지 않는다)
- `pub fn notify(&mut self)` (method, since 0.3.2): 구독자 알림. (구독한 순서대로)
- `pub fn read_from_storage(&self) -> Value` (method, since 0.3.2): 저장소에서 읽기. (기본값 위에 저장된 state 를 덮는다. 기본값에 없던 키도 살리고, 새로 생긴 기본 키는 기본값으로 채운다)
  - state 가 객체나 배열이 아니면 기본값이다. (원본 typeof state === "object", 배열은 번호 키로 섞는다)
  - returns Value: 저장된 상태를 기본 상태 위에 덮은 새 객체. (없거나, 판이 다르거나, 풀 수 없으면 기본 상태의 복사본)
- `pub fn write_to_storage(&self)` (method, since 0.3.2): 저장소에 쓰기. ({"version": 판 번호, "state": 상태})
- `pub fn read_stored_text(&self) -> String` (method, since 0.4.0): 저장된 글 읽기. (없거나 못 읽으면 빈 글)
  - returns String: 저장된 JSON 글. 없거나 못 읽으면 빈 글.
- `pub fn set_storage_backend(&mut self, storage_backend: Option<Box<dyn LocalStorageBackend>>)` (method, since 0.4.0): 이 저장소만 쓰는 곳 갈아 끼우기. (None 이면 LocalStorage. 그곳에서 상태를 다시 읽고 구독자에게 알린다)
  - `storage_backend` Option<Box<dyn LocalStorageBackend>>: 이 저장소만 쓸 곳. (None 이면 LocalStorage)
- `pub fn get_storage_backend(&self) -> Option<Rc<RefCell<Box<dyn LocalStorageBackend>>>>` (method, since 0.4.0): 이 저장소만 쓰는 곳 반환. (없으면 None, 빌릴 때는 borrow / borrow_mut)
  - returns Option<Rc<RefCell<Box<dyn LocalStorageBackend>>>>: 이 저장소만 쓰는 곳. 없으면 None.
- `pub fn get_storage_key(&self) -> &str` (method, since 0.3.2): 저장 키 반환.
  - returns &str: 저장소 키.
