use std::fmt;
use super::Timestamp;
const LONG_TAG_PREFIX: &str = "tag:yaml.org,2002:";
#[derive(Debug, Clone, PartialEq)]
pub(in crate::schema::generate) enum Resolved {
Null,
Bool(bool),
Int(i64),
Uint(u64),
Float(f64),
Str(String),
Timestamp(Timestamp),
}
impl fmt::Display for Resolved {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Null => write!(f, "null"),
Self::Bool(b) => write!(f, "{b}"),
Self::Int(i) => write!(f, "{i}"),
Self::Uint(u) => write!(f, "{u}"),
Self::Float(x) => write!(f, "{x}"),
Self::Str(s) => write!(f, "{s}"),
Self::Timestamp(t) => write!(f, "{t}"),
}
}
}
pub(in crate::schema::generate) fn short_tag(tag: &str) -> String {
match tag.strip_prefix(LONG_TAG_PREFIX) {
Some(rest) => format!("!!{rest}"),
None => tag.to_owned(),
}
}
fn resolvable(tag: &str) -> bool {
matches!(
tag,
"" | "!!str" | "!!bool" | "!!int" | "!!float" | "!!null" | "!!timestamp"
)
}
pub(in crate::schema::generate) fn resolve(
tag: &str,
input: &str,
) -> Result<(String, Resolved), String> {
let tag = short_tag(tag);
if !resolvable(&tag) {
return Ok((tag, Resolved::Str(input.to_owned())));
}
let (rtag, value) = resolve_implicit(&tag, input);
if tag.is_empty() || tag == rtag || tag == "!!str" || tag == "!!binary" {
return Ok((rtag, value));
}
if tag == "!!float" {
match value {
Resolved::Int(i) if rtag == "!!int" => {
#[allow(clippy::cast_precision_loss)]
return Ok(("!!float".to_owned(), Resolved::Float(i as f64)));
}
_ => {}
}
}
Err(format!("cannot decode {rtag} `{input}` as a {tag}"))
}
fn resolve_implicit(tag: &str, input: &str) -> (String, Resolved) {
let hint = match input.as_bytes().first() {
None => b'N',
Some(b'+' | b'-') => b'S',
Some(b'0'..=b'9') => b'D',
Some(b'y' | b'Y' | b'n' | b'N' | b't' | b'T' | b'f' | b'F' | b'o' | b'O' | b'~') => b'M',
Some(b'.') => b'.',
Some(_) => 0,
};
let string = || ("!!str".to_owned(), Resolved::Str(input.to_owned()));
if hint == 0 || tag == "!!str" || tag == "!!binary" {
return string();
}
if let Some(found) = lookup(input) {
return found;
}
match hint {
b'.' => match go_parse_float(input) {
Some(f) => ("!!float".to_owned(), Resolved::Float(f)),
None => string(),
},
b'D' | b'S' => resolve_number(tag, input).unwrap_or_else(string),
_ => string(),
}
}
fn lookup(input: &str) -> Option<(String, Resolved)> {
let found = match input {
"true" | "True" | "TRUE" => ("!!bool", Resolved::Bool(true)),
"false" | "False" | "FALSE" => ("!!bool", Resolved::Bool(false)),
"" | "~" | "null" | "Null" | "NULL" => ("!!null", Resolved::Null),
".nan" | ".NaN" | ".NAN" => ("!!float", Resolved::Float(f64::NAN)),
".inf" | ".Inf" | ".INF" | "+.inf" | "+.Inf" | "+.INF" => {
("!!float", Resolved::Float(f64::INFINITY))
}
"-.inf" | "-.Inf" | "-.INF" => ("!!float", Resolved::Float(f64::NEG_INFINITY)),
"<<" => ("!!merge", Resolved::Str("<<".to_owned())),
_ => return None,
};
Some((found.0.to_owned(), found.1))
}
fn resolve_number(tag: &str, input: &str) -> Option<(String, Resolved)> {
let plain = input.replace('_', "");
if (tag.is_empty() || tag == "!!timestamp")
&& let Some(stamp) = Timestamp::parse(input)
{
return Some(("!!timestamp".to_owned(), Resolved::Timestamp(stamp)));
}
if let Some(int) = go_parse_int(&plain) {
return Some(("!!int".to_owned(), Resolved::Int(int)));
}
if let Some(uint) = go_parse_uint(&plain) {
return Some(("!!int".to_owned(), Resolved::Uint(uint)));
}
if yaml_style_float(&plain)
&& let Some(f) = go_parse_float(&plain)
{
return Some(("!!float".to_owned(), Resolved::Float(f)));
}
None
}
fn yaml_style_float(s: &str) -> bool {
let bytes = s.as_bytes();
let mut at = usize::from(matches!(bytes.first(), Some(b'+' | b'-')));
let digits = |at: &mut usize| {
let start = *at;
while bytes.get(*at).is_some_and(u8::is_ascii_digit) {
*at += 1;
}
*at - start
};
if bytes.get(at) == Some(&b'.') {
at += 1;
if digits(&mut at) == 0 {
return false;
}
} else {
if digits(&mut at) == 0 {
return false;
}
if bytes.get(at) == Some(&b'.') {
at += 1;
digits(&mut at);
}
}
if matches!(bytes.get(at), Some(b'e' | b'E')) {
at += 1;
if matches!(bytes.get(at), Some(b'+' | b'-')) {
at += 1;
}
if digits(&mut at) == 0 {
return false;
}
}
at == bytes.len()
}
pub(in crate::schema::generate) fn go_parse_uint(s: &str) -> Option<u64> {
let bytes = s.as_bytes();
if bytes.is_empty() {
return None;
}
let lower = |i: usize| bytes[i].to_ascii_lowercase();
let (base, digits) = if bytes[0] == b'0' {
match () {
() if bytes.len() >= 3 && lower(1) == b'b' => (2, &bytes[2..]),
() if bytes.len() >= 3 && lower(1) == b'o' => (8, &bytes[2..]),
() if bytes.len() >= 3 && lower(1) == b'x' => (16, &bytes[2..]),
() => (8, &bytes[1..]),
}
} else {
(10, bytes)
};
let mut value = 0_u64;
for &byte in digits {
let digit = match byte {
b'0'..=b'9' => u64::from(byte - b'0'),
b'a'..=b'z' => u64::from(byte - b'a') + 10,
b'A'..=b'Z' => u64::from(byte - b'A') + 10,
_ => return None,
};
if digit >= base {
return None;
}
value = value.checked_mul(base)?.checked_add(digit)?;
}
Some(value)
}
pub(in crate::schema::generate) fn go_parse_int(s: &str) -> Option<i64> {
let (negative, rest) = match s.as_bytes().first()? {
b'+' => (false, &s[1..]),
b'-' => (true, &s[1..]),
_ => (false, s),
};
let magnitude = go_parse_uint(rest)?;
if negative {
return 0_i64.checked_sub_unsigned(magnitude);
}
i64::try_from(magnitude).ok()
}
pub(in crate::schema::generate) fn go_parse_float(s: &str) -> Option<f64> {
let (negative, body) = match s.as_bytes().first()? {
b'+' => (false, &s[1..]),
b'-' => (true, &s[1..]),
_ => (false, s),
};
let lower = body.to_ascii_lowercase();
let signed = |f: f64| if negative { -f } else { f };
match lower.as_str() {
"inf" | "infinity" => return Some(signed(f64::INFINITY)),
"nan" => return Some(f64::NAN),
_ => {}
}
if let Some(hex) = lower.strip_prefix("0x") {
return parse_hex_float(hex).map(signed);
}
if lower.is_empty()
|| !lower
.bytes()
.all(|b| b.is_ascii_digit() || matches!(b, b'.' | b'e' | b'+' | b'-'))
|| lower.starts_with(['e', '+', '-'])
{
return None;
}
let value: f64 = lower.parse().ok()?;
value.is_finite().then(|| signed(value))
}
fn parse_hex_float(s: &str) -> Option<f64> {
let (mantissa, exponent) = s.split_once('p')?;
let exponent: i32 = exponent
.strip_prefix('+')
.unwrap_or(exponent)
.parse()
.ok()?;
let (whole, fraction) = mantissa.split_once('.').unwrap_or((mantissa, ""));
if whole.is_empty() && fraction.is_empty() {
return None;
}
let mut value = 0.0_f64;
for digit in whole.chars() {
value = value * 16.0 + f64::from(digit.to_digit(16)?);
}
let mut scale = 1.0 / 16.0;
for digit in fraction.chars() {
value += f64::from(digit.to_digit(16)?) * scale;
scale /= 16.0;
}
let result = value * 2.0_f64.powi(exponent);
result.is_finite().then_some(result)
}