use crate::mrid::Mrid;
use crate::object::Compound;
use crate::schema::{EnumValueId, Primitive, Schema};
use std::fmt;
#[derive(Clone, PartialEq)]
pub enum Value {
Boolean(bool),
Integer(i64),
Float(Real),
Text(Box<str>),
Enum(EnumValueId),
Reference(Mrid),
Compound(Box<Compound>),
}
#[derive(Clone)]
pub struct Real(Repr);
#[derive(Clone)]
enum Repr {
Plain(f64),
Written(Box<(f64, Box<str>)>),
}
impl Real {
pub fn new(value: f64) -> Real {
Real(Repr::Plain(value))
}
pub fn from_document(value: f64, text: &str, prim: Primitive) -> Real {
if is_canonical_plain(value, text) || text == canonical(value, prim) {
return Real(Repr::Plain(value));
}
if !is_lexical(prim, text) {
return Real(Repr::Plain(value));
}
Real(Repr::Written(Box::new((value, text.into()))))
}
#[inline]
pub fn get(&self) -> f64 {
match &self.0 {
Repr::Plain(v) => *v,
Repr::Written(w) => w.0,
}
}
pub fn lexical(&self) -> Option<&str> {
match &self.0 {
Repr::Plain(_) => None,
Repr::Written(w) => Some(&w.1),
}
}
pub fn to_lexical_as(&self, prim: Primitive) -> String {
match &self.0 {
Repr::Plain(v) => canonical(*v, prim),
Repr::Written(w) if is_lexical(prim, &w.1) => w.1.to_string(),
Repr::Written(w) => canonical(w.0, prim),
}
}
}
impl PartialEq for Real {
fn eq(&self, other: &Real) -> bool {
self.get() == other.get()
}
}
impl fmt::Debug for Real {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.lexical() {
Some(s) => write!(f, "{}({s})", self.get()),
None => write!(f, "{}", self.get()),
}
}
}
impl fmt::Display for Real {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.to_lexical_as(Primitive::Float))
}
}
impl From<f64> for Real {
fn from(value: f64) -> Real {
Real::new(value)
}
}
fn is_canonical_plain(value: f64, text: &str) -> bool {
let abs = value.abs();
if abs != 0.0 && !(1e-5..1e16).contains(&abs) {
return false;
}
let body = match text.strip_prefix('-') {
Some(rest) => {
if value == 0.0 {
return false;
}
rest
}
None => {
if value < 0.0 {
return false;
}
text
}
};
let (int, frac) = match body.split_once('.') {
Some((i, f)) => (i, Some(f)),
None => (body, None),
};
let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
if !digits(int) || (int.len() > 1 && int.starts_with('0')) {
return false;
}
if let Some(f) = frac
&& (!digits(f) || f.ends_with('0'))
{
return false;
}
int.len() + frac.map_or(0, str::len) <= 17
}
fn canonical(value: f64, prim: Primitive) -> String {
match prim {
Primitive::Decimal => plain_decimal(value),
_ => format_float(value),
}
}
fn is_lexical(prim: Primitive, s: &str) -> bool {
let exponent_allowed = match prim {
Primitive::Float => true,
Primitive::Decimal => false,
_ => return false,
};
if matches!(s, "INF" | "-INF" | "+INF" | "NaN") {
return exponent_allowed;
}
let (mantissa, exponent) = match s.find(['e', 'E']) {
Some(i) if exponent_allowed => (&s[..i], Some(&s[i + 1..])),
Some(_) => return false,
None => (s, None),
};
let digits_around_point = |t: &str| {
let t = t.strip_prefix(['+', '-']).unwrap_or(t);
let (int, frac) = t.split_once('.').unwrap_or((t, ""));
!(int.is_empty() && frac.is_empty())
&& int.chars().all(|c| c.is_ascii_digit())
&& frac.chars().all(|c| c.is_ascii_digit())
};
let integer = |t: &str| {
let t = t.strip_prefix(['+', '-']).unwrap_or(t);
!t.is_empty() && t.chars().all(|c| c.is_ascii_digit())
};
digits_around_point(mantissa) && exponent.is_none_or(integer)
}
impl Value {
pub fn as_bool(&self) -> Option<bool> {
match self {
Value::Boolean(b) => Some(*b),
_ => None,
}
}
pub fn as_i64(&self) -> Option<i64> {
match self {
Value::Integer(i) => Some(*i),
Value::Float(f) => Some(f.get() as i64),
_ => None,
}
}
pub fn as_f64(&self) -> Option<f64> {
match self {
Value::Float(f) => Some(f.get()),
Value::Integer(i) => Some(*i as f64),
_ => None,
}
}
pub fn as_str(&self) -> Option<&str> {
match self {
Value::Text(s) => Some(s),
_ => None,
}
}
pub fn as_enum(&self) -> Option<EnumValueId> {
match self {
Value::Enum(e) => Some(*e),
_ => None,
}
}
pub fn as_reference(&self) -> Option<&Mrid> {
match self {
Value::Reference(m) => Some(m),
_ => None,
}
}
pub fn as_compound(&self) -> Option<&Compound> {
match self {
Value::Compound(c) => Some(c),
_ => None,
}
}
pub fn to_lexical(&self) -> Option<String> {
Some(match self {
Value::Boolean(b) => if *b { "true" } else { "false" }.to_owned(),
Value::Integer(i) => i.to_string(),
Value::Float(f) => f.to_lexical_as(Primitive::Float),
Value::Text(s) => s.to_string(),
Value::Enum(_) | Value::Reference(_) | Value::Compound(_) => return None,
})
}
pub fn to_lexical_as(&self, prim: Primitive) -> Option<String> {
match self {
Value::Float(f) => Some(f.to_lexical_as(prim)),
_ => self.to_lexical(),
}
}
pub fn fits(&self, prim: Primitive) -> bool {
match prim {
Primitive::Boolean => matches!(self, Value::Boolean(_)),
Primitive::Integer => matches!(self, Value::Integer(_)),
Primitive::Float | Primitive::Decimal => {
matches!(self, Value::Float(_) | Value::Integer(_))
}
Primitive::String
| Primitive::Date
| Primitive::DateTime
| Primitive::MonthDay
| Primitive::Time
| Primitive::Duration
| Primitive::Uri => matches!(self, Value::Text(_)),
}
}
pub fn shape(&self) -> &'static str {
match self {
Value::Boolean(_) => "a boolean",
Value::Integer(_) => "an integer",
Value::Float(_) => "a float",
Value::Text(_) => "text",
Value::Enum(_) => "an enumeration literal",
Value::Reference(_) => "a reference",
Value::Compound(_) => "a compound",
}
}
pub fn parse_primitive(prim: Primitive, text: &str) -> Result<Value, ParseValueError> {
let t = text.trim();
Ok(match prim {
Primitive::Boolean => match t {
"true" | "1" => Value::Boolean(true),
"false" | "0" => Value::Boolean(false),
_ => return Err(ParseValueError::new(prim, text)),
},
Primitive::Integer => Value::Integer(
t.parse::<i64>()
.or_else(|_| t.parse::<f64>().map(|f| f as i64))
.map_err(|_| ParseValueError::new(prim, text))?,
),
Primitive::Float | Primitive::Decimal => {
let f = parse_float(t).ok_or_else(|| ParseValueError::new(prim, text))?;
Value::Float(Real::from_document(f, t, prim))
}
Primitive::String
| Primitive::Date
| Primitive::DateTime
| Primitive::MonthDay
| Primitive::Time
| Primitive::Duration
| Primitive::Uri => Value::Text(text.into()),
})
}
}
impl From<bool> for Value {
fn from(b: bool) -> Value {
Value::Boolean(b)
}
}
impl From<i64> for Value {
fn from(i: i64) -> Value {
Value::Integer(i)
}
}
impl From<f64> for Value {
fn from(f: f64) -> Value {
Value::Float(Real::new(f))
}
}
impl From<Real> for Value {
fn from(r: Real) -> Value {
Value::Float(r)
}
}
impl From<&str> for Value {
fn from(s: &str) -> Value {
Value::Text(s.into())
}
}
impl From<String> for Value {
fn from(s: String) -> Value {
Value::Text(s.into_boxed_str())
}
}
impl From<EnumValueId> for Value {
fn from(e: EnumValueId) -> Value {
Value::Enum(e)
}
}
impl From<Mrid> for Value {
fn from(m: Mrid) -> Value {
Value::Reference(m)
}
}
impl From<Compound> for Value {
fn from(c: Compound) -> Value {
Value::Compound(Box::new(c))
}
}
fn parse_float(t: &str) -> Option<f64> {
if let Ok(f) = t.parse::<f64>() {
return Some(f);
}
let normalized = t.replace(['D', 'd'], "E");
if let Ok(f) = normalized.parse::<f64>() {
return Some(f);
}
let (_, tail) = normalized.split_once(',')?;
let unambiguous = !normalized.contains('.')
&& !tail.contains(',')
&& tail.chars().take_while(char::is_ascii_digit).count() != 3;
unambiguous
.then(|| normalized.replace(',', ".").parse::<f64>().ok())
.flatten()
}
fn format_float(f: f64) -> String {
if f.is_nan() {
return "NaN".to_owned();
}
if f.is_infinite() {
return if f > 0.0 { "INF" } else { "-INF" }.to_owned();
}
let abs = f.abs();
if abs != 0.0 && !(1e-5..1e16).contains(&abs) {
return format!("{f:E}");
}
plain_decimal(f)
}
fn plain_decimal(f: f64) -> String {
if !f.is_finite() {
return format_float(f);
}
let s = f.to_string();
if s == "-0" { "0".to_owned() } else { s }
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseValueError {
pub expected: Primitive,
pub text: String,
}
impl ParseValueError {
fn new(expected: Primitive, text: &str) -> Self {
ParseValueError {
expected,
text: text.chars().take(64).collect(),
}
}
}
impl fmt::Display for ParseValueError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "cannot parse {:?} from {:?}", self.expected, self.text)
}
}
impl std::error::Error for ParseValueError {}
impl fmt::Debug for Value {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Value::Boolean(b) => write!(f, "{b}"),
Value::Integer(i) => write!(f, "{i}"),
Value::Float(x) => write!(f, "{x}"),
Value::Text(s) => write!(f, "{s:?}"),
Value::Enum(e) => write!(f, "enum#{}", e.0),
Value::Reference(m) => write!(f, "->{m}"),
Value::Compound(c) => write!(f, "{{{} fields}}", c.len()),
}
}
}
pub fn display_value(schema: &Schema, v: &Value) -> String {
match v {
Value::Enum(e) => schema.enum_value(*e).name.to_owned(),
Value::Reference(m) => m.canonical(),
Value::Compound(c) => {
let fields: Vec<String> = c
.values()
.iter()
.map(|(a, v)| format!("{}={}", schema.attr(*a).label, display_value(schema, v)))
.collect();
format!("{{{}}}", fields.join(", "))
}
other => other.to_lexical().unwrap_or_default(),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_documents_spelling_of_a_number_survives_a_round_trip() {
for (text, prim) in [
("2.62637E-05", Primitive::Float),
("0e+000", Primitive::Float),
("250.000000", Primitive::Float),
("-330.750000", Primitive::Float),
("6.8E-08", Primitive::Float),
("1.0", Primitive::Float),
("250.000000", Primitive::Decimal),
] {
let v = Value::parse_primitive(prim, text).unwrap();
assert_eq!(
v.to_lexical_as(prim).as_deref(),
Some(text),
"{text:?} as {prim:?}"
);
}
}
#[test]
fn spelling_is_not_part_of_the_value() {
let written = Value::parse_primitive(Primitive::Float, "250.000000").unwrap();
let plain = Value::from(250.0);
assert_eq!(written, plain);
assert_eq!(written.as_f64(), Some(250.0));
}
#[test]
fn a_spelling_is_only_kept_when_it_is_a_conforming_lexical_form() {
let v = Value::parse_primitive(Primitive::Float, "1,5").unwrap();
assert_eq!(v.as_f64(), Some(1.5));
assert_eq!(v.to_lexical().as_deref(), Some("1.5"));
let v = Value::parse_primitive(Primitive::Float, "1.5D+3").unwrap();
assert_eq!(v.to_lexical().as_deref(), Some("1500"));
let v = Value::parse_primitive(Primitive::Float, "6.8E-08").unwrap();
assert_eq!(
v.to_lexical_as(Primitive::Decimal).as_deref(),
Some("0.000000068")
);
}
#[test]
fn the_shape_test_never_disagrees_with_formatting() {
let texts = [
"0",
"1",
"-1",
"250",
"2.2",
"-330.75",
"0.0000262637",
"1e5",
"1E5",
"0e+000",
"250.000000",
"-0",
"007",
"1.0",
"0.10",
"+1",
"1.5D+3",
"1,5",
"12345678901234567",
"0.30000000000000004",
"1.7976931348623157E308",
"5E-324",
"-2.62637E-05",
];
for text in texts {
let Some(v) = parse_float(text) else { continue };
for prim in [Primitive::Float, Primitive::Decimal] {
if is_canonical_plain(v, text) {
assert_eq!(
text,
canonical(v, prim),
"{text:?} claimed canonical for {prim:?}"
);
}
}
}
}
#[test]
fn parses_the_primitive_forms_used_in_exchange_files() {
assert_eq!(
Value::parse_primitive(Primitive::Boolean, "true").unwrap(),
Value::Boolean(true)
);
assert_eq!(
Value::parse_primitive(Primitive::Boolean, " false ").unwrap(),
Value::Boolean(false)
);
assert_eq!(
Value::parse_primitive(Primitive::Integer, "42").unwrap(),
Value::Integer(42)
);
assert_eq!(
Value::parse_primitive(Primitive::Float, "-67.2335").unwrap(),
Value::from(-67.2335)
);
assert_eq!(
Value::parse_primitive(Primitive::Float, "1.5E3").unwrap(),
Value::from(1500.0)
);
}
#[test]
fn tolerates_non_conforming_numeric_forms() {
assert_eq!(
Value::parse_primitive(Primitive::Float, "1.5D+3").unwrap(),
Value::from(1500.0)
);
assert_eq!(
Value::parse_primitive(Primitive::Integer, "7.0").unwrap(),
Value::Integer(7)
);
}
#[test]
fn rejects_unparseable_values() {
assert!(Value::parse_primitive(Primitive::Boolean, "yes").is_err());
assert!(Value::parse_primitive(Primitive::Float, "abc").is_err());
}
#[test]
fn a_comma_is_only_read_as_a_decimal_mark_where_it_cannot_be_a_thousands_separator() {
let f = |s: &str| Value::parse_primitive(Primitive::Float, s);
assert_eq!(f("-67,2335").unwrap(), Value::from(-67.2335));
assert_eq!(f("1,5").unwrap(), Value::from(1.5));
assert_eq!(f("1,5E3").unwrap(), Value::from(1500.0));
assert!(f("1,234").is_err(), "1,234 is ambiguous");
assert!(f("1,000").is_err(), "1,000 is ambiguous");
assert!(f("1,234.5").is_err());
assert!(f("1,234,567").is_err());
}
#[test]
fn ordinary_rust_values_convert_to_the_right_variant() {
assert_eq!(Value::from(true), Value::Boolean(true));
assert_eq!(Value::from(7i64), Value::Integer(7));
assert_eq!(Value::from(2.2f64), Value::from(2.2));
assert_eq!(Value::from("BE-Line_1"), Value::Text("BE-Line_1".into()));
assert_eq!(
Value::from(String::from("owned")),
Value::Text("owned".into())
);
let m = Mrid::parse("70c4656c-f7a0-4319-98bb-84fb5e2e9b37");
assert_eq!(Value::from(m.clone()), Value::Reference(m));
}
#[test]
fn strings_keep_surrounding_whitespace() {
assert_eq!(
Value::parse_primitive(Primitive::String, " NL LoadArea ").unwrap(),
Value::Text(" NL LoadArea ".into())
);
}
#[test]
fn float_formatting_round_trips() {
for f in [
0.0,
-0.0,
1.0,
-67.2335,
1e-7,
1.5e300,
8.953211,
f64::MIN_POSITIVE,
f64::MAX,
f64::MIN,
1e15,
1e16,
1e-5,
1e-6,
] {
let s = format_float(f);
assert_eq!(
s.parse::<f64>().unwrap(),
if f == 0.0 { 0.0 } else { f },
"{f} rendered as {s}"
);
}
assert_eq!(format_float(-0.0), "0");
}
#[test]
fn extreme_floats_use_exponent_notation_rather_than_hundreds_of_digits() {
assert_eq!(format_float(1.5e300), "1.5E300");
assert_eq!(format_float(1e-9), "1E-9");
assert!(format_float(f64::MAX).len() < 24);
assert_eq!(format_float(-67.2335), "-67.2335");
assert_eq!(format_float(0.0001), "0.0001");
}
#[test]
fn non_finite_floats_use_the_xml_schema_lexical_forms() {
assert_eq!(format_float(f64::NAN), "NaN");
assert_eq!(format_float(f64::INFINITY), "INF");
assert_eq!(format_float(f64::NEG_INFINITY), "-INF");
for s in ["NaN", "INF", "-INF"] {
assert!(
Value::parse_primitive(Primitive::Float, s).is_ok(),
"{s} should parse"
);
}
}
}