use std::{iter::Peekable, str::CharIndices};
pub(super) fn decode(value: &str, escape: char, double_quotes: bool) -> Option<String> {
decode_with_positions(value, escape, double_quotes, |_, _| {})
}
pub(super) fn decode_with_positions(
value: &str,
escape: char,
double_quotes: bool,
mut emit: impl FnMut(usize, char),
) -> Option<String> {
let mut output = String::new();
let mut chars = value.char_indices().peekable();
while let Some((at, character)) = chars.next() {
let scalar = match character {
'\'' if double_quotes && consume(&mut chars, '\'') => '\'',
character if character == escape => decode_escape(&mut chars, escape)?,
character => character,
};
emit(at, scalar);
output.push(scalar);
}
Some(output)
}
fn decode_escape(chars: &mut Peekable<CharIndices<'_>>, escape: char) -> Option<char> {
if consume(chars, escape) {
return Some(escape);
}
let scalar = codepoint(chars)?;
if !(0xD800..=0xDBFF).contains(&scalar) {
return char::from_u32(scalar);
}
consume(chars, escape).then_some(())?;
let low = codepoint(chars)?;
(0xDC00..=0xDFFF).contains(&low).then_some(())?;
char::from_u32(0x10000 + ((scalar - 0xD800) << 10) + (low - 0xDC00))
}
fn consume(chars: &mut Peekable<CharIndices<'_>>, expected: char) -> bool {
chars
.next_if(|(_, character)| *character == expected)
.is_some()
}
fn codepoint(chars: &mut Peekable<CharIndices<'_>>) -> Option<u32> {
let digits = if consume(chars, '+') { 6 } else { 4 };
let codepoint = chars
.take(digits)
.map(|(_, character)| character)
.collect::<String>();
(codepoint.len() == digits && codepoint.chars().all(|digit| digit.is_ascii_hexdigit()))
.then(|| u32::from_str_radix(&codepoint, 16).ok())
.flatten()
}
#[cfg(all(test, any(nm_shard_all, nm_shard_1)))]
mod tests;