Skip to main content

cim_kit/
value.rs

1//! Attribute values.
2//!
3//! [`Mrid`]: crate::mrid::Mrid
4
5use crate::mrid::Mrid;
6use crate::object::Compound;
7use crate::schema::{EnumValueId, Primitive, Schema};
8use std::fmt;
9
10/// The value of a single attribute occurrence.
11///
12/// CIM datatypes (`Resistance`, `ActivePower`, ...) serialize as their underlying
13/// primitive, so they are represented by [`Value::Float`] and friends; the unit and
14/// multiplier are schema constants recoverable from the attribute's
15/// [`DatatypeDef`](crate::schema::DatatypeDef).
16#[derive(Clone, PartialEq)]
17pub enum Value {
18    Boolean(bool),
19    Integer(i64),
20    Float(Real),
21    /// Strings, dates, times and durations; CIM keeps these in their lexical form.
22    Text(Box<str>),
23    /// An enumeration literal.
24    Enum(EnumValueId),
25    /// A reference to another object, by mRID.
26    Reference(Mrid),
27    /// An inline structured value with no identity of its own.
28    ///
29    /// Boxed: compounds are rare, and inline they would triple every value's size.
30    Compound(Box<Compound>),
31}
32
33/// A CIM `Float` or `Decimal` value: the number, and the spelling it arrived in.
34///
35/// Like [`Mrid`], two `Real`s denoting one number are **equal whatever they were written
36/// as**, so a difference never reports a reformatting, while re-export reproduces the
37/// spelling (`2.62637E-05`, `250.000000`, `-90E6`).
38///
39/// A spelling is kept **only when it is a conforming lexical form for the primitive it was
40/// read as**; tolerated deviations such as `1,5` or `1.5D+3`
41/// ([`Value::parse_primitive`]) are written back in canonical form.
42#[derive(Clone)]
43pub struct Real(Repr);
44
45/// Two shapes rather than `f64` plus `Option<Box<str>>`, keeping `Value` at 24 bytes;
46/// only the rare value with a non-canonical spelling allocates.
47#[derive(Clone)]
48enum Repr {
49    /// Renders canonically.
50    Plain(f64),
51    /// The number, and the spelling a document wrote it with.
52    Written(Box<(f64, Box<str>)>),
53}
54
55impl Real {
56    /// A number with no particular spelling: it renders canonically.
57    pub fn new(value: f64) -> Real {
58        Real(Repr::Plain(value))
59    }
60
61    /// A number as a document wrote it.
62    ///
63    /// The text is kept only when it differs from what this crate would write anyway and
64    /// is a conforming lexical form for `prim` — so a value that was already canonical
65    /// costs nothing, and a deviating one is repaired rather than echoed.
66    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    /// The spelling this value was read with, where it differs from the canonical form.
85    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    /// How to write it: the document's spelling where there is one, else canonical.
93    pub fn to_lexical_as(&self, prim: Primitive) -> String {
94        match &self.0 {
95            Repr::Plain(v) => canonical(*v, prim),
96            // A spelling read as one primitive can be wrong for another: `0e+000` is a
97            // valid `xsd:float` and not a valid `xsd:decimal`, and the RDF writer types a
98            // literal from the profile rather than from how it was read.
99            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
105/// Equality is the number, not the spelling: `1.0` read from a file equals `1` computed in
106/// memory. It is `f64` equality, so `NaN` equals nothing, itself included.
107impl 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
134/// Whether `text` is already exactly what [`canonical`] would render, decided without
135/// rendering it.
136///
137/// Avoids formatting every float on read (hot path). Conservative: `false` means "format
138/// it and compare", which costs an allocation but is never wrong.
139///
140/// The reasoning: Rust's `Display` for `f64` is the shortest decimal that round-trips, and
141/// [`format_float`] uses it inside `1e-5..1e16`. A text in that range which has no leading
142/// zero, no trailing fraction zero, no sign but `-`, no exponent and at most 17 significant
143/// digits and which parsed to `value` *is* that shortest form: any shorter decimal would
144/// round-trip to a different `f64`, and 17 digits always suffice to name one.
145fn is_canonical_plain(value: f64, text: &str) -> bool {
146    let abs = value.abs();
147    if abs != 0.0 && !(1e-5..1e16).contains(&abs) {
148        // `format_float` writes these in exponent form; let the exact comparison decide.
149        return false;
150    }
151    let body = match text.strip_prefix('-') {
152        Some(rest) => {
153            // `-0` renders as `0`, and `-0.0` is not reachable here for another reason:
154            // it would have to have a trailing zero.
155            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    // Enough digits to name any `f64` uniquely; beyond that a longer text can still parse
181    // to a value with a shorter rendering, so it is not decidable here.
182    int.len() + frac.map_or(0, str::len) <= 17
183}
184
185/// The form this crate writes for `value` when nothing better is known.
186fn canonical(value: f64, prim: Primitive) -> String {
187    match prim {
188        Primitive::Decimal => plain_decimal(value),
189        _ => format_float(value),
190    }
191}
192
193/// Whether `s` is a lexical form of `prim` that a conforming consumer will accept.
194///
195/// Only the two numeric primitives are asked about, because they are the only ones whose
196/// stored value is not the text itself. The grammars are XML Schema's, and the difference
197/// between them is the one that matters here: `xsd:decimal` has no exponent.
198fn 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    /// Render in the lexical form CIM/XML uses for element text.
273    ///
274    /// Only meaningful for values serialized as text; enumerations, references and
275    /// compounds have their own serializations and return `None`.
276    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    /// Render in the lexical form `prim` permits.
287    ///
288    /// `xsd:decimal` has **no exponent notation**, so a `Decimal` is written out in full;
289    /// a `Float` uses exponent form where plain decimal would be long.
290    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    /// Whether this value can serve an attribute declared as `prim`.
298    ///
299    /// Shared by [`validate`](mod@crate::validate) and the RDF writer. An integer serves a
300    /// float or decimal, and text serves dates, times and durations (kept lexically).
301    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    /// A one-word description of what this value is, for diagnostics.
319    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    /// Parse element text according to the attribute's primitive type.
332    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                    // A few exporters write integral values with a decimal point.
343                    .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
361// Conversions for building models (`obj.set(attr, 2.2.into())`). Deliberately no
362// `From<i32>` or `From<f32>`: CIM's `Integer` is `i64` and `Float` is `f64`.
363
364impl 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
411/// Parse a float, accepting the forms that appear in published exchange files.
412///
413/// A Fortran-style exponent (`1.5D+3`) is accepted. A comma decimal mark is accepted only
414/// where it cannot be a thousands separator: one comma, no point, and not exactly three
415/// digits after it (`1,234` is refused as
416/// [`Rule::InvalidValue`](crate::Rule::InvalidValue)).
417fn 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
434/// Format a float in the shortest form that round-trips exactly.
435///
436/// `NaN`, `INF` and `-INF` are the lexical forms XML Schema defines for the floating-point
437/// types, which is what CIM `Float` becomes in RDF — see [`Primitive::xsd_datatype`].
438///
439/// Rust's `Display` never uses exponent notation (`1.5e300` would be 301 digits), so
440/// values outside the compact range use `LowerExp`, which is also shortest-round-trip.
441fn 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    // The bounds are where `{}` stops being the shorter rendering of the two.
450    if abs != 0.0 && !(1e-5..1e16).contains(&abs) {
451        return format!("{f:E}");
452    }
453    plain_decimal(f)
454}
455
456/// Format a float without an exponent, which is all `xsd:decimal` allows.
457///
458/// Rust's `Display` for `f64` never uses exponent notation, so it is already the plain
459/// form; only the two spellings of zero need normalizing.
460fn plain_decimal(f: f64) -> String {
461    if !f.is_finite() {
462        // Neither `NaN` nor `INF` is in the decimal lexical space, but losing the value
463        // would be worse than writing what it is.
464        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            // Keep diagnostics bounded even if a file contains a huge text node.
481            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
508/// Human-readable rendering that resolves enumeration literals through `schema`.
509pub 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    /// A number's spelling is information: the published corpus writes `2.62637E-05` and
530    /// `250.000000`, and re-exporting those as `0.0000262637` and `250` changes 8,623
531    /// values in a model set that is supposed to come back as it went in.
532    #[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    /// Spelling is not value. Two models that differ only in how a producer formatted a
553    /// number are the same model — otherwise every difference report would fill with
554    /// changes nobody made.
555    #[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    /// The reader accepts forms that published files deviate with; the writer must not
564    /// hand them on, because output this crate promises is valid has to be valid.
565    #[test]
566    fn a_spelling_is_only_kept_when_it_is_a_conforming_lexical_form() {
567        // A comma decimal mark parses (where it is unambiguous) and is repaired on the
568        // way out, not echoed.
569        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        // A Fortran exponent, likewise — and 1500 is inside the range this crate writes
573        // plainly, so the canonical form is not an exponent at all.
574        let v = Value::parse_primitive(Primitive::Float, "1.5D+3").unwrap();
575        assert_eq!(v.to_lexical().as_deref(), Some("1500"));
576        // `xsd:decimal` has no exponent notation, so a float spelling that uses one is not
577        // reused when the profile types the attribute as a decimal.
578        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    /// The fast path may only ever answer "canonical" where the exact comparison would.
586    #[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        // Integral value written with a decimal point.
658        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    /// A comma is a decimal mark to one producer and a thousands separator to another, and
671    /// the two readings differ by a factor of a thousand. Guessing is worse than refusing.
672    #[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        // Not three digits after the comma: no locale writes a thousands group that way.
676        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        // Exactly three: `1,234` is 1.234 or 1234 and nothing in the document says which.
680        assert!(f("1,234").is_err(), "1,234 is ambiguous");
681        assert!(f("1,000").is_err(), "1,000 is ambiguous");
682        // Both marks, or two commas: a grouped number, which CIM/XML never writes.
683        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        // Names may legitimately contain leading/trailing spaces; only numeric and
704        // boolean parsing trims.
705        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        // `f64::to_string` never uses an exponent, so it renders 1.5e300 as 301 digits.
742        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        // The ordinary range keeps its plain decimal form.
746        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        // And they read back.
756        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}