use super::Context;
#[derive(Clone, Copy, Debug, Default)]
#[expect(
clippy::struct_excessive_bools,
reason = "each flag is a separate finding of the one pass"
)]
pub(super) struct Scan {
pub(super) apostrophes: usize,
pub(super) quotes: usize,
pub(super) backslashes: usize,
pub(super) breaks: bool,
pub(super) escapes: bool,
pub(super) plain: bool,
pub(super) literal: bool,
pub(super) folded: bool,
}
impl Scan {
pub(super) fn of(value: &str, context: Context) -> Self {
let bytes = value.as_bytes();
let flow = context == Context::Flow;
let mut scan = Self::default();
let mut syntax = starts_plain(bytes, flow) && !matches!(bytes.last(), Some(b' ' | b'\t'));
for (at, &byte) in bytes.iter().enumerate() {
if !NOTABLE[usize::from(byte)] {
continue;
}
match byte {
b'\'' => scan.apostrophes += 1,
b'"' => scan.quotes += 1,
b'\\' | b'\t' => scan.backslashes += 1,
b'\n' => scan.breaks = true,
b':' if bytes.get(at + 1).is_none_or(|&next| ends_plain(next, flow)) => {
syntax = false;
}
b'#' if at > 0 && matches!(bytes[at - 1], b' ' | b'\t') => syntax = false,
_ if flow && is_flow(byte) => syntax = false,
0x00..=0x1f | 0x7f => scan.escapes = true,
0x80.. => scan.escapes |= escaped(&bytes[at..]),
_ => {}
}
}
let carried = !scan.escapes;
scan.plain = syntax && carried && !scan.breaks && reads_as_string(value);
scan.folded = carried && !scan.breaks && !bytes.is_empty();
scan.literal = carried && literal_reads_back(bytes);
scan
}
pub(super) fn double_only(self) -> bool {
self.breaks || self.escapes
}
}
const NOTABLE: [bool; 256] = {
let mut table = [false; 256];
let mut byte = 0;
while byte < table.len() {
table[byte] = byte < 0x20 || byte >= 0x7f;
byte += 1;
}
let marks = b"'\"\\:#,[]{}";
let mut at = 0;
while at < marks.len() {
table[marks[at] as usize] = true;
at += 1;
}
table
};
const INDICATORS: &[u8] = b",[]{}#&*!|>'\"%@`";
fn starts_plain(bytes: &[u8], flow: bool) -> bool {
match bytes {
[] => false,
[b'?'] => flow,
[b'-' | b'?' | b':', rest @ ..] => !matches!(rest.first(), None | Some(b' ' | b'\t')),
[first, ..] => !matches!(first, b' ' | b'\t') && !INDICATORS.contains(first),
}
}
fn ends_plain(next: u8, flow: bool) -> bool {
matches!(next, b' ' | b'\t') || (flow && is_flow(next))
}
fn is_flow(byte: u8) -> bool {
matches!(byte, b',' | b'[' | b']' | b'{' | b'}')
}
fn escaped(bytes: &[u8]) -> bool {
matches!(
bytes,
[0xc2, 0x80..=0x9f, ..]
| [0xe2, 0x80, 0xa8 | 0xa9, ..]
| [0xef, 0xbb, 0xbf, ..]
| [0xef, 0xbf, 0xbe | 0xbf, ..]
)
}
fn literal_reads_back(bytes: &[u8]) -> bool {
match bytes.iter().position(|&byte| byte != b'\n') {
Some(first) => first == 0 || bytes[first] != b' ',
None => bytes.len() >= 2,
}
}
fn reads_as_string(text: &str) -> bool {
let bytes = text.as_bytes();
match bytes {
b"~" => false,
[b'n' | b'N', ..] => !bytes.eq_ignore_ascii_case(b"null"),
[b't' | b'T', ..] => !bytes.eq_ignore_ascii_case(b"true"),
[b'f' | b'F', ..] => !bytes.eq_ignore_ascii_case(b"false"),
[b'0'..=b'9' | b'+' | b'-' | b'.', ..] => !number(text),
_ => true,
}
}
fn number(text: &str) -> bool {
let bytes = text.as_bytes();
let (negative, unsigned) = match bytes {
[b'-', rest @ ..] => (true, rest),
[b'+', rest @ ..] => (false, rest),
_ => (false, bytes),
};
if unsigned.eq_ignore_ascii_case(b".inf") || unsigned.eq_ignore_ascii_case(b".nan") {
return true;
}
if let [b'0', radix, digits @ ..] = unsigned {
let radix = match radix {
b'x' | b'X' => Some(16),
b'o' | b'O' => Some(8),
b'b' | b'B' => Some(2),
_ => None,
};
if let Some(radix) = radix {
return integer(digits, radix, negative);
}
}
let leading_zero = unsigned.len() > 1 && unsigned[0] == b'0';
(!leading_zero && integer(unsigned, 10, negative)) || float(text, unsigned)
}
fn integer(digits: &[u8], radix: u32, negative: bool) -> bool {
let limit = if negative { 1 << 63 } else { u64::MAX };
let mut value: u64 = 0;
let mut any = false;
for (at, &byte) in digits.iter().enumerate() {
if byte == b'_' {
let between = at > 0
&& digits[at - 1] != b'_'
&& digits.get(at + 1).is_some_and(|&next| next != b'_');
if !between {
return false;
}
continue;
}
let Some(digit) = char::from(byte).to_digit(radix) else {
return false;
};
let Some(next) = value
.checked_mul(u64::from(radix))
.and_then(|value| value.checked_add(u64::from(digit)))
.filter(|&value| value <= limit)
else {
return false;
};
value = next;
any = true;
}
any
}
fn float(text: &str, unsigned: &[u8]) -> bool {
let digits = |bytes: &[u8]| {
bytes
.iter()
.take_while(|byte| byte.is_ascii_digit())
.count()
};
let whole = digits(unsigned);
let mut rest = &unsigned[whole..];
let mut fraction = 0;
if let [b'.', tail @ ..] = rest {
fraction = digits(tail);
rest = &tail[fraction..];
}
if whole + fraction == 0 {
return false;
}
let [b'e' | b'E', tail @ ..] = rest else {
return rest.is_empty();
};
let tail = match tail {
[b'+' | b'-', rest @ ..] => rest,
_ => tail,
};
let exponent = digits(tail);
exponent > 0
&& exponent == tail.len()
&& (whole > 0 || text.parse::<f64>().is_ok_and(f64::is_finite))
}