use std::collections::HashMap;
use crate::limits::GlobalHasher;
use crate::error::{Error, ErrorCode, ErrorKind};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Owner {
Root,
Block(usize),
Unknown,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Continuation {
Flow,
Indent(usize),
Line {
start_indent: usize,
standalone: bool,
allow_block_indicator: bool,
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum LineShape {
Owner(Owner),
Open,
Content,
}
#[inline]
pub(super) fn leading_spaces(text: &str) -> usize {
text.len() - text.trim_start_matches(' ').len()
}
pub(super) fn block_prefix(text: &str, compat: bool) -> (&str, usize, Option<Owner>) {
let (text, marker_possible) = if compat {
text.strip_prefix('\u{feff}')
.map_or((text, true), |rest| (rest, false))
} else {
(text.trim_start_matches('\u{feff}'), true)
};
let bytes = text.as_bytes();
let separator = |index: usize| index >= bytes.len() || matches!(bytes[index], b' ' | b'\t');
let skip_blanks = |mut index: usize| {
while index < bytes.len() && matches!(bytes[index], b' ' | b'\t') {
index += 1;
}
index
};
let mut index = 0;
while index < bytes.len() && bytes[index] == b' ' {
index += 1;
}
let mut owner = None;
if marker_possible && index == 0 && text.starts_with("---") && separator(3) {
owner = Some(Owner::Root);
index = skip_blanks(3);
}
while index < bytes.len() && matches!(bytes[index], b'-' | b'?' | b':') && separator(index + 1)
{
owner = Some(Owner::Block(index));
index = skip_blanks(index + 1);
}
(text, index, owner)
}
pub(super) fn line_shape(text: &str, names: NameRules<'_, '_>) -> LineShape {
let (text, index, owner) = block_prefix(text, names.compat);
let rest = &text[index..];
if let LineStop::Value(colon) = walk_line(rest, names) {
return if only_properties(&rest[colon + 1..], names.compat) {
LineShape::Owner(Owner::Block(text[..index].chars().count()))
} else {
LineShape::Content
};
}
if only_properties(rest, names.compat) {
owner.map_or(LineShape::Open, LineShape::Owner)
} else {
LineShape::Content
}
}
#[derive(Clone, Copy)]
pub(super) struct NameRules<'s, 'a> {
pub(super) compat: bool,
pub(super) colon_anchors: Option<&'s HashMap<&'a str, usize, GlobalHasher>>,
pub(super) input: &'a str,
}
impl NameRules<'_, '_> {
pub(super) fn alias_keeps_colon(self, name: &str) -> bool {
!self.compat
|| self.colon_anchors.is_some_and(|names| {
names.get(name).is_some_and(|&defined| {
name.as_ptr()
.addr()
.checked_sub(self.input.as_ptr().addr())
.is_some_and(|at| at <= self.input.len() && defined < at)
})
})
}
}
pub(super) fn only_properties(text: &str, compat: bool) -> bool {
text.split([' ', '\t'])
.filter(|token| !token.is_empty())
.all(|token| {
token.starts_with('!')
|| (token.starts_with('&')
&& !(compat
&& (1..token.len())
.any(|index| compat_name_stop(token.as_bytes(), index, 1))))
})
}
pub(super) fn compat_question_stops_name(after: Option<char>, in_flow: bool) -> bool {
after.is_some_and(|next| {
!is_blank(next)
&& !matches!(next, '[' | ']' | '{' | '}' | ',')
&& (in_flow || !matches!(next, '\u{85}' | '\u{2028}' | '\u{2029}'))
})
}
pub(super) fn compat_colon_stops_name(after: Option<char>) -> bool {
after.is_some_and(|next| !is_blank(next) && !matches!(next, '\u{85}' | '\u{2028}' | '\u{2029}'))
}
fn compat_name_stop(bytes: &[u8], index: usize, name_start: usize) -> bool {
let after = || {
std::str::from_utf8(&bytes[index + 1..])
.ok()
.and_then(|rest| rest.chars().next())
};
match bytes[index] {
b'?' => compat_question_stops_name(after(), false),
b':' => index > name_start && compat_colon_stops_name(after()),
_ => false,
}
}
#[derive(Debug, PartialEq, Eq)]
pub(super) enum LineStop {
Value(usize),
Comment(usize),
End,
}
pub(super) fn walk_line(text: &str, names: NameRules<'_, '_>) -> LineStop {
let bytes = text.as_bytes();
let mut index = 0;
let mut in_plain = false;
while index < bytes.len() {
let byte = bytes[index];
match byte {
b'#' if index == 0 || matches!(bytes[index - 1], b' ' | b'\t') => {
return LineStop::Comment(index);
}
b':' if bytes
.get(index + 1)
.is_none_or(|next| matches!(next, b' ' | b'\t')) =>
{
return LineStop::Value(index);
}
_ if in_plain => {}
b'"' | b'\'' => index = closing_quote(bytes, index),
b'!' | b'&' | b'*' => {
let name_start = index + 1;
while index + 1 < bytes.len() && !matches!(bytes[index + 1], b' ' | b'\t') {
if names.compat
&& byte != b'!'
&& compat_name_stop(bytes, index + 1, name_start)
{
break;
}
index += 1;
}
if byte == b'*'
&& index > name_start
&& bytes[index] == b':'
&& !names.alias_keeps_colon(&text[name_start..=index])
{
return LineStop::Value(index);
}
}
b'[' | b'{' => match flow_collection_end(bytes, index, names.compat) {
Some(end) => index = end,
None => return LineStop::End,
},
b' ' | b'\t' => {}
_ => in_plain = true,
}
index += 1;
}
LineStop::End
}
pub(super) fn starts_block_collection(line: &str, names: NameRules<'_, '_>) -> bool {
let bytes = line.as_bytes();
let separated = |index: usize| {
bytes
.get(index + 1)
.is_none_or(|next| matches!(next, b' ' | b'\t'))
};
let skip_blanks = |mut index: usize| {
while matches!(bytes.get(index), Some(b' ' | b'\t')) {
index += 1;
}
index
};
if matches!(bytes.first(), Some(b'-' | b'?')) && separated(0) {
return true;
}
let mut index = 0;
while let Some(&property @ (b'!' | b'&')) = bytes.get(index) {
let name_start = index + 1;
index = name_start;
while index < bytes.len()
&& !matches!(bytes[index], b' ' | b'\t')
&& !(names.compat && property == b'&' && compat_name_stop(bytes, index, name_start))
{
index += 1;
}
index = skip_blanks(index);
}
let end = match bytes.get(index) {
Some(b':') if separated(index) => return true,
Some(b'-' | b'?') if separated(index) => return false,
None | Some(b'#' | b'|' | b'>' | b',' | b']' | b'}' | b'%' | b'@' | b'`') => return false,
Some(b'"' | b'\'') => {
let close = closing_quote(bytes, index);
if close >= bytes.len() {
return false;
}
close + 1
}
Some(b'[' | b'{') => match flow_collection_end(bytes, index, names.compat) {
Some(close) => close + 1,
None => return false,
},
Some(b'*') => {
let name_end = (index..bytes.len())
.find(|&at| matches!(bytes[at], b' ' | b'\t'))
.unwrap_or(bytes.len());
if let LineStop::Value(_) = walk_line(&line[index..name_end], names) {
return true;
}
name_end
}
Some(_) => return matches!(walk_line(&line[index..], names), LineStop::Value(_)),
};
let after = skip_blanks(end);
bytes.get(after) == Some(&b':') && separated(after)
}
pub(super) fn flow_collection_end(bytes: &[u8], open: usize, compat: bool) -> Option<usize> {
let blank_follows = |index: usize| matches!(bytes.get(index + 1), Some(b' ' | b'\t'));
let mut depth = 0_usize;
let mut index = open;
let mut after_json_like = false;
while index < bytes.len() {
let byte = bytes[index];
if matches!(byte, b' ' | b'\t') {
index += 1;
continue;
}
let mut json_like = false;
match byte {
b'#' => return None,
b'[' | b'{' => depth += 1,
b']' | b'}' => {
depth -= 1;
if depth == 0 {
return Some(index);
}
json_like = true;
}
b',' => {}
b'"' | b'\'' => {
index = closing_quote(bytes, index);
json_like = true;
}
b'!' if bytes.get(index + 1) == Some(&b'<') => {
while index + 1 < bytes.len() && bytes[index] != b'>' {
index += 1;
}
}
b'!' | b'&' | b'*' => {
while bytes
.get(index + 1)
.is_some_and(|next| !matches!(next, b' ' | b'\t' | b',' | b']' | b'}'))
{
index += 1;
}
}
b'?' if compat || blank_follows(index) => {}
b':' if after_json_like || blank_follows(index) => {}
_ => {
while let Some(&next) = bytes.get(index + 1) {
if matches!(next, b',' | b'[' | b']' | b'{' | b'}' | b':')
|| (next == b'#' && matches!(bytes[index], b' ' | b'\t'))
{
break;
}
index += 1;
}
}
}
after_json_like = json_like;
index += 1;
}
None
}
pub(super) fn closing_quote(bytes: &[u8], open: usize) -> usize {
let quote = bytes[open];
let mut index = open + 1;
while index < bytes.len() {
if quote == b'"' && bytes[index] == b'\\' {
index += 2;
continue;
}
if bytes[index] == quote {
if quote == b'\'' && bytes.get(index + 1) == Some(&b'\'') {
index += 2;
continue;
}
return index;
}
index += 1;
}
bytes.len()
}
pub(super) fn strip_comment<'t>(line: &'t str, names: NameRules<'_, '_>) -> &'t str {
let (text, mut from, _) = block_prefix(line, names.compat);
let mark = line.len() - text.len();
loop {
match walk_line(&text[from..], names) {
LineStop::Value(colon) => from += colon + 1,
LineStop::Comment(comment) => return &line[..mark + from + comment],
LineStop::End => return line,
}
}
}
pub(super) fn non_printable_error(input: &str, index: usize) -> Error {
let Some(ch) = input[index..].chars().next() else {
return Error::coded(
ErrorKind::Scanner,
ErrorCode::NonPrintableChar,
"invalid character boundary",
);
};
Error::coded(
ErrorKind::Scanner,
ErrorCode::NonPrintableChar,
format!(
"non-printable character U+{:04X} is not allowed in YAML",
u32::from(ch)
),
)
}
pub(super) enum PercentError {
Escape(usize),
Utf8,
}
pub(super) fn decode_percent_escapes(raw: &str) -> Result<String, PercentError> {
if !raw.contains('%') {
return Ok(raw.to_owned());
}
let bytes = raw.as_bytes();
let mut decoded = Vec::with_capacity(bytes.len());
let mut index = 0;
while index < bytes.len() {
if bytes[index] == b'%' {
let hex = raw
.get(index + 1..index + 3)
.filter(|digits| digits.bytes().all(|byte| byte.is_ascii_hexdigit()))
.and_then(|digits| u8::from_str_radix(digits, 16).ok())
.ok_or(PercentError::Escape(index))?;
decoded.push(hex);
index += 3;
} else {
decoded.push(bytes[index]);
index += 1;
}
}
String::from_utf8(decoded).map_err(|_| PercentError::Utf8)
}
#[inline]
pub(super) fn is_uri_char(ch: char) -> bool {
ch.is_ascii_alphanumeric()
|| matches!(
ch,
'-' | '#'
| ';'
| '/'
| '?'
| ':'
| '@'
| '&'
| '='
| '+'
| '$'
| ','
| '_'
| '.'
| '!'
| '~'
| '*'
| '\''
| '('
| ')'
| '['
| ']'
| '%'
)
}
pub(super) fn uri_text_ok(text: &str) -> bool {
let bytes = text.as_bytes();
text.char_indices().all(|(index, ch)| {
is_uri_char(ch)
&& (ch != '%'
|| (bytes.get(index + 1).is_some_and(u8::is_ascii_hexdigit)
&& bytes.get(index + 2).is_some_and(u8::is_ascii_hexdigit)))
})
}
#[inline]
pub(super) fn is_tag_char(ch: char) -> bool {
is_uri_char(ch) && !matches!(ch, '!' | ',' | '[' | ']' | '{' | '}')
}
#[inline]
pub(super) fn is_blank(ch: char) -> bool {
matches!(ch, ' ' | '\t') || is_line_break(ch)
}
#[inline]
pub(super) fn is_line_break(ch: char) -> bool {
matches!(ch, '\n' | '\r')
}