# misc/storagetext (vanilla-engine 0.4.0)

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

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.

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

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

Example: Text holding the first half of a cut emoji

```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): Builds from UTF-16 units. (unpaired surrogates appear as the replacement character)
  - `code_units` &[u16]: The original UTF-16 units.
  - returns PreservedText: PreservedText holding those units and the text shown with the replacement character.
- `pub fn get_lossy_text(&self) -> &str` (method, since 0.4.0): Text shown with the replacement character.
  - returns &str: Rust text with unpaired surrogates replaced by the replacement character (U+FFFD).
- `pub fn get_code_units(&self) -> &[u16]` (method, since 0.4.0): The original UTF-16 units.
  - returns &[u16]: The original UTF-16 units given at creation.
- `pub fn has_lone_surrogate(&self) -> bool` (method, since 0.4.0): Whether there are unpaired surrogates. (if not, it is the same as the Rust string)
  - returns bool: True if there are unpaired surrogates.

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

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

Example: Reading `\ud83d` written by the original and writing it back unchanged

```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): Empty table.
  - returns JsonSurrogateTable: Empty table.
- `pub fn is_empty(&self) -> bool` (method, since 0.4.0): Whether it is empty. (there were no strings containing unpaired surrogates)
  - returns bool: True if there was no text containing unpaired surrogates.
- `pub fn find_value_code_units(&self, path: &[JsonPathSegment], text: &str) -> Option<&[u16]>` (method, since 0.4.0): 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]: Place of the value. (JSON path from the top value)
  - `text` &str: Text currently at that place.
  - returns Option<&[u16]>: 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.
- `pub fn find_text_code_units(&self, text: &str) -> Option<&[u16]>` (method, since 0.4.0): Units of the original string that looks the same. (only when there is exactly one)
  - `text` &str: Text shown with the replacement character.
  - returns Option<&[u16]>: Original UTF-16 units. None if there is no original text shown as that, or two or more texts with different original units.

## JsonObjectEntry (struct)

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

```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): Key. (original UTF-16 units and the text shown with the replacement character)
  - returns PreservedText
- `pub value: Value` (field, since 0.4.0): Value. (unpaired surrogates as the replacement character)
  - returns Value
- `pub surrogate_table: JsonSurrogateTable` (field, since 0.4.0): Unpaired surrogate table of the value. (places with the value as the root (empty path))
  - returns JsonSurrogateTable

## Functions and constants

- `pub fn has_lone_surrogate(code_units: &[u16]) -> bool` (method, since 0.4.0): Whether there are unpaired surrogates.
  - `code_units` &[u16]: UTF-16 units to check.
  - returns bool: True if there is at least one unpaired surrogate.
- `pub fn quote_json_code_units(code_units: &[u16]) -> String` (method, since 0.4.0): 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 units of the text to quote.
  - returns String: JSON text in the form JSON.stringify writes. (including the surrounding quotes)
- `pub fn parse_json(text: &str) -> Result<(Value, JsonSurrogateTable), String>` (method, since 0.4.0): Reads JSON. (like JSON.parse, unpaired surrogates are read as the replacement character and kept in the table)
  - `text` &str: JSON text to read.
  - returns Result<(Value, JsonSurrogateTable), String>: The value and its unpaired surrogate table. Err(reason and position) if the JSON is invalid.
- `pub fn parse_json_code_units(code_units: &[u16]) -> Result<(Value, JsonSurrogateTable), String>` (method, since 0.4.0): Reads JSON from UTF-16 units. (the original JS string as is, raw unpaired surrogates accepted too)
  - `code_units` &[u16]: UTF-16 units of the JSON text to read. (also takes raw unpaired surrogates)
  - returns Result<(Value, JsonSurrogateTable), String>: The value and its unpaired surrogate table. Err(reason and position) if the JSON is invalid.
- `pub fn parse_json_object_entries(text: &str) -> Result<Vec<JsonObjectEntry>, String>` (method, since 0.4.0): 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 text to read.
  - returns Result<Vec<JsonObjectEntry>, String>: 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.
- `pub fn stringify_json(value: &Value, surrogate_table: &JsonSurrogateTable) -> String` (method, since 0.4.0): 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: The table left by parse_json. (JsonSurrogateTable::new() if no text was read)
  - returns String: JSON text.

  Example: The same text as the original 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): Writes JSON. (when the value was at the base_path position of the table)
  - `value` &Value: Value to write.
  - `base_path` &[JsonPathSegment]: Place in the table where this value was. (same as stringify_json with an empty path)
  - `surrogate_table` &JsonSurrogateTable: Table left by parse_json.
  - returns String: JSON text.
- `pub fn stringify_json_with_space(value: &Value, space: &str, surrogate_table: &JsonSurrogateTable) -> String` (method, since 0.4.0): 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: The indent text. (the third argument of the original JSON.stringify, e.g. "\t", "  ")
  - `surrogate_table` &JsonSurrogateTable: The table left by parse_json. (JsonSurrogateTable::new() if no text was read)
  - returns String: JSON text.

  Example: Indenting with tabs

  ```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): Quotes text for JSON.stringify. (same as the original JSON.stringify(text), including the surrounding quotes)
  - `text` &str: Text to write.
  - returns String: JSON text.

  Example: Escapes

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

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

- `Key` = `Key(String)`: Object key.
- `Index` = `Index(usize)`: Array index. (from 0)
