vanilladocs
vanillapunch.com
API / misc/storagetext

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 로 쓴다. 대체 문자로 보이는 글이 같은데 원래 단위가 서로 다른 글이 둘 이상이면 자리가 맞는 것만 원래 단위로 쓴다.

The engine's JSON text writing and preservation of unpaired surrogates in stored text. (used by every engine path that writes JSON; the surrogate table is used by LocalStorage and PersistedStore)

  • The original localStorage and JSON are JS strings (UTF-16), so they hold unpaired surrogates (U+D800 ~ U+DFFF that lost their pair). They come from user input such as cut emoji, and JSON.stringify writes them as escapes like \ud83d. (the well-formed JSON.stringify of ES2019)
  • Rust String is UTF-8 and cannot hold such text. So they appear as the replacement character (U+FFFD) on the Rust side, and unmodified text is written back in its original UTF-16 units. Values saved by the original version are not lost when the Rust version reads and rewrites them.
  • PreservedText: the original UTF-16 units and the text as displayed with replacement characters.
  • parse_json, parse_json_code_units: read like JSON.parse but read unpaired surrogates (both escapes and raw units) as the replacement character, and record the places (JSON paths) where such text was and the original units in a JsonSurrogateTable. Numbers are the same as what serde_json reads.
  • stringify_json, stringify_json_with_space: write text identical to the original JSON.stringify down to the character (used by every engine path that writes JSON), but if text displayed with replacement characters is still at a place in the table, it writes the original units, and even at another place, if the text is the same (same as moving text over in the original), it writes the original units as \udXXX like JSON.stringify. If two or more texts look the same with replacement characters but have different original units, only those at matching places are written in the original units.

PreservedTextstruct traits Clone, Debug, PartialEq, Eq

소스source

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

Text shown with the original UTF-16 units and the replacement character.

예제Example잘린 이모지의 앞 반쪽을 든 글Text holding the first half of a cut emoji
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());
정적staticpub fn from_code_units(code_units: &[u16]) -> PreservedText#0.4.0 부터since 0.4.0소스source

UTF-16 단위로 만들기. (짝 없는 서로게이트는 대체 문자로 보인다)

Builds from UTF-16 units. (unpaired surrogates appear as the replacement character)

code_units&[u16]
원래 UTF-16 단위.The original UTF-16 units.

반환ReturnsPreservedText 그 단위와 대체 문자로 보인 글을 든 PreservedText.PreservedText holding those units and the text shown with the replacement character.

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

대체 문자로 보인 글.

Text shown with the replacement character.

반환Returns&str 짝 없는 서로게이트를 대체 문자(U+FFFD)로 바꾼 러스트 글.Rust text with unpaired surrogates replaced by the replacement character (U+FFFD).

메서드methodpub fn get_code_units(&self) -> &[u16]#0.4.0 부터since 0.4.0소스source

원래 UTF-16 단위.

The original UTF-16 units.

반환Returns&[u16] 만들 때 받은 원래 UTF-16 단위.The original UTF-16 units given at creation.

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

짝 없는 서로게이트가 있는지. (없으면 러스트 글과 같다)

Whether there are unpaired surrogates. (if not, it is the same as the Rust string)

반환Returnsbool 짝 없는 서로게이트가 있으면 true.True if there are unpaired surrogates.

JsonSurrogateTablestruct traits Clone, Debug, Default

소스source

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

Table of strings containing unpaired surrogates. (filled by parse_json and used by stringify_json)

예제Example원본이 쓴 `\ud83d` 를 읽고 그대로 다시 쓰기Reading `\ud83d` written by the original and writing it back unchanged
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);
생성자constructorpub fn new() -> JsonSurrogateTable#0.4.0 부터since 0.4.0소스source

빈 표.

Empty table.

반환ReturnsJsonSurrogateTable 빈 표.Empty table.

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

비었는지. (짝 없는 서로게이트가 든 글이 없었다)

Whether it is empty. (there were no strings containing unpaired surrogates)

반환Returnsbool 짝 없는 서로게이트가 든 글이 없었으면 true.True if there was no text containing unpaired surrogates.

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

그 자리 값 글의 원래 단위. (자리가 맞고 글이 그대로면 그것, 아니면 같은 글로 보이는 원래 글이 하나뿐일 때 그것)

The original units of the string value at that position. (that one if the position matches and the string is unchanged, otherwise the original string that looks the same, when there is exactly one)

path&[JsonPathSegment]
값의 자리. (맨 위 값에서부터의 JSON 경로)Place of the value. (JSON path from the top value)
text&str
지금 그 자리에 든 글.Text currently at that place.

반환ReturnsOption<&[u16]> 원래 UTF-16 단위. (자리가 맞고 글이 그대로면 그 자리의 것, 아니면 find_text_code_units 와 같다) 찾지 못하면 None.Original UTF-16 units. (those of that place if the place matches and the text is unchanged, otherwise the same as find_text_code_units) None if not found.

메서드methodpub fn find_text_code_units(&self, text: &str) -> Option<&[u16]>#0.4.0 부터since 0.4.0소스source

같은 글로 보이는 원래 글의 단위. (하나뿐일 때만)

Units of the original string that looks the same. (only when there is exactly one)

text&str
대체 문자로 보인 글.Text shown with the replacement character.

반환ReturnsOption<&[u16]> 원래 UTF-16 단위. 그렇게 보이는 원래 글이 없거나, 원래 단위가 서로 다른 글이 둘 이상이면 None.Original UTF-16 units. None if there is no original text shown as that, or two or more texts with different original units.

JsonObjectEntrystruct

소스source

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

One entry of a JSON object. (the key in original UTF-16 units, the value's table holds places with that value as the root (empty path))

예제Example짝 없는 서로게이트로만 다른 두 키를 따로 읽기Reading two keys that differ only by unpaired surrogates separately
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());
필드fieldpub key: PreservedText#0.4.0 부터since 0.4.0소스source

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

Key. (original UTF-16 units and the text shown with the replacement character)

반환ReturnsPreservedText

필드fieldpub value: Value#0.4.0 부터since 0.4.0소스source

값. (짝 없는 서로게이트는 대체 문자)

Value. (unpaired surrogates as the replacement character)

반환ReturnsValue

필드fieldpub surrogate_table: JsonSurrogateTable#0.4.0 부터since 0.4.0소스source

값의 짝 없는 서로게이트 표. (값을 바탕(빈 경로)으로 한 자리)

Unpaired surrogate table of the value. (places with the value as the root (empty path))

반환ReturnsJsonSurrogateTable

함수Functions

함수functionpub fn has_lone_surrogate(code_units: &[u16]) -> bool#0.4.0 부터since 0.4.0소스source

짝 없는 서로게이트가 있는지.

Whether there are unpaired surrogates.

code_units&[u16]
볼 UTF-16 단위.UTF-16 units to check.

반환Returnsbool 짝 없는 서로게이트가 하나라도 있으면 true.True if there is at least one unpaired surrogate.

함수functionpub fn quote_json_code_units(code_units: &[u16]) -> String#0.4.0 부터since 0.4.0소스source

JSON.stringify 의 글 따옴표. (QuoteJSONString: " 와 \ 와 \b \f \n \r \t, 그 밖의 U+0000 ~ U+001F 와 짝 없는 서로게이트는 \u 소문자 넷 자리)

String quoting of JSON.stringify. (QuoteJSONString: " and \ and \b \f \n \r \t, other U+0000 ~ U+001F and unpaired surrogates as \u with four lowercase digits)

code_units&[u16]
따옴표로 감쌀 글의 UTF-16 단위.UTF-16 units of the text to quote.

반환ReturnsString JSON.stringify 가 쓰는 꼴의 JSON 글. (앞뒤 따옴표까지)JSON text in the form JSON.stringify writes. (including the surrounding quotes)

함수functionpub fn parse_json(text: &str) -> Result<(Value, JsonSurrogateTable), String>#0.4.0 부터since 0.4.0소스source

JSON 읽기. (JSON.parse 처럼, 짝 없는 서로게이트는 대체 문자로 읽고 표에 남긴다)

Reads JSON. (like JSON.parse, unpaired surrogates are read as the replacement character and kept in the table)

text&str
읽을 JSON 글.JSON text to read.

반환ReturnsResult<(Value, JsonSurrogateTable), String> 값과 그 짝 없는 서로게이트 표. 틀린 JSON 이면 Err(까닭과 그 자리).The value and its unpaired surrogate table. Err(reason and position) if the JSON is invalid.

함수functionpub fn parse_json_code_units(code_units: &[u16]) -> Result<(Value, JsonSurrogateTable), String>#0.4.0 부터since 0.4.0소스source

UTF-16 단위의 JSON 읽기. (원본 JS 글 그대로, 날 짝 없는 서로게이트도 받는다)

Reads JSON from UTF-16 units. (the original JS string as is, raw unpaired surrogates accepted too)

code_units&[u16]
읽을 JSON 글의 UTF-16 단위. (날 짝 없는 서로게이트도 받는다)UTF-16 units of the JSON text to read. (also takes raw unpaired surrogates)

반환ReturnsResult<(Value, JsonSurrogateTable), String> 값과 그 짝 없는 서로게이트 표. 틀린 JSON 이면 Err(까닭과 그 자리).The value and its unpaired surrogate table. Err(reason and position) if the JSON is invalid.

함수functionpub fn parse_json_object_entries(text: &str) -> Result<Vec<JsonObjectEntry>, String>#0.4.0 부터since 0.4.0소스source

맨 위가 객체인 JSON 을 칸 목록으로 읽기. (맨 위가 객체가 아니면 빈 목록)

  • 짝 없는 서로게이트로만 다른 두 키도 따로 담는다. (serde_json 맵에서는 대체 문자로 같은 키가 되어 하나만 남는다)
  • 차례는 글에 적힌 차례고, 같은 키가 또 나와도 모두 담는다. (JSON.parse 처럼 뒤의 값이 이기게 하려면 담는 쪽이 덮어쓴다)

Reads JSON whose top level is an object as a list of entries. (an empty list if the top level is not an object)

  • Two keys that differ only by unpaired surrogates are also stored separately. (in a serde_json map they become the same key with the replacement character and only one remains)
  • The order is the order written in the text, and repeated keys are all stored. (to make later values win like JSON.parse, the receiving side overwrites)
text&str
읽을 JSON 글.JSON text to read.

반환ReturnsResult<Vec<JsonObjectEntry>, String> 칸 목록. (글에 적힌 차례, 맨 위가 객체가 아니면 빈 목록) 틀린 JSON 이면 Err(까닭과 그 자리).List of entries. (in the order written in the text, an empty list if the top is not an object) Err(reason and position) if the JSON is invalid.

함수functionpub fn stringify_json(value: &Value, surrogate_table: &JsonSurrogateTable) -> String#0.4.0 부터since 0.4.0소스source

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, 초안 세이브)이 모두 이것을 쓴다.

Writes JSON. (identical to the original JSON.stringify(value) down to the character; text left in the table is written in its original units)

  • Numbers use the original String(number) form. (1.0 → 1, -0 → 0, 1e21 → 1e+21, large integers are also converted to f64)
  • Object entries are ordered like an original JS object: array-index-like names ("0" ~ "4294967294") first in numeric order, then the rest in insertion order.
  • Text uses the original QuoteJSONString form. (quote_json_text)
  • Every engine path that writes JSON (LocalStorage, PersistedStore, UIDocument, WebSocketClient, the draft save) uses this.
value&Value
쓸 값.Value to write.
surrogate_table&JsonSurrogateTable
parse_json 이 남긴 표. (따로 읽은 글이 없으면 JsonSurrogateTable::new())The table left by parse_json. (JsonSurrogateTable::new() if no text was read)

반환ReturnsString JSON 글.JSON text.

예제Example원본 JSON.stringify 와 같은 글The same text as the original JSON.stringify
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]}"#);
함수functionpub fn stringify_json_at(value: &Value, base_path: &[JsonPathSegment], surrogate_table: &JsonSurrogateTable) -> String#0.4.0 부터since 0.4.0소스source

JSON 쓰기. (값이 표의 base_path 자리에 있던 것일 때)

Writes JSON. (when the value was at the base_path position of the table)

value&Value
쓸 값.Value to write.
base_path&[JsonPathSegment]
이 값이 표에서 있던 자리. (빈 경로면 stringify_json 과 같다)Place in the table where this value was. (same as stringify_json with an empty path)
surrogate_table&JsonSurrogateTable
parse_json 이 남긴 표.Table left by parse_json.

반환ReturnsString JSON 글.JSON text.

함수functionpub fn stringify_json_with_space(value: &Value, space: &str, surrogate_table: &JsonSurrogateTable) -> String#0.4.0 부터since 0.4.0소스source

들여 쓴 JSON 쓰기. (원본 JSON.stringify(value, null, space) 와 글자까지 같다)

  • 빈 배열과 빈 객체는 [] 와 {}, 그 밖에는 한 칸에 한 줄씩 space 를 깊이만큼 앞에 둔다. 객체 칸은 "이름": 값 꼴이다.
  • 원본처럼 space 는 앞 10 글자까지만 쓴다. (빈 글이면 stringify_json 과 같다)

Writes indented JSON. (identical to the original JSON.stringify(value, null, space) down to the character)

  • Empty arrays and objects are [] and {}; otherwise one entry per line with space repeated by depth in front. Object entries take the "name": value form.
  • As in the original, only the first 10 characters of space are used. (an empty string is the same as stringify_json)
value&Value
쓸 값.Value to write.
space&str
들여쓰기 글. (원본 JSON.stringify 의 셋째 인자, 예: "\t", " ")The indent text. (the third argument of the original JSON.stringify, e.g. "\t", " ")
surrogate_table&JsonSurrogateTable
parse_json 이 남긴 표. (따로 읽은 글이 없으면 JsonSurrogateTable::new())The table left by parse_json. (JsonSurrogateTable::new() if no text was read)

반환ReturnsString JSON 글.JSON text.

예제Example탭으로 들여 쓰기Indenting with tabs
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}");
함수functionpub fn quote_json_text(text: &str) -> String#0.4.0 부터since 0.4.0소스source

JSON.stringify 의 글 따옴표. (원본 JSON.stringify(text) 와 같다, 앞뒤 따옴표까지)

Quotes text for JSON.stringify. (same as the original JSON.stringify(text), including the surrounding quotes)

text&str
쓸 글.Text to write.

반환ReturnsString JSON 글.JSON text.

예제Example이스케이프Escapes
use vanilla::misc::storagetext;

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

JsonPathSegmentenum traits Clone, Debug, PartialEq, Eq, Hash

소스source

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

One segment of a JSON path. (an object key or an array index)

이름Name값Value설명Description
KeyKey(String)객체 키.Object key.
IndexIndex(usize)배열 차례. (0 부터)Array index. (from 0)