1use crate::mrid::Mrid;
6use crate::object::Compound;
7use crate::schema::{EnumValueId, Primitive, Schema};
8use std::fmt;
9
10#[derive(Clone, PartialEq)]
17pub enum Value {
18 Boolean(bool),
19 Integer(i64),
20 Float(Real),
21 Text(Box<str>),
23 Enum(EnumValueId),
25 Reference(Mrid),
27 Compound(Box<Compound>),
31}
32
33#[derive(Clone)]
43pub struct Real(Repr);
44
45#[derive(Clone)]
48enum Repr {
49 Plain(f64),
51 Written(Box<(f64, Box<str>)>),
53}
54
55impl Real {
56 pub fn new(value: f64) -> Real {
58 Real(Repr::Plain(value))
59 }
60
61 pub fn from_document(value: f64, text: &str, prim: Primitive) -> Real {
67 if is_canonical_plain(value, text) || text == canonical(value, prim) {
68 return Real(Repr::Plain(value));
69 }
70 if !is_lexical(prim, text) {
71 return Real(Repr::Plain(value));
72 }
73 Real(Repr::Written(Box::new((value, text.into()))))
74 }
75
76 #[inline]
77 pub fn get(&self) -> f64 {
78 match &self.0 {
79 Repr::Plain(v) => *v,
80 Repr::Written(w) => w.0,
81 }
82 }
83
84 pub fn lexical(&self) -> Option<&str> {
86 match &self.0 {
87 Repr::Plain(_) => None,
88 Repr::Written(w) => Some(&w.1),
89 }
90 }
91
92 pub fn to_lexical_as(&self, prim: Primitive) -> String {
94 match &self.0 {
95 Repr::Plain(v) => canonical(*v, prim),
96 Repr::Written(w) if is_lexical(prim, &w.1) => w.1.to_string(),
100 Repr::Written(w) => canonical(w.0, prim),
101 }
102 }
103}
104
105impl PartialEq for Real {
108 fn eq(&self, other: &Real) -> bool {
109 self.get() == other.get()
110 }
111}
112
113impl fmt::Debug for Real {
114 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115 match self.lexical() {
116 Some(s) => write!(f, "{}({s})", self.get()),
117 None => write!(f, "{}", self.get()),
118 }
119 }
120}
121
122impl fmt::Display for Real {
123 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124 f.write_str(&self.to_lexical_as(Primitive::Float))
125 }
126}
127
128impl From<f64> for Real {
129 fn from(value: f64) -> Real {
130 Real::new(value)
131 }
132}
133
134fn is_canonical_plain(value: f64, text: &str) -> bool {
146 let abs = value.abs();
147 if abs != 0.0 && !(1e-5..1e16).contains(&abs) {
148 return false;
150 }
151 let body = match text.strip_prefix('-') {
152 Some(rest) => {
153 if value == 0.0 {
156 return false;
157 }
158 rest
159 }
160 None => {
161 if value < 0.0 {
162 return false;
163 }
164 text
165 }
166 };
167 let (int, frac) = match body.split_once('.') {
168 Some((i, f)) => (i, Some(f)),
169 None => (body, None),
170 };
171 let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
172 if !digits(int) || (int.len() > 1 && int.starts_with('0')) {
173 return false;
174 }
175 if let Some(f) = frac
176 && (!digits(f) || f.ends_with('0'))
177 {
178 return false;
179 }
180 int.len() + frac.map_or(0, str::len) <= 17
183}
184
185fn canonical(value: f64, prim: Primitive) -> String {
187 match prim {
188 Primitive::Decimal => plain_decimal(value),
189 _ => format_float(value),
190 }
191}
192
193fn is_lexical(prim: Primitive, s: &str) -> bool {
199 let exponent_allowed = match prim {
200 Primitive::Float => true,
201 Primitive::Decimal => false,
202 _ => return false,
203 };
204 if matches!(s, "INF" | "-INF" | "+INF" | "NaN") {
205 return exponent_allowed;
206 }
207 let (mantissa, exponent) = match s.find(['e', 'E']) {
208 Some(i) if exponent_allowed => (&s[..i], Some(&s[i + 1..])),
209 Some(_) => return false,
210 None => (s, None),
211 };
212 let digits_around_point = |t: &str| {
213 let t = t.strip_prefix(['+', '-']).unwrap_or(t);
214 let (int, frac) = t.split_once('.').unwrap_or((t, ""));
215 !(int.is_empty() && frac.is_empty())
216 && int.chars().all(|c| c.is_ascii_digit())
217 && frac.chars().all(|c| c.is_ascii_digit())
218 };
219 let integer = |t: &str| {
220 let t = t.strip_prefix(['+', '-']).unwrap_or(t);
221 !t.is_empty() && t.chars().all(|c| c.is_ascii_digit())
222 };
223 digits_around_point(mantissa) && exponent.is_none_or(integer)
224}
225
226impl Value {
227 pub fn as_bool(&self) -> Option<bool> {
228 match self {
229 Value::Boolean(b) => Some(*b),
230 _ => None,
231 }
232 }
233 pub fn as_i64(&self) -> Option<i64> {
234 match self {
235 Value::Integer(i) => Some(*i),
236 Value::Float(f) => Some(f.get() as i64),
237 _ => None,
238 }
239 }
240 pub fn as_f64(&self) -> Option<f64> {
241 match self {
242 Value::Float(f) => Some(f.get()),
243 Value::Integer(i) => Some(*i as f64),
244 _ => None,
245 }
246 }
247 pub fn as_str(&self) -> Option<&str> {
248 match self {
249 Value::Text(s) => Some(s),
250 _ => None,
251 }
252 }
253 pub fn as_enum(&self) -> Option<EnumValueId> {
254 match self {
255 Value::Enum(e) => Some(*e),
256 _ => None,
257 }
258 }
259 pub fn as_reference(&self) -> Option<&Mrid> {
260 match self {
261 Value::Reference(m) => Some(m),
262 _ => None,
263 }
264 }
265 pub fn as_compound(&self) -> Option<&Compound> {
266 match self {
267 Value::Compound(c) => Some(c),
268 _ => None,
269 }
270 }
271
272 pub fn to_lexical(&self) -> Option<String> {
277 Some(match self {
278 Value::Boolean(b) => if *b { "true" } else { "false" }.to_owned(),
279 Value::Integer(i) => i.to_string(),
280 Value::Float(f) => f.to_lexical_as(Primitive::Float),
281 Value::Text(s) => s.to_string(),
282 Value::Enum(_) | Value::Reference(_) | Value::Compound(_) => return None,
283 })
284 }
285
286 pub fn to_lexical_as(&self, prim: Primitive) -> Option<String> {
291 match self {
292 Value::Float(f) => Some(f.to_lexical_as(prim)),
293 _ => self.to_lexical(),
294 }
295 }
296
297 pub fn fits(&self, prim: Primitive) -> bool {
302 match prim {
303 Primitive::Boolean => matches!(self, Value::Boolean(_)),
304 Primitive::Integer => matches!(self, Value::Integer(_)),
305 Primitive::Float | Primitive::Decimal => {
306 matches!(self, Value::Float(_) | Value::Integer(_))
307 }
308 Primitive::String
309 | Primitive::Date
310 | Primitive::DateTime
311 | Primitive::MonthDay
312 | Primitive::Time
313 | Primitive::Duration
314 | Primitive::Uri => matches!(self, Value::Text(_)),
315 }
316 }
317
318 pub fn shape(&self) -> &'static str {
320 match self {
321 Value::Boolean(_) => "a boolean",
322 Value::Integer(_) => "an integer",
323 Value::Float(_) => "a float",
324 Value::Text(_) => "text",
325 Value::Enum(_) => "an enumeration literal",
326 Value::Reference(_) => "a reference",
327 Value::Compound(_) => "a compound",
328 }
329 }
330
331 pub fn parse_primitive(prim: Primitive, text: &str) -> Result<Value, ParseValueError> {
333 let t = text.trim();
334 Ok(match prim {
335 Primitive::Boolean => match t {
336 "true" | "1" => Value::Boolean(true),
337 "false" | "0" => Value::Boolean(false),
338 _ => return Err(ParseValueError::new(prim, text)),
339 },
340 Primitive::Integer => Value::Integer(
341 t.parse::<i64>()
342 .or_else(|_| t.parse::<f64>().map(|f| f as i64))
344 .map_err(|_| ParseValueError::new(prim, text))?,
345 ),
346 Primitive::Float | Primitive::Decimal => {
347 let f = parse_float(t).ok_or_else(|| ParseValueError::new(prim, text))?;
348 Value::Float(Real::from_document(f, t, prim))
349 }
350 Primitive::String
351 | Primitive::Date
352 | Primitive::DateTime
353 | Primitive::MonthDay
354 | Primitive::Time
355 | Primitive::Duration
356 | Primitive::Uri => Value::Text(text.into()),
357 })
358 }
359}
360
361impl From<bool> for Value {
365 fn from(b: bool) -> Value {
366 Value::Boolean(b)
367 }
368}
369impl From<i64> for Value {
370 fn from(i: i64) -> Value {
371 Value::Integer(i)
372 }
373}
374impl From<f64> for Value {
375 fn from(f: f64) -> Value {
376 Value::Float(Real::new(f))
377 }
378}
379
380impl From<Real> for Value {
381 fn from(r: Real) -> Value {
382 Value::Float(r)
383 }
384}
385impl From<&str> for Value {
386 fn from(s: &str) -> Value {
387 Value::Text(s.into())
388 }
389}
390impl From<String> for Value {
391 fn from(s: String) -> Value {
392 Value::Text(s.into_boxed_str())
393 }
394}
395impl From<EnumValueId> for Value {
396 fn from(e: EnumValueId) -> Value {
397 Value::Enum(e)
398 }
399}
400impl From<Mrid> for Value {
401 fn from(m: Mrid) -> Value {
402 Value::Reference(m)
403 }
404}
405impl From<Compound> for Value {
406 fn from(c: Compound) -> Value {
407 Value::Compound(Box::new(c))
408 }
409}
410
411fn parse_float(t: &str) -> Option<f64> {
418 if let Ok(f) = t.parse::<f64>() {
419 return Some(f);
420 }
421 let normalized = t.replace(['D', 'd'], "E");
422 if let Ok(f) = normalized.parse::<f64>() {
423 return Some(f);
424 }
425 let (_, tail) = normalized.split_once(',')?;
426 let unambiguous = !normalized.contains('.')
427 && !tail.contains(',')
428 && tail.chars().take_while(char::is_ascii_digit).count() != 3;
429 unambiguous
430 .then(|| normalized.replace(',', ".").parse::<f64>().ok())
431 .flatten()
432}
433
434fn format_float(f: f64) -> String {
442 if f.is_nan() {
443 return "NaN".to_owned();
444 }
445 if f.is_infinite() {
446 return if f > 0.0 { "INF" } else { "-INF" }.to_owned();
447 }
448 let abs = f.abs();
449 if abs != 0.0 && !(1e-5..1e16).contains(&abs) {
451 return format!("{f:E}");
452 }
453 plain_decimal(f)
454}
455
456fn plain_decimal(f: f64) -> String {
461 if !f.is_finite() {
462 return format_float(f);
465 }
466 let s = f.to_string();
467 if s == "-0" { "0".to_owned() } else { s }
468}
469
470#[derive(Debug, Clone, PartialEq, Eq)]
471pub struct ParseValueError {
472 pub expected: Primitive,
473 pub text: String,
474}
475
476impl ParseValueError {
477 fn new(expected: Primitive, text: &str) -> Self {
478 ParseValueError {
479 expected,
480 text: text.chars().take(64).collect(),
482 }
483 }
484}
485
486impl fmt::Display for ParseValueError {
487 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
488 write!(f, "cannot parse {:?} from {:?}", self.expected, self.text)
489 }
490}
491
492impl std::error::Error for ParseValueError {}
493
494impl fmt::Debug for Value {
495 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
496 match self {
497 Value::Boolean(b) => write!(f, "{b}"),
498 Value::Integer(i) => write!(f, "{i}"),
499 Value::Float(x) => write!(f, "{x}"),
500 Value::Text(s) => write!(f, "{s:?}"),
501 Value::Enum(e) => write!(f, "enum#{}", e.0),
502 Value::Reference(m) => write!(f, "->{m}"),
503 Value::Compound(c) => write!(f, "{{{} fields}}", c.len()),
504 }
505 }
506}
507
508pub fn display_value(schema: &Schema, v: &Value) -> String {
510 match v {
511 Value::Enum(e) => schema.enum_value(*e).name.to_owned(),
512 Value::Reference(m) => m.canonical(),
513 Value::Compound(c) => {
514 let fields: Vec<String> = c
515 .values()
516 .iter()
517 .map(|(a, v)| format!("{}={}", schema.attr(*a).label, display_value(schema, v)))
518 .collect();
519 format!("{{{}}}", fields.join(", "))
520 }
521 other => other.to_lexical().unwrap_or_default(),
522 }
523}
524
525#[cfg(test)]
526mod tests {
527 use super::*;
528
529 #[test]
533 fn a_documents_spelling_of_a_number_survives_a_round_trip() {
534 for (text, prim) in [
535 ("2.62637E-05", Primitive::Float),
536 ("0e+000", Primitive::Float),
537 ("250.000000", Primitive::Float),
538 ("-330.750000", Primitive::Float),
539 ("6.8E-08", Primitive::Float),
540 ("1.0", Primitive::Float),
541 ("250.000000", Primitive::Decimal),
542 ] {
543 let v = Value::parse_primitive(prim, text).unwrap();
544 assert_eq!(
545 v.to_lexical_as(prim).as_deref(),
546 Some(text),
547 "{text:?} as {prim:?}"
548 );
549 }
550 }
551
552 #[test]
556 fn spelling_is_not_part_of_the_value() {
557 let written = Value::parse_primitive(Primitive::Float, "250.000000").unwrap();
558 let plain = Value::from(250.0);
559 assert_eq!(written, plain);
560 assert_eq!(written.as_f64(), Some(250.0));
561 }
562
563 #[test]
566 fn a_spelling_is_only_kept_when_it_is_a_conforming_lexical_form() {
567 let v = Value::parse_primitive(Primitive::Float, "1,5").unwrap();
570 assert_eq!(v.as_f64(), Some(1.5));
571 assert_eq!(v.to_lexical().as_deref(), Some("1.5"));
572 let v = Value::parse_primitive(Primitive::Float, "1.5D+3").unwrap();
575 assert_eq!(v.to_lexical().as_deref(), Some("1500"));
576 let v = Value::parse_primitive(Primitive::Float, "6.8E-08").unwrap();
579 assert_eq!(
580 v.to_lexical_as(Primitive::Decimal).as_deref(),
581 Some("0.000000068")
582 );
583 }
584
585 #[test]
587 fn the_shape_test_never_disagrees_with_formatting() {
588 let texts = [
589 "0",
590 "1",
591 "-1",
592 "250",
593 "2.2",
594 "-330.75",
595 "0.0000262637",
596 "1e5",
597 "1E5",
598 "0e+000",
599 "250.000000",
600 "-0",
601 "007",
602 "1.0",
603 "0.10",
604 "+1",
605 "1.5D+3",
606 "1,5",
607 "12345678901234567",
608 "0.30000000000000004",
609 "1.7976931348623157E308",
610 "5E-324",
611 "-2.62637E-05",
612 ];
613 for text in texts {
614 let Some(v) = parse_float(text) else { continue };
615 for prim in [Primitive::Float, Primitive::Decimal] {
616 if is_canonical_plain(v, text) {
617 assert_eq!(
618 text,
619 canonical(v, prim),
620 "{text:?} claimed canonical for {prim:?}"
621 );
622 }
623 }
624 }
625 }
626
627 #[test]
628 fn parses_the_primitive_forms_used_in_exchange_files() {
629 assert_eq!(
630 Value::parse_primitive(Primitive::Boolean, "true").unwrap(),
631 Value::Boolean(true)
632 );
633 assert_eq!(
634 Value::parse_primitive(Primitive::Boolean, " false ").unwrap(),
635 Value::Boolean(false)
636 );
637 assert_eq!(
638 Value::parse_primitive(Primitive::Integer, "42").unwrap(),
639 Value::Integer(42)
640 );
641 assert_eq!(
642 Value::parse_primitive(Primitive::Float, "-67.2335").unwrap(),
643 Value::from(-67.2335)
644 );
645 assert_eq!(
646 Value::parse_primitive(Primitive::Float, "1.5E3").unwrap(),
647 Value::from(1500.0)
648 );
649 }
650
651 #[test]
652 fn tolerates_non_conforming_numeric_forms() {
653 assert_eq!(
654 Value::parse_primitive(Primitive::Float, "1.5D+3").unwrap(),
655 Value::from(1500.0)
656 );
657 assert_eq!(
659 Value::parse_primitive(Primitive::Integer, "7.0").unwrap(),
660 Value::Integer(7)
661 );
662 }
663
664 #[test]
665 fn rejects_unparseable_values() {
666 assert!(Value::parse_primitive(Primitive::Boolean, "yes").is_err());
667 assert!(Value::parse_primitive(Primitive::Float, "abc").is_err());
668 }
669
670 #[test]
673 fn a_comma_is_only_read_as_a_decimal_mark_where_it_cannot_be_a_thousands_separator() {
674 let f = |s: &str| Value::parse_primitive(Primitive::Float, s);
675 assert_eq!(f("-67,2335").unwrap(), Value::from(-67.2335));
677 assert_eq!(f("1,5").unwrap(), Value::from(1.5));
678 assert_eq!(f("1,5E3").unwrap(), Value::from(1500.0));
679 assert!(f("1,234").is_err(), "1,234 is ambiguous");
681 assert!(f("1,000").is_err(), "1,000 is ambiguous");
682 assert!(f("1,234.5").is_err());
684 assert!(f("1,234,567").is_err());
685 }
686
687 #[test]
688 fn ordinary_rust_values_convert_to_the_right_variant() {
689 assert_eq!(Value::from(true), Value::Boolean(true));
690 assert_eq!(Value::from(7i64), Value::Integer(7));
691 assert_eq!(Value::from(2.2f64), Value::from(2.2));
692 assert_eq!(Value::from("BE-Line_1"), Value::Text("BE-Line_1".into()));
693 assert_eq!(
694 Value::from(String::from("owned")),
695 Value::Text("owned".into())
696 );
697 let m = Mrid::parse("70c4656c-f7a0-4319-98bb-84fb5e2e9b37");
698 assert_eq!(Value::from(m.clone()), Value::Reference(m));
699 }
700
701 #[test]
702 fn strings_keep_surrounding_whitespace() {
703 assert_eq!(
706 Value::parse_primitive(Primitive::String, " NL LoadArea ").unwrap(),
707 Value::Text(" NL LoadArea ".into())
708 );
709 }
710
711 #[test]
712 fn float_formatting_round_trips() {
713 for f in [
714 0.0,
715 -0.0,
716 1.0,
717 -67.2335,
718 1e-7,
719 1.5e300,
720 8.953211,
721 f64::MIN_POSITIVE,
722 f64::MAX,
723 f64::MIN,
724 1e15,
725 1e16,
726 1e-5,
727 1e-6,
728 ] {
729 let s = format_float(f);
730 assert_eq!(
731 s.parse::<f64>().unwrap(),
732 if f == 0.0 { 0.0 } else { f },
733 "{f} rendered as {s}"
734 );
735 }
736 assert_eq!(format_float(-0.0), "0");
737 }
738
739 #[test]
740 fn extreme_floats_use_exponent_notation_rather_than_hundreds_of_digits() {
741 assert_eq!(format_float(1.5e300), "1.5E300");
743 assert_eq!(format_float(1e-9), "1E-9");
744 assert!(format_float(f64::MAX).len() < 24);
745 assert_eq!(format_float(-67.2335), "-67.2335");
747 assert_eq!(format_float(0.0001), "0.0001");
748 }
749
750 #[test]
751 fn non_finite_floats_use_the_xml_schema_lexical_forms() {
752 assert_eq!(format_float(f64::NAN), "NaN");
753 assert_eq!(format_float(f64::INFINITY), "INF");
754 assert_eq!(format_float(f64::NEG_INFINITY), "-INF");
755 for s in ["NaN", "INF", "-INF"] {
757 assert!(
758 Value::parse_primitive(Primitive::Float, s).is_ok(),
759 "{s} should parse"
760 );
761 }
762 }
763}