use std::fmt::Write;
pub(crate) fn string(text: &str) -> String {
let mut out = String::with_capacity(text.len().saturating_add(2));
push(&mut out, text);
out
}
pub(super) fn push(out: &mut String, text: &str) {
out.push('"');
inner(out, text);
out.push('"');
}
pub(super) fn inner(out: &mut String, text: &str) {
if text.bytes().all(plain) {
out.push_str(text);
} else {
text.chars().for_each(|character| escaped(out, character));
}
}
const fn plain(byte: u8) -> bool {
matches!(byte, 0x20..=0x7E) && byte != b'"' && byte != b'\\'
}
fn escaped(out: &mut String, character: char) {
let named = match character {
'"' => "\\\"",
'\\' => "\\\\",
'\n' => "\\n",
'\r' => "\\r",
'\t' => "\\t",
'\u{8}' => "\\b",
'\u{c}' => "\\f",
_ => return unnamed(out, character),
};
out.push_str(named);
}
fn unnamed(out: &mut String, character: char) {
let code = u32::from(character);
if (0x20..0x7F).contains(&code) {
return out.push(character);
}
if code > 0xFFFF {
return surrogates(out, code);
}
unit(out, code);
}
fn unit(out: &mut String, code: u32) {
let _infallible = write!(out, "\\u{code:04x}");
}
fn surrogates(out: &mut String, code: u32) {
let rest = code.saturating_sub(0x1_0000);
unit(out, 0xD800 | (rest >> 10));
unit(out, 0xDC00 | (rest & 0x3FF));
}
#[cfg(test)]
mod tests {
use super::string;
#[test]
fn plain_ascii_is_left_alone() {
assert_eq!(string("src/a.rs"), "\"src/a.rs\"");
}
#[test]
fn a_quote_is_escaped() {
assert_eq!(string("a\"b"), "\"a\\\"b\"");
}
#[test]
fn a_backslash_is_escaped() {
assert_eq!(string("a\\b"), "\"a\\\\b\"");
}
#[test]
fn the_named_control_characters_use_their_short_escape() {
assert_eq!(string("\n\r\t"), "\"\\n\\r\\t\"");
assert_eq!(string("\u{8}\u{c}"), "\"\\b\\f\"");
}
#[test]
fn an_unnamed_control_character_becomes_a_u_escape() {
assert_eq!(string("\u{1}"), "\"\\u0001\"");
}
#[test]
fn delete_is_escaped_although_json_does_not_demand_it() {
assert_eq!(string("\u{7f}"), "\"\\u007f\"");
}
#[test]
fn a_non_ascii_code_point_leaves_as_a_u_escape() {
assert_eq!(string("\u{2014}"), "\"\\u2014\"");
}
#[test]
fn a_non_ascii_code_point_keeps_its_neighbours() {
assert_eq!(string("a\u{a0}b"), "\"a\\u00a0b\"");
}
#[test]
fn an_astral_code_point_becomes_a_surrogate_pair() {
assert_eq!(string("\u{1F600}"), "\"\\ud83d\\ude00\"");
}
}