# misc/localstorage (vanilla-engine 0.4.0)

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

로컬 스토리지.
- 원본 misc/localstorage.js 를 옮긴 것이다. 문자열 키에 문자열 값을 영구 저장하는 정적 함수 묶음이다.
- 저장하는 곳:
  웹(wasm32): 원본처럼 window.localStorage. (출처(origin)마다 따로, 키를 그대로 쓴다)
  데스크탑: 앱 폴더의 localstorage.json 하나. (키 → 문자열 값의 JSON 객체, 쓸 때마다 바로 저장한다)
    윈도우   %APPDATA%\{앱 이름}\localstorage.json
    맥       $HOME/Library/Application Support/{앱 이름}/localstorage.json
    리눅스   $XDG_DATA_HOME/{앱 이름}/localstorage.json (없으면 $HOME/.local/share/{앱 이름}/...)
    환경 변수를 못 읽으면 임시 폴더(std::env::temp_dir) 아래에 둔다.
  앱 이름은 기본으로 실행 파일 이름이다. set_application_name 이나 set_application_name_from_engine(EngineConfiguration.title)로 바꾼다.
  set_storage_directory 로 폴더를 직접 정할 수도 있다. (시험, 들고 다니는 게임)
- 원본과 다른 점:
  숫자는 원본(JS number)처럼 f64 다. 글로 바꾸기는 원본 String(number) 그대로다. (가장 짧은 표기, 1e21 이상과 1e-7 이하는 1e+21 같은 지수, NaN, Infinity, -0 → "0")
    읽기는 원본 Number(text) 그대로다. (JS 빈칸을 떼고, 빈 글은 0, 0x, 0o, 0b 표기, "1.", ".5", 지수, Infinity, 그 밖은 NaN)
  데스크탑 저장은 스레드마다 따로 들고 있다가 파일에 쓴다. (엔진은 한 스레드에서 돈다)
- 저장소 갈아 끼우기: set_backend 에 LocalStorageBackend 를 넘기면 위 기본 저장소 대신 그것을 쓴다. (플랫폼 SDK 의 저장소 같은 것)
  원본 setBackend 의 객체({ getItem, setItem, removeItem, getKeys, clear }) 자리가 트레이트다. 원본의 예외는 Err 로 알린다.
  넘긴 저장소는 `Rc<RefCell>` 에 담는다. get_backend 는 그 Rc 를 돌려주고, 부르는 쪽은 borrow / borrow_mut 로 빌려 쓴다.
- 막혀도 죽지 않는다: 저장소가 없거나(웹의 막힌 localStorage) 쓰기가 실패하면(가득 참, 폴더를 못 만듦, 바꿔 낀 저장소의 Err)
  이 실행이 살아 있는 동안 메모리에 대신 둔다. (is_memory_fallback, 다시 켜면 없다)
- 읽기(get_string, get_boolean, get_number, get_json)는 없는 키에 기본값을 써 넣지 않는다. (원본과 같다)
- 짝 없는 서로게이트: 원본 localStorage 는 JS 글(UTF-16)이라 짝 없는 서로게이트가 든 값(잘린 이모지 같은 것)과
  그것을 \ud83d 꼴로 쓴 JSON 을 담는다. 러스트 String 은 그런 글을 담지 못해 러스트 쪽에는 대체 문자(U+FFFD)로 보이고,
  읽은 값을 고치지 않고 다시 쓰면(set_item, set_string, set_json) 원래 UTF-16 단위 그대로 쓴다. (misc/storagetext.rs)
  원래 단위가 필요하면 get_item_code_units, set_item_code_units 로 JS 글 그대로 읽고 쓴다.
  키도 같다. 짝 없는 서로게이트로만 다른 두 키(원본에서 다른 키)는 러스트 글로는 같은 글로 보이지만 저장소 안에서는 따로 든다.
  get_keys_code_units 로 모든 키를 원래 단위로 받고, get_item_by_key_code_units, set_item_by_key_code_units,
  remove_item_by_key_code_units, contains_key_code_units 로 키와 값을 모두 원래 단위로 가려 부른다. (원본 localStorage 함수 그대로)
  러스트 글 키는 그 글 그대로의 키가 있으면 그것, 없으면 그 글로 보이는 짝 없는 서로게이트 키의 첫째를 가리킨다. (get_keys 로 받은 키로 부를 수 있다)
  웹은 브라우저 localStorage 에 JS 글 그대로 쓰고, 데스크탑 파일은 그런 값과 키를 원본 JSON.stringify 처럼 \udXXX 로 적는다.
  바꿔 낀 저장소(LocalStorageBackend)는 러스트 글로 주고받아 그 저장소가 든 글 그대로다. (키도 보인 글로 준다)

## LocalStorageBackend (trait)

바꿔 끼우는 저장소. (원본 setBackend 에 넘기는 객체)
- get_keys 와 clear 는 없어도 된다. get_keys 가 없으면 키 목록(get_keys, clear_by_prefix)은 메모리에 대신 둔 것만 보이고,
  clear 가 없으면 get_keys 의 키를 하나씩 지운다.
- 이 함수들 안에서 LocalStorage 를 다시 부르면 기본 저장소를 쓴다. (바꿔 낀 저장소는 부르는 동안 빌려 있다)
  get_backend 로 꺼낸 저장소를 빌린 채로 LocalStorage 를 불러도 기본 저장소를 쓴다.

예제: 내 저장소로 갈아 끼우기

```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): 값 읽기. (없으면 Ok(None))
  - `key` &str: 키.
  - returns Result<Option<String>, String>: 저장된 글. 없으면 Ok(None), 못 읽으면 Err(까닭). (LocalStorage 는 Err 를 없는 것으로 읽는다)
- `fn set_item(&mut self, key: &str, value: &str) -> Result<(), String>` (method, since 0.4.0): 값 쓰기.
  - `key` &str: 키.
  - `value` &str: 쓸 글.
  - returns Result<(), String>: 썼으면 Ok(()). 못 쓰면 Err(까닭). (LocalStorage 는 그 값을 메모리에 대신 둔다)
- `fn remove_item(&mut self, key: &str) -> Result<(), String>` (method, since 0.4.0): 값 지우기.
  - `key` &str: 지울 키.
  - returns Result<(), String>: 지웠으면 Ok(()). 못 지우면 Err(까닭). (LocalStorage 는 알리고 넘어간다)
- `fn get_keys(&self) -> Result<Vec<String>, String>` (method, since 0.4.0): 모든 키. (기본은 빈 목록)
  - returns Result<Vec<String>, String>: 모든 키. 못 읽으면 Err(까닭). (LocalStorage 는 빈 목록으로 친다)
- `fn clear(&mut self) -> Result<(), String>` (method, since 0.4.0): 전부 지우기. (기본은 get_keys 의 키를 하나씩 지운다)
  - returns Result<(), String>: 다 지웠으면 Ok(()). 못 지우면 Err(까닭). (LocalStorage 는 알리고 넘어간다)

## LocalStorage (struct)

로컬 스토리지. (정적 함수 묶음)

예제: 점수와 설정 저장하고 읽기

```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): 앱 이름 설정. (데스크탑 저장 폴더 이름. 웹은 출처마다 따로라 쓰지 않는다)
  - `application_name` &str: 앱 이름. (폴더 이름에 못 쓰는 글자는 '_' 로 바꾸고, 비면 "vanilla")
- `pub fn set_application_name_from_engine(engine: &Engine)` (static, since 0.3.2): 엔진 설정의 창 제목을 앱 이름으로 쓴다. (EngineConfiguration.title)
  - `engine` &Engine: 창 제목(EngineConfiguration.title)을 읽을 엔진.
- `pub fn set_storage_directory(storage_directory_path: Option<PathBuf>)` (static, since 0.3.2): 저장 폴더 직접 설정. (None 이면 앱 이름으로 정한 기본 폴더. 웹은 쓰지 않는다)
  - `storage_directory_path` Option<PathBuf>: localstorage.json 을 둘 폴더. (None 이면 앱 이름으로 정한 기본 폴더)
- `pub fn get_storage_file_path() -> Option<PathBuf>` (static, since 0.3.2): 저장 파일 경로. (데스크탑만, 웹은 None)
  - returns Option<PathBuf>: 저장 파일 경로. (데스크탑은 늘 Some, 웹은 None)
- `pub fn set_backend(backend: Option<Box<dyn LocalStorageBackend>>)` (static, since 0.4.0): 저장소 갈아 끼우기. (None 이면 기본 저장소로 돌아간다. 메모리에 대신 둔 값은 버린다)
  - `backend` Option<Box<dyn LocalStorageBackend>>: 갈아 끼울 저장소. (None 이면 기본 저장소)
- `pub fn get_backend() -> Option<Rc<RefCell<Box<dyn LocalStorageBackend>>>>` (static, since 0.4.0): 갈아 끼운 저장소 반환. (없으면 None, 빌릴 때는 borrow / borrow_mut)
  - returns Option<Rc<RefCell<Box<dyn LocalStorageBackend>>>>: 갈아 끼운 저장소. 없으면 None.
- `pub fn is_memory_fallback() -> bool` (static, since 0.4.0): 저장소를 못 써서 메모리에 대신 둔 적이 있는지.
  - returns bool: 메모리로 대신한 적이 있으면 참. (set_backend 를 부르면 거짓으로 돌아간다)
- `pub fn get_item(key: &str) -> Option<String>` (static, since 0.4.0): 값 하나 읽기. (없거나 못 읽으면 None. 메모리에 대신 둔 값이 앞선다. 짝 없는 서로게이트는 대체 문자로 보인다)
  - `key` &str: 키.
  - returns Option<String>: 저장된 글. 없거나 못 읽으면 None.
- `pub fn get_item_code_units(key: &str) -> Option<Vec<u16>>` (static, since 0.4.0): 값 하나를 원래 UTF-16 단위로 읽기. (원본 JS 글 그대로, 짝 없는 서로게이트도 담는다)
  - `key` &str: 키.
  - returns Option<Vec<u16>>: 저장된 글의 UTF-16 단위. 없거나 못 읽으면 None.
- `pub fn set_item(key: &str, value: &str) -> bool` (static, since 0.4.0): 값 하나 쓰기. (저장소에 썼으면 true, 못 써서 메모리에 대신 뒀으면 false)
  - 이 키에서 읽은 짝 없는 서로게이트가 든 값을 고치지 않고 다시 쓰면 원래 단위로 쓴다.
  - `key` &str: 키.
  - `value` &str: 쓸 글.
  - returns bool: 저장소에 썼으면 참. 메모리에 대신 뒀으면 거짓.
- `pub fn set_item_code_units(key: &str, code_units: &[u16]) -> bool` (static, since 0.4.0): 값 하나를 UTF-16 단위로 쓰기. (원본 JS 글 그대로, 짝 없는 서로게이트도 그대로 쓴다)
  - `key` &str: 키.
  - `code_units` &[u16]: 쓸 글의 UTF-16 단위.
  - returns bool: 저장소에 썼으면 참. 메모리에 대신 뒀으면 거짓.
- `pub fn remove_item(key: &str)` (static, since 0.4.0): 값 하나 지우기. (메모리에 대신 둔 값도 지운다)
  - `key` &str: 지울 키.
- `pub fn get_item_by_key_code_units(key_code_units: &[u16]) -> Option<Vec<u16>>` (static, since 0.4.0): 키와 값을 모두 UTF-16 단위로 읽기. (원본 localStorage.getItem 그대로, 짝 없는 서로게이트로만 다른 두 키도 가린다)
  - `key_code_units` &[u16]: 키의 UTF-16 단위.
  - returns Option<Vec<u16>>: 저장된 글의 UTF-16 단위. 없거나 못 읽으면 None.
- `pub fn set_item_by_key_code_units(key_code_units: &[u16], value_code_units: &[u16]) -> bool` (static, since 0.4.0): 키와 값을 모두 UTF-16 단위로 쓰기. (원본 localStorage.setItem 그대로, 저장소에 썼으면 true)
  - `key_code_units` &[u16]: 키의 UTF-16 단위.
  - `value_code_units` &[u16]: 쓸 글의 UTF-16 단위.
  - returns bool: 저장소에 썼으면 참. 메모리에 대신 뒀으면 거짓.
- `pub fn remove_item_by_key_code_units(key_code_units: &[u16])` (static, since 0.4.0): UTF-16 단위 키로 지우기. (원본 localStorage.removeItem 그대로)
  - `key_code_units` &[u16]: 지울 키의 UTF-16 단위.
- `pub fn contains_key_code_units(key_code_units: &[u16]) -> bool` (static, since 0.4.0): UTF-16 단위 키가 있는지.
  - `key_code_units` &[u16]: 찾을 키의 UTF-16 단위.
  - returns bool: 값이 있으면 참.
- `pub fn clear()` (static, since 0.3.2): 전체 제거.
- `pub fn set_string(key: &str, string_value: &str)` (static, since 0.3.2): 문자열 값 설정.
  - `key` &str: 키.
  - `string_value` &str: 쓸 글.
- `pub fn set_boolean(key: &str, boolean_value: bool)` (static, since 0.3.2): 논리 값 설정. ("true" / "false" 로 저장한다)
  - `key` &str: 키.
  - `boolean_value` bool: 쓸 값. ("true" 나 "false" 글로 쓴다)
- `pub fn set_number(key: &str, number_value: f64)` (static, since 0.3.2): 숫자 값 설정. (원본 String(number) 꼴로 저장한다)
  - `key` &str: 키.
  - `number_value` f64: 쓸 값. (원본 String(number) 꼴의 글로 바꿔 쓴다)
- `pub fn remove(key: &str)` (static, since 0.3.2): 값 제거.
  - `key` &str: 지울 키.
- `pub fn get_string(key: &str, default_string_value: &str) -> String` (static, since 0.3.2): 문자열 값 반환. (없으면 기본값. 저장소에는 쓰지 않는다)
  - `key` &str: 키.
  - `default_string_value` &str: 없을 때 돌려줄 값.
  - returns String: 저장된 글. 없으면 기본값.
- `pub fn get_boolean(key: &str, default_boolean_value: bool) -> bool` (static, since 0.3.2): 논리 값 반환. (없거나 빈 글이면 기본값, 저장소에는 쓰지 않는다. "true" 만 참)
  - `key` &str: 키.
  - `default_boolean_value` bool: 없거나 빈 글일 때 돌려줄 값.
  - returns bool: 저장된 글이 "true" 면 참. 없거나 빈 글이면 기본값.
- `pub fn get_number(key: &str, default_number_value: f64) -> f64` (static, since 0.3.2): 숫자 값 반환. (없거나 빈 글이면 기본값, 저장소에는 쓰지 않는다. 숫자가 아니면 NaN, 원본 Number(text))
  - `key` &str: 키.
  - `default_number_value` f64: 없거나 빈 글일 때 돌려줄 값.
  - returns f64: 저장된 글을 원본 Number(text) 처럼 바꾼 값. (없거나 빈 글이면 기본값, 숫자가 아니면 NaN)
- `pub fn clear_by_prefix(prefix: &str) -> usize` (static, since 0.3.2): 접두사로 시작하는 키 한꺼번에 지우기. (게임 네임스페이스의 저장을 통째로 지울 때, 지운 키 수)
  - 보인 글로 견준다. 짝 없는 서로게이트로만 다른 키도 따로 센다.
  - `prefix` &str: 지울 키의 접두사. (빈 글이면 아무것도 지우지 않는다)
  - returns usize: 지운 키 수.
- `pub fn contains_key(key: &str) -> bool` (static, since 0.3.2): 키가 있는지.
  - `key` &str: 찾을 키.
  - returns bool: 값이 있으면 참.
- `pub fn get_keys() -> Vec<String>` (static, since 0.3.2): 모든 키 반환. (정렬해서, 메모리에 대신 둔 키도 넣는다)
  - 짝 없는 서로게이트가 든 키는 대체 문자로 보인다. 보인 글이 같은 키는 하나만 나오니, 모두 가려 보려면 get_keys_code_units.
  - returns Vec<String>: 저장소와 메모리의 키를 합쳐 정렬한 목록.
- `pub fn get_keys_code_units() -> Vec<Vec<u16>>` (static, since 0.4.0): 모든 키를 UTF-16 단위로 반환. (원본 localStorage.key(i) 의 글 그대로, 정렬해서)
  - returns Vec<Vec<u16>>: 모든 키의 UTF-16 단위 목록. (저장소와 메모리의 키를 합쳐 정렬한다)
- `pub fn get_json(key: &str, default_value: serde_json::Value) -> serde_json::Value` (static, since 0.4.0): JSON 값 반환. (없거나 풀 수 없으면 기본값, 저장소에는 쓰지 않는다)
  - 짝 없는 서로게이트가 든 글(원본 JSON.stringify 의 \ud83d 같은 것)은 대체 문자로 읽고, 그 자리를 남겨 set_json 이 원래대로 쓴다.
  - `key` &str: 키.
  - `default_value` serde_json::Value: 없거나 빈 글이거나 풀 수 없을 때 돌려줄 값.
  - returns serde_json::Value: 풀어 낸 값. 없거나 풀 수 없으면 기본값.
- `pub fn set_json(key: &str, value: &serde_json::Value) -> bool` (static, since 0.4.0): JSON 값 설정. (JSON 글로 바꿔 쓴다. 저장소에 썼으면 true)
  - get_json 으로 읽은 짝 없는 서로게이트가 든 글을 고치지 않았으면 원본 JSON.stringify 처럼 \udXXX 로 쓴다.
  - `key` &str: 키.
  - `value` &serde_json::Value: JSON 으로 바꿔 쓸 값.
  - returns bool: 저장소에 썼으면 참. (메모리에 대신 뒀으면 거짓)
