# misc/storagetext (vanilla-engine 0.4.0)

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

엔진의 JSON 글 쓰기와 저장 글의 짝 없는 서로게이트 보존. (엔진이 JSON 을 쓰는 길 모두가 쓴다, 서로게이트 표는 LocalStorage 와 PersistedStore 가 쓴다)
- 원본 localStorage 와 JSON 은 JS 글(UTF-16)이라 짝 없는 서로게이트(짝을 잃은 U+D800 ~ U+DFFF)를 담는다.
  잘린 이모지처럼 사용자 입력에서 생기고, JSON.stringify 는 그것을 \ud83d 같은 이스케이프로 쓴다. (ES2019 의 잘 짜인 JSON.stringify)
- 러스트 String 은 UTF-8 이라 그런 글을 담지 못한다. 그래서 러스트 쪽에는 대체 문자(U+FFFD)로 보이고,
  고치지 않은 글을 다시 쓸 때는 원래 UTF-16 단위 그대로 쓴다. 원본 판이 저장한 값을 러스트 판이 읽고 다시 써도 잃지 않는다.
- PreservedText: 원래 UTF-16 단위와 대체 문자로 보인 글.
- parse_json, parse_json_code_units: JSON.parse 처럼 읽되 짝 없는 서로게이트(이스케이프와 날 단위 모두)를 대체 문자로 읽고,
  그런 글이 있던 자리(JSON 경로)와 원래 단위를 JsonSurrogateTable 에 남긴다. 수는 serde_json 이 읽은 것과 같다.
- stringify_json, stringify_json_with_space: 원본 JSON.stringify 와 글자까지 같은 글을 쓰되(엔진이 JSON 을 쓰는 길 모두가 쓴다), 표의 자리에 대체 문자로 보인 글이 그대로 있으면 원래 단위를,
  다른 자리라도 같은 글이면(원본에서 글을 옮겨 담은 것과 같다) 원래 단위를 JSON.stringify 처럼 \udXXX 로 쓴다.
  대체 문자로 보이는 글이 같은데 원래 단위가 서로 다른 글이 둘 이상이면 자리가 맞는 것만 원래 단위로 쓴다.

## PreservedText (struct) (Clone, Debug, PartialEq, Eq)

원래 UTF-16 단위와 대체 문자로 보인 글.

예제: 잘린 이모지의 앞 반쪽을 든 글

```rust
use vanilla::misc::storagetext::PreservedText;

let preserved_text = PreservedText::from_code_units(&[0x61, 0xD83D]);
assert_eq!(preserved_text.get_lossy_text(), "a\u{fffd}");
assert_eq!(preserved_text.get_code_units(), &[0x61, 0xD83D]);
assert!(preserved_text.has_lone_surrogate());
assert!(!PreservedText::from_code_units(&[0xD83D, 0xDE00]).has_lone_surrogate());
```

- `pub fn from_code_units(code_units: &[u16]) -> PreservedText` (static, since 0.4.0): UTF-16 단위로 만들기. (짝 없는 서로게이트는 대체 문자로 보인다)
  - `code_units` &[u16]: 원래 UTF-16 단위.
  - returns PreservedText: 그 단위와 대체 문자로 보인 글을 든 PreservedText.
- `pub fn get_lossy_text(&self) -> &str` (method, since 0.4.0): 대체 문자로 보인 글.
  - returns &str: 짝 없는 서로게이트를 대체 문자(U+FFFD)로 바꾼 러스트 글.
- `pub fn get_code_units(&self) -> &[u16]` (method, since 0.4.0): 원래 UTF-16 단위.
  - returns &[u16]: 만들 때 받은 원래 UTF-16 단위.
- `pub fn has_lone_surrogate(&self) -> bool` (method, since 0.4.0): 짝 없는 서로게이트가 있는지. (없으면 러스트 글과 같다)
  - returns bool: 짝 없는 서로게이트가 있으면 true.

## JsonSurrogateTable (struct) (Clone, Debug, Default)

짝 없는 서로게이트가 든 글의 표. (parse_json 이 채우고 stringify_json 이 쓴다)

예제: 원본이 쓴 `\ud83d` 를 읽고 그대로 다시 쓰기

```rust
use vanilla::misc::storagetext::{self, JsonPathSegment};

let stored_text = r#"{"name":"a\ud83d"}"#;
let (value, surrogate_table) = storagetext::parse_json(stored_text).unwrap();
assert_eq!(value["name"], "a\u{fffd}");
assert!(!surrogate_table.is_empty());
let name_path = [JsonPathSegment::Key(String::from("name"))];
assert_eq!(surrogate_table.find_value_code_units(&name_path, "a\u{fffd}"), Some(&[0x61u16, 0xD83D][..]));
assert_eq!(storagetext::stringify_json(&value, &surrogate_table), stored_text);
```

- `pub fn new() -> JsonSurrogateTable` (constructor, since 0.4.0): 빈 표.
  - returns JsonSurrogateTable: 빈 표.
- `pub fn is_empty(&self) -> bool` (method, since 0.4.0): 비었는지. (짝 없는 서로게이트가 든 글이 없었다)
  - returns bool: 짝 없는 서로게이트가 든 글이 없었으면 true.
- `pub fn find_value_code_units(&self, path: &[JsonPathSegment], text: &str) -> Option<&[u16]>` (method, since 0.4.0): 그 자리 값 글의 원래 단위. (자리가 맞고 글이 그대로면 그것, 아니면 같은 글로 보이는 원래 글이 하나뿐일 때 그것)
  - `path` &[JsonPathSegment]: 값의 자리. (맨 위 값에서부터의 JSON 경로)
  - `text` &str: 지금 그 자리에 든 글.
  - returns Option<&[u16]>: 원래 UTF-16 단위. (자리가 맞고 글이 그대로면 그 자리의 것, 아니면 find_text_code_units 와 같다) 찾지 못하면 None.
- `pub fn find_text_code_units(&self, text: &str) -> Option<&[u16]>` (method, since 0.4.0): 같은 글로 보이는 원래 글의 단위. (하나뿐일 때만)
  - `text` &str: 대체 문자로 보인 글.
  - returns Option<&[u16]>: 원래 UTF-16 단위. 그렇게 보이는 원래 글이 없거나, 원래 단위가 서로 다른 글이 둘 이상이면 None.

## JsonObjectEntry (struct)

JSON 객체의 칸 하나. (키는 원래 UTF-16 단위, 값의 표는 그 값을 바탕(빈 경로)으로 한 자리)

예제: 짝 없는 서로게이트로만 다른 두 키를 따로 읽기

```rust
use vanilla::misc::storagetext;

let entry_list = storagetext::parse_json_object_entries(r#"{"k\ud800":"one","k\ud801":"two"}"#).unwrap();
assert_eq!(entry_list.len(), 2);
assert_eq!(entry_list[0].key.get_lossy_text(), "k\u{fffd}");
assert_eq!(entry_list[1].key.get_lossy_text(), "k\u{fffd}");
assert_eq!(entry_list[1].key.get_code_units(), &[0x6B, 0xD801]);
assert_eq!(entry_list[1].value, "two");
assert!(entry_list[1].surrogate_table.is_empty());
```

- `pub key: PreservedText` (field, since 0.4.0): 키. (원래 UTF-16 단위와 대체 문자로 보인 글)
  - returns PreservedText
- `pub value: Value` (field, since 0.4.0): 값. (짝 없는 서로게이트는 대체 문자)
  - returns Value
- `pub surrogate_table: JsonSurrogateTable` (field, since 0.4.0): 값의 짝 없는 서로게이트 표. (값을 바탕(빈 경로)으로 한 자리)
  - returns JsonSurrogateTable

## Functions and constants

- `pub fn has_lone_surrogate(code_units: &[u16]) -> bool` (method, since 0.4.0): 짝 없는 서로게이트가 있는지.
  - `code_units` &[u16]: 볼 UTF-16 단위.
  - returns bool: 짝 없는 서로게이트가 하나라도 있으면 true.
- `pub fn quote_json_code_units(code_units: &[u16]) -> String` (method, since 0.4.0): JSON.stringify 의 글 따옴표. (QuoteJSONString: " 와 \ 와 \b \f \n \r \t, 그 밖의 U+0000 ~ U+001F 와 짝 없는 서로게이트는 \u 소문자 넷 자리)
  - `code_units` &[u16]: 따옴표로 감쌀 글의 UTF-16 단위.
  - returns String: JSON.stringify 가 쓰는 꼴의 JSON 글. (앞뒤 따옴표까지)
- `pub fn parse_json(text: &str) -> Result<(Value, JsonSurrogateTable), String>` (method, since 0.4.0): JSON 읽기. (JSON.parse 처럼, 짝 없는 서로게이트는 대체 문자로 읽고 표에 남긴다)
  - `text` &str: 읽을 JSON 글.
  - returns Result<(Value, JsonSurrogateTable), String>: 값과 그 짝 없는 서로게이트 표. 틀린 JSON 이면 Err(까닭과 그 자리).
- `pub fn parse_json_code_units(code_units: &[u16]) -> Result<(Value, JsonSurrogateTable), String>` (method, since 0.4.0): UTF-16 단위의 JSON 읽기. (원본 JS 글 그대로, 날 짝 없는 서로게이트도 받는다)
  - `code_units` &[u16]: 읽을 JSON 글의 UTF-16 단위. (날 짝 없는 서로게이트도 받는다)
  - returns Result<(Value, JsonSurrogateTable), String>: 값과 그 짝 없는 서로게이트 표. 틀린 JSON 이면 Err(까닭과 그 자리).
- `pub fn parse_json_object_entries(text: &str) -> Result<Vec<JsonObjectEntry>, String>` (method, since 0.4.0): 맨 위가 객체인 JSON 을 칸 목록으로 읽기. (맨 위가 객체가 아니면 빈 목록)
  - 짝 없는 서로게이트로만 다른 두 키도 따로 담는다. (serde_json 맵에서는 대체 문자로 같은 키가 되어 하나만 남는다)
  - 차례는 글에 적힌 차례고, 같은 키가 또 나와도 모두 담는다. (JSON.parse 처럼 뒤의 값이 이기게 하려면 담는 쪽이 덮어쓴다)
  - `text` &str: 읽을 JSON 글.
  - returns Result<Vec<JsonObjectEntry>, String>: 칸 목록. (글에 적힌 차례, 맨 위가 객체가 아니면 빈 목록) 틀린 JSON 이면 Err(까닭과 그 자리).
- `pub fn stringify_json(value: &Value, surrogate_table: &JsonSurrogateTable) -> String` (method, since 0.4.0): JSON 쓰기. (원본 JSON.stringify(value) 와 글자까지 같다, 표에 남은 글은 원래 단위로)
  - 수는 원본 String(수) 꼴이다. (1.0 → 1, -0 → 0, 1e21 → 1e+21, 큰 정수도 f64 로 바꿔 쓴다)
  - 객체 칸 차례는 원본 JS 객체처럼 배열 번호 꼴 이름("0" ~ "4294967294")을 수 차례로 먼저, 나머지는 넣은 차례다.
  - 글은 원본 QuoteJSONString 꼴이다. (quote_json_text)
  - 엔진이 JSON 을 쓰는 길(LocalStorage, PersistedStore, UIDocument, WebSocketClient, 초안 세이브)이 모두 이것을 쓴다.
  - `value` &Value: 쓸 값.
  - `surrogate_table` &JsonSurrogateTable: parse_json 이 남긴 표. (따로 읽은 글이 없으면 JsonSurrogateTable::new())
  - returns String: JSON 글.

  예제: 원본 JSON.stringify 와 같은 글

  ```rust
  use vanilla::misc::storagetext::{self, JsonSurrogateTable};
  
  let value = serde_json::json!({ "b": 1.0, "2": -0.0, "a": [1e21, 0.1, 1e-7], "1": "x\ny" });
  assert_eq!(storagetext::stringify_json(&value, &JsonSurrogateTable::new()), r#"{"1":"x\ny","2":0,"b":1,"a":[1e+21,0.1,1e-7]}"#);
  ```

- `pub fn stringify_json_at(value: &Value, base_path: &[JsonPathSegment], surrogate_table: &JsonSurrogateTable) -> String` (method, since 0.4.0): JSON 쓰기. (값이 표의 base_path 자리에 있던 것일 때)
  - `value` &Value: 쓸 값.
  - `base_path` &[JsonPathSegment]: 이 값이 표에서 있던 자리. (빈 경로면 stringify_json 과 같다)
  - `surrogate_table` &JsonSurrogateTable: parse_json 이 남긴 표.
  - returns String: JSON 글.
- `pub fn stringify_json_with_space(value: &Value, space: &str, surrogate_table: &JsonSurrogateTable) -> String` (method, since 0.4.0): 들여 쓴 JSON 쓰기. (원본 JSON.stringify(value, null, space) 와 글자까지 같다)
  - 빈 배열과 빈 객체는 [] 와 {}, 그 밖에는 한 칸에 한 줄씩 space 를 깊이만큼 앞에 둔다. 객체 칸은 "이름": 값 꼴이다.
  - 원본처럼 space 는 앞 10 글자까지만 쓴다. (빈 글이면 stringify_json 과 같다)
  - `value` &Value: 쓸 값.
  - `space` &str: 들여쓰기 글. (원본 JSON.stringify 의 셋째 인자, 예: "\t", "  ")
  - `surrogate_table` &JsonSurrogateTable: parse_json 이 남긴 표. (따로 읽은 글이 없으면 JsonSurrogateTable::new())
  - returns String: JSON 글.

  예제: 탭으로 들여 쓰기

  ```rust
  use vanilla::misc::storagetext::{self, JsonSurrogateTable};
  
  let value = serde_json::json!({ "version": 1, "root": { "list": [2.5, []], "empty": {} } });
  let json_text = storagetext::stringify_json_with_space(&value, "\t", &JsonSurrogateTable::new());
  assert_eq!(json_text, "{\n\t\"version\": 1,\n\t\"root\": {\n\t\t\"list\": [\n\t\t\t2.5,\n\t\t\t[]\n\t\t],\n\t\t\"empty\": {}\n\t}\n}");
  ```

- `pub fn quote_json_text(text: &str) -> String` (method, since 0.4.0): JSON.stringify 의 글 따옴표. (원본 JSON.stringify(text) 와 같다, 앞뒤 따옴표까지)
  - `text` &str: 쓸 글.
  - returns String: JSON 글.

  예제: 이스케이프

  ```rust
  use vanilla::misc::storagetext;
  
  assert_eq!(storagetext::quote_json_text("a\"b\\\n\u{1}"), r#""a\"b\\\n\u0001""#);
  ```

## JsonPathSegment (enum) (Clone, Debug, PartialEq, Eq, Hash)

JSON 경로 한 마디. (객체 키나 배열 차례)

- `Key` = `Key(String)`: 객체 키.
- `Index` = `Index(usize)`: 배열 차례. (0 부터)
