Files
pokerfreak/src/json/parse_string.rs
T

89 lines
3.3 KiB
Rust

use super::parse_error::fail;
use crate::fault::Fault;
fn hex4(bytes: &[u8], from: usize) -> Result<u32, Fault> {
let digits = bytes.get(from..from + 4).ok_or_else(|| fail(from, "truncated \\u escape"))?;
digits.iter().try_fold(0u32, |acc, b| {
char::from(*b)
.to_digit(16)
.map(|d| acc * 16 + d)
.ok_or_else(|| fail(from, "invalid \\u escape"))
})
}
/// Decodes the escape whose `u` is at `from`; returns the char and the end offset.
fn unicode_escape(bytes: &[u8], from: usize) -> Result<(char, usize), Fault> {
let first = hex4(bytes, from + 1)?;
let after = from + 5;
match first {
0xD800..=0xDBFF => {
let has_pair = bytes.get(after) == Some(&b'\\') && bytes.get(after + 1) == Some(&b'u');
let second = if has_pair { hex4(bytes, after + 2)? } else { 0 };
match second {
0xDC00..=0xDFFF => {
let code = 0x10000 + ((first - 0xD800) << 10) + (second - 0xDC00);
char::from_u32(code)
.map(|c| (c, after + 6))
.ok_or_else(|| fail(from, "invalid surrogate pair"))
}
_ => Err(fail(from, "unpaired high surrogate")),
}
}
0xDC00..=0xDFFF => Err(fail(from, "unpaired low surrogate")),
code => char::from_u32(code)
.map(|c| (c, after))
.ok_or_else(|| fail(from, "invalid code point")),
}
}
fn simple_escape(byte: u8) -> Option<char> {
match byte {
b'"' => Some('"'),
b'\\' => Some('\\'),
b'/' => Some('/'),
b'b' => Some('\u{8}'),
b'f' => Some('\u{c}'),
b'n' => Some('\n'),
b'r' => Some('\r'),
b't' => Some('\t'),
_ => None,
}
}
/// String whose opening quote is at `start`; returns the text and the offset after the closing quote.
pub fn string(bytes: &[u8], start: usize) -> Result<(String, usize), Fault> {
let mut out = String::new();
let mut pos = start + 1;
loop {
match bytes.get(pos) {
None => return Err(fail(pos, "unterminated string")),
Some(b'"') => return Ok((out, pos + 1)),
Some(b'\\') => match bytes.get(pos + 1) {
Some(b'u') => {
let (c, next) = unicode_escape(bytes, pos + 1)?;
out.push(c);
pos = next;
}
Some(other) => {
let c = simple_escape(*other).ok_or_else(|| fail(pos, "invalid escape"))?;
out.push(c);
pos += 2;
}
None => return Err(fail(pos, "unterminated string")),
},
Some(b) if *b < 0x20 => return Err(fail(pos, "control character in string")),
Some(_) => {
// Copy a whole run up to the next special byte (runs end on ASCII, so UTF-8 stays intact).
let run = bytes[pos..]
.iter()
.take_while(|b| **b != b'"' && **b != b'\\' && **b >= 0x20)
.count();
let chunk = std::str::from_utf8(&bytes[pos..pos + run])
.map_err(|_| fail(pos, "invalid UTF-8"))?;
out.push_str(chunk);
pos += run;
}
}
}
}