vanilladocs
vanillapunch.com
API / misc/persistedstore

misc/persistedstore

지속 저장소.

  • 원본 misc/persistedstore.js 를 옮긴 것이다. 키 하나에 상태 객체를 JSON 으로 저장하고, 바뀔 때 구독자에게 알린다.
  • 판 번호(version)가 다르거나 해석에 실패하면 기본값으로 돌아간다.
  • 저장은 LocalStorage 를 쓴다. 저장 꼴({"version":1,"state":{...}})이 원본과 같아서 웹에서는 원본 게임의 저장을 그대로 읽는다. set_storage_backend 로 이 저장소만 다른 곳(LocalStorageBackend, 플랫폼의 저장소 같은 것)에 둘 수 있다. 넘긴 저장소는 Rc<RefCell> 에 담는다. get_storage_backend 는 그 Rc 를 돌려주고, 부르는 쪽은 borrow / borrow_mut 로 빌려 쓴다. (빌린 채로 이 저장소를 읽거나 쓰면 읽기는 빈 글, 쓰기는 알리고 넘어간다)
  • 사용:
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, 원본 판의 저장을 읽고 다시 써도 잃지 않는다)

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

PersistedStoreSubscriptionstruct traits Clone, Copy, Debug, PartialEq, Eq, Hash

소스source

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

Subscription number. (pass it to unsubscribe)

예제Example구독 번호로 한 구독만 풀기Ending only one subscription by its subscription number
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);

PersistedStorestruct

짝Counterpart: vanilla.js PersistedStore소스source

지속 저장소.

Persistent store.

예제Example설정을 저장하고 바뀔 때 알림 받기Save settings and get notified on change
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);
생성자constructorpub fn new(storage_key: &str, default_state: Value, version: i64) -> PersistedStore#0.3.2 부터since 0.3.2소스source

생성. (만들면서 저장소에서 읽는다)

Constructor. (reads from the storage on creation)

storage_key&str
상태를 둘 저장소 키.Storage key that holds the state.
default_stateValue
기본 상태. (저장된 것이 없거나 판이 다르면 이것을 복사해 쓴다)Default state. (a copy is used when nothing is stored or the version differs)
versioni64
저장 꼴의 판 번호. (저장된 판과 다르면 기본 상태로 되돌아간다)Version number of the saved format. (falls back to the default state if it differs from the stored version)

반환ReturnsPersistedStore 저장소에서 상태를 읽어 둔 지속 저장소.Persistent store with the state read from the storage.

짝Counterpart: vanilla.js PersistedStore.constructor

메서드methodpub fn get(&self) -> &Value#0.3.2 부터since 0.3.2소스source

상태 반환. (객체 Value. 고칠 때는 set / replace 를 쓴다)

Returns the state. (an object Value. Use set / replace to modify it)

반환Returns&Value 지금 상태.The current state.

짝Counterpart: vanilla.js PersistedStore.get

메서드methodpub fn set(&mut self, partial_state: Value)#0.3.2 부터since 0.3.2소스source

상태 일부 갱신. (얕은 병합 뒤 저장하고 구독자에게 알린다)

Updates part of the state. (shallow merges, then saves and notifies the subscribers)

partial_stateValue
바꿀 키와 값만 담은 객체.Object with only the keys and values to change.

짝Counterpart: vanilla.js PersistedStore.set

메서드methodpub fn get_string_code_units(&self, path: &[JsonPathSegment]) -> Option<Vec<u16>>#0.4.0 부터since 0.4.0소스source

상태 안 글의 JS 글 단위. (UTF-16, 짝 없는 서로게이트도 원본 글 그대로, LocalStorage::get_item_code_units 와 같은 꼴)

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)

반환ReturnsOption<Vec<u16>> 그 자리 글의 UTF-16 단위. (원본이 저장한 짝 없는 서로게이트가 있으면 그것, 아니면 글을 UTF-16 으로 편 것) 그 자리가 글이 아니면 None.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글 자리의 JS 글 단위 읽고 쓰기Read and write JS code units at a string place
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"}}"#);
메서드methodpub fn set_string_code_units(&mut self, path: &[JsonPathSegment], code_units: &[u16]) -> bool#0.4.0 부터since 0.4.0소스source

상태 안 글을 JS 글 단위로 쓰기. (짝 없는 서로게이트도 원본처럼 \udXXX 로 저장한다, 저장하고 구독자에게 알린다)

  • 없는 키는 객체로 만들며 내려간다. 배열 차례가 없거나 객체도 배열도 아닌 값을 지나야 하면 쓰지 않는다.

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]
쓸 UTF-16 단위.The UTF-16 units to write.

반환Returnsbool 썼으면 true.true if it wrote.

메서드methodpub fn replace(&mut self, next_state: Value)#0.3.2 부터since 0.3.2소스source

상태 전체 교체.

Replaces the whole state.

next_stateValue
새 상태. (배열은 번호 키의 객체로 펴고, 객체도 배열도 아니면 빈 객체로 친다)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)

짝Counterpart: vanilla.js PersistedStore.replace

메서드methodpub fn reset(&mut self)#0.3.2 부터since 0.3.2소스source

기본값으로 초기화.

Resets to the default value.

짝Counterpart: vanilla.js PersistedStore.reset

메서드methodpub fn subscribe(&mut self, subscriber: impl FnMut(&Value) + 'static) -> PersistedStoreSubscription#0.3.2 부터since 0.3.2소스source

구독. (구독 번호를 돌려준다)

Subscribes. (returns the subscription number)

subscriberimpl FnMut(&Value) + 'static
알릴 때마다(set, replace, reset, set_storage_backend, notify) 지금 상태를 받는 함수.Function that receives the current state on every notification (set, replace, reset, set_storage_backend, notify).

반환ReturnsPersistedStoreSubscription 구독 번호. (unsubscribe 에 넘긴다)Subscription number. (pass it to unsubscribe)

짝Counterpart: vanilla.js PersistedStore.subscribe

메서드methodpub fn unsubscribe(&mut self, subscription: PersistedStoreSubscription)#0.3.2 부터since 0.3.2소스source

구독 해지. (원본 subscribe 가 돌려준 해지 함수 자리)

Unsubscribes. (in place of the unsubscribe function returned by the original subscribe)

subscriptionPersistedStoreSubscription
subscribe 가 돌려준 구독 번호. (모르는 것이면 아무것도 하지 않는다)Subscription number returned by subscribe. (does nothing if unknown)

짝Counterpart: vanilla.js PersistedStore.unsubscribe

메서드methodpub fn notify(&mut self)#0.3.2 부터since 0.3.2소스source

구독자 알림. (구독한 순서대로)

Notifies the subscribers. (in subscription order)

짝Counterpart: vanilla.js PersistedStore.notify

메서드methodpub fn read_from_storage(&self) -> Value#0.3.2 부터since 0.3.2소스source

저장소에서 읽기. (기본값 위에 저장된 state 를 덮는다. 기본값에 없던 키도 살리고, 새로 생긴 기본 키는 기본값으로 채운다)

  • state 가 객체나 배열이 아니면 기본값이다. (원본 typeof state === "object", 배열은 번호 키로 섞는다)

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)

반환ReturnsValue 저장된 상태를 기본 상태 위에 덮은 새 객체. (없거나, 판이 다르거나, 풀 수 없으면 기본 상태의 복사본)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)

짝Counterpart: vanilla.js PersistedStore.readFromStorage

메서드methodpub fn write_to_storage(&self)#0.3.2 부터since 0.3.2소스source

저장소에 쓰기. ({"version": 판 번호, "state": 상태})

Writes to the storage. ({"version": version number, "state": state})

짝Counterpart: vanilla.js PersistedStore.writeToStorage

메서드methodpub fn read_stored_text(&self) -> String#0.4.0 부터since 0.4.0소스source

저장된 글 읽기. (없거나 못 읽으면 빈 글)

Reads the stored text. (empty text if missing or unreadable)

반환ReturnsString 저장된 JSON 글. 없거나 못 읽으면 빈 글.The stored JSON text. An empty string if missing or unreadable.

짝Counterpart: vanilla.js PersistedStore.readStoredText

메서드methodpub fn set_storage_backend(&mut self, storage_backend: Option<Box<dyn LocalStorageBackend>>)#0.4.0 부터since 0.4.0소스source

이 저장소만 쓰는 곳 갈아 끼우기. (None 이면 LocalStorage. 그곳에서 상태를 다시 읽고 구독자에게 알린다)

Swaps the backend used only by this store. (None uses LocalStorage. Rereads the state from there and notifies the subscribers)

storage_backendOption<Box<dyn LocalStorageBackend>>
이 저장소만 쓸 곳. (None 이면 LocalStorage)Storage used only by this store. (LocalStorage if None)

짝Counterpart: vanilla.js PersistedStore.setStorageBackend

메서드methodpub fn get_storage_backend(&self) -> Option<Rc<RefCell<Box<dyn LocalStorageBackend>>>>#0.4.0 부터since 0.4.0소스source

이 저장소만 쓰는 곳 반환. (없으면 None, 빌릴 때는 borrow / borrow_mut)

Returns the backend used only by this store. (None if none, use borrow / borrow_mut to borrow it)

반환ReturnsOption<Rc<RefCell<Box<dyn LocalStorageBackend>>>> 이 저장소만 쓰는 곳. 없으면 None.Storage used only by this store. None if none.

짝Counterpart: vanilla.js PersistedStore.getStorageBackend

메서드methodpub fn get_storage_key(&self) -> &str#0.3.2 부터since 0.3.2소스source

저장 키 반환.

Returns the storage key.

반환Returns&str 저장소 키.Storage key.

짝Counterpart: vanilla.js PersistedStore.getStorageKey