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 because compounds are rare — four types in all of CGMES 3.0 — and a
30 /// `Compound` inline would triple the size of every value in the model.
31 Compound(Box<Compound>),
32}
33
34/// A CIM `Float` or `Decimal` value: the number, and the spelling it arrived in.
35///
36/// The number is the value; the spelling is how one document happened to write it. They
37/// are kept apart for the same reason [`Mrid`] keeps a UUID apart from its spelling, and
38/// the consequences are the same shape: two `Real`s that denote one number are **equal
39/// whatever they were written as**, so a difference between two model states never reports
40/// a change that is only a reformatting — while a re-export still reproduces the document
41/// it read.
42///
43/// It matters because published models are full of forms no formatter would choose. The
44/// CGMES 3.0 conformity corpus writes `2.62637E-05`, `0e+000` and `250.000000`; rendering
45/// those as `0.0000262637`, `0` and `250` re-exports a numerically identical model as a
46/// textually different file, which is what a receiving system diffs. ENTSO-E's RDF-Syntax
47/// User Guide is explicit that engineering notation is chosen deliberately — from CIM18
48/// active power travels as `-90E6` rather than as `-90000000` precisely to carry the
49/// producer's precision — so a number's spelling is information, not noise.
50///
51/// A spelling is kept **only when it is a conforming lexical form for the primitive it was
52/// read as**. The reader accepts `1,5` and `1.5D+3` from files that deviate
53/// ([`Value::parse_primitive`]), and reproducing those would propagate a defect into
54/// output this crate promises is valid; those are repaired to the canonical form, which is
55/// the same stance the header takes on a malformed `urn:uuid:`.
56#[derive(Clone)]
57pub struct Real(Repr);
58
59/// Two shapes rather than a number beside an `Option<Box<str>>`, and the reason is
60/// [`Value`]'s size.
61///
62/// An optional string inline makes `Real` 24 bytes, which makes `Value` 32 and every slot
63/// in the model 8 bytes larger — a measured ~10% on read for a spelling 98.5% of values do
64/// not have. Boxing the rare case keeps `Real` pointer-sized, so `Value` stays 24 bytes and
65/// the common value costs exactly what it did before: a `f64`. The published CGMES 3.0
66/// corpus allocates 8,623 times for its 951,340 values.
67#[derive(Clone)]
68enum Repr {
69 /// Renders canonically.
70 Plain(f64),
71 /// The number, and the spelling a document wrote it with.
72 Written(Box<(f64, Box<str>)>),
73}
74
75impl Real {
76 /// A number with no particular spelling: it renders canonically.
77 pub fn new(value: f64) -> Real {
78 Real(Repr::Plain(value))
79 }
80
81 /// A number as a document wrote it.
82 ///
83 /// The text is kept only when it differs from what this crate would write anyway and
84 /// is a conforming lexical form for `prim` — so a value that was already canonical
85 /// costs nothing, and a deviating one is repaired rather than echoed.
86 pub fn from_document(value: f64, text: &str, prim: Primitive) -> Real {
87 if is_canonical_plain(value, text) || text == canonical(value, prim) {
88 return Real(Repr::Plain(value));
89 }
90 if !is_lexical(prim, text) {
91 return Real(Repr::Plain(value));
92 }
93 Real(Repr::Written(Box::new((value, text.into()))))
94 }
95
96 #[inline]
97 pub fn get(&self) -> f64 {
98 match &self.0 {
99 Repr::Plain(v) => *v,
100 Repr::Written(w) => w.0,
101 }
102 }
103
104 /// The spelling this value was read with, where it differs from the canonical form.
105 pub fn lexical(&self) -> Option<&str> {
106 match &self.0 {
107 Repr::Plain(_) => None,
108 Repr::Written(w) => Some(&w.1),
109 }
110 }
111
112 /// How to write it: the document's spelling where there is one, else canonical.
113 pub fn to_lexical_as(&self, prim: Primitive) -> String {
114 match &self.0 {
115 Repr::Plain(v) => canonical(*v, prim),
116 // A spelling read as one primitive can be wrong for another: `0e+000` is a
117 // valid `xsd:float` and not a valid `xsd:decimal`, and the RDF writer types a
118 // literal from the profile rather than from how it was read.
119 Repr::Written(w) if is_lexical(prim, &w.1) => w.1.to_string(),
120 Repr::Written(w) => canonical(w.0, prim),
121 }
122 }
123}
124
125/// Equality is the number. The spelling is not part of the value, so `1.0` read from one
126/// file equals `1` computed in memory — which is what keeps [`crate::diff`] from reporting
127/// a change where a producer only changed its formatter.
128///
129/// It is `f64` equality, so `NaN` equals nothing, itself included. CIM has no use for one
130/// and no published model contains one, but a difference computed over a model that does
131/// will report that value as changed on every run.
132impl PartialEq for Real {
133 fn eq(&self, other: &Real) -> bool {
134 self.get() == other.get()
135 }
136}
137
138impl fmt::Debug for Real {
139 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
140 match self.lexical() {
141 Some(s) => write!(f, "{}({s})", self.get()),
142 None => write!(f, "{}", self.get()),
143 }
144 }
145}
146
147impl fmt::Display for Real {
148 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
149 f.write_str(&self.to_lexical_as(Primitive::Float))
150 }
151}
152
153impl From<f64> for Real {
154 fn from(value: f64) -> Real {
155 Real::new(value)
156 }
157}
158
159/// Whether `text` is already exactly what [`canonical`] would render, decided without
160/// rendering it.
161///
162/// The comparison it replaces formats a `f64` into a fresh `String` for **every** float in
163/// the document, which measured 6% of the time to read a 112 MiB model — paid on 100% of
164/// values to learn something about 1.5% of them. This is the same question answered by one
165/// pass over the bytes.
166///
167/// It is deliberately conservative: `false` means "format it and see", so a shape this does
168/// not recognise costs the old comparison and never a wrong answer. The two ways to be
169/// wrong are both safe — claiming canonical when it is not re-exports the canonical form,
170/// which is what the census over the published corpus would catch, and claiming
171/// non-canonical when it is costs one allocation and writes identical text.
172///
173/// The reasoning: Rust's `Display` for `f64` is the shortest decimal that round-trips, and
174/// [`format_float`] uses it inside `1e-5..1e16`. A text in that range which has no leading
175/// zero, no trailing fraction zero, no sign but `-`, no exponent and at most 17 significant
176/// digits and which parsed to `value` *is* that shortest form: any shorter decimal would
177/// round-trip to a different `f64`, and 17 digits always suffice to name one.
178fn is_canonical_plain(value: f64, text: &str) -> bool {
179 let abs = value.abs();
180 if abs != 0.0 && !(1e-5..1e16).contains(&abs) {
181 // `format_float` writes these in exponent form; let the exact comparison decide.
182 return false;
183 }
184 let body = match text.strip_prefix('-') {
185 Some(rest) => {
186 // `-0` renders as `0`, and `-0.0` is not reachable here for another reason:
187 // it would have to have a trailing zero.
188 if value == 0.0 {
189 return false;
190 }
191 rest
192 }
193 None => {
194 if value < 0.0 {
195 return false;
196 }
197 text
198 }
199 };
200 let (int, frac) = match body.split_once('.') {
201 Some((i, f)) => (i, Some(f)),
202 None => (body, None),
203 };
204 let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
205 if !digits(int) || (int.len() > 1 && int.starts_with('0')) {
206 return false;
207 }
208 if let Some(f) = frac
209 && (!digits(f) || f.ends_with('0'))
210 {
211 return false;
212 }
213 // Enough digits to name any `f64` uniquely; beyond that a longer text can still parse
214 // to a value with a shorter rendering, so it is not decidable here.
215 int.len() + frac.map_or(0, str::len) <= 17
216}
217
218/// The form this crate writes for `value` when nothing better is known.
219fn canonical(value: f64, prim: Primitive) -> String {
220 match prim {
221 Primitive::Decimal => plain_decimal(value),
222 _ => format_float(value),
223 }
224}
225
226/// Whether `s` is a lexical form of `prim` that a conforming consumer will accept.
227///
228/// Only the two numeric primitives are asked about, because they are the only ones whose
229/// stored value is not the text itself. The grammars are XML Schema's, and the difference
230/// between them is the one that matters here: `xsd:decimal` has no exponent.
231fn is_lexical(prim: Primitive, s: &str) -> bool {
232 let exponent_allowed = match prim {
233 Primitive::Float => true,
234 Primitive::Decimal => false,
235 _ => return false,
236 };
237 if matches!(s, "INF" | "-INF" | "+INF" | "NaN") {
238 return exponent_allowed;
239 }
240 let (mantissa, exponent) = match s.find(['e', 'E']) {
241 Some(i) if exponent_allowed => (&s[..i], Some(&s[i + 1..])),
242 Some(_) => return false,
243 None => (s, None),
244 };
245 let digits_around_point = |t: &str| {
246 let t = t.strip_prefix(['+', '-']).unwrap_or(t);
247 let (int, frac) = t.split_once('.').unwrap_or((t, ""));
248 !(int.is_empty() && frac.is_empty())
249 && int.chars().all(|c| c.is_ascii_digit())
250 && frac.chars().all(|c| c.is_ascii_digit())
251 };
252 let integer = |t: &str| {
253 let t = t.strip_prefix(['+', '-']).unwrap_or(t);
254 !t.is_empty() && t.chars().all(|c| c.is_ascii_digit())
255 };
256 digits_around_point(mantissa) && exponent.is_none_or(integer)
257}
258
259impl Value {
260 pub fn as_bool(&self) -> Option<bool> {
261 match self {
262 Value::Boolean(b) => Some(*b),
263 _ => None,
264 }
265 }
266 pub fn as_i64(&self) -> Option<i64> {
267 match self {
268 Value::Integer(i) => Some(*i),
269 Value::Float(f) => Some(f.get() as i64),
270 _ => None,
271 }
272 }
273 pub fn as_f64(&self) -> Option<f64> {
274 match self {
275 Value::Float(f) => Some(f.get()),
276 Value::Integer(i) => Some(*i as f64),
277 _ => None,
278 }
279 }
280 pub fn as_str(&self) -> Option<&str> {
281 match self {
282 Value::Text(s) => Some(s),
283 _ => None,
284 }
285 }
286 pub fn as_enum(&self) -> Option<EnumValueId> {
287 match self {
288 Value::Enum(e) => Some(*e),
289 _ => None,
290 }
291 }
292 pub fn as_reference(&self) -> Option<&Mrid> {
293 match self {
294 Value::Reference(m) => Some(m),
295 _ => None,
296 }
297 }
298 pub fn as_compound(&self) -> Option<&Compound> {
299 match self {
300 Value::Compound(c) => Some(c),
301 _ => None,
302 }
303 }
304
305 /// Render in the lexical form CIM/XML uses for element text.
306 ///
307 /// Only meaningful for values serialized as text; enumerations, references and
308 /// compounds have their own serializations and return `None`.
309 pub fn to_lexical(&self) -> Option<String> {
310 Some(match self {
311 Value::Boolean(b) => if *b { "true" } else { "false" }.to_owned(),
312 Value::Integer(i) => i.to_string(),
313 Value::Float(f) => f.to_lexical_as(Primitive::Float),
314 Value::Text(s) => s.to_string(),
315 Value::Enum(_) | Value::Reference(_) | Value::Compound(_) => return None,
316 })
317 }
318
319 /// Render in the lexical form `prim` permits.
320 ///
321 /// Only one primitive is fussier than [`Value::to_lexical`]: `xsd:decimal`'s lexical
322 /// space has **no exponent notation**, while `xsd:float`'s does and needs it — Rust's
323 /// plain float formatting would otherwise render `1.5e300` as 301 digits. Decimals are
324 /// therefore always written out in full, which is bounded in practice because the
325 /// values CIM types as `Decimal` are money and per-unit quantities.
326 pub fn to_lexical_as(&self, prim: Primitive) -> Option<String> {
327 match self {
328 Value::Float(f) => Some(f.to_lexical_as(prim)),
329 _ => self.to_lexical(),
330 }
331 }
332
333 /// Whether this value can serve an attribute declared as `prim`.
334 ///
335 /// The single definition of that question, shared by
336 /// [`validate`](mod@crate::validate) — which reports a mismatch — and by the RDF writer,
337 /// which has to decide whether to label the literal with the declared type or with
338 /// the one the value actually has.
339 ///
340 /// Two allowances are deliberate. An integer serves a float or decimal, because
341 /// `1` is a perfectly good float and CIM/XML gives no way to say otherwise. And dates,
342 /// times and durations are kept in their lexical form by design, so text serves them.
343 pub fn fits(&self, prim: Primitive) -> bool {
344 match prim {
345 Primitive::Boolean => matches!(self, Value::Boolean(_)),
346 Primitive::Integer => matches!(self, Value::Integer(_)),
347 Primitive::Float | Primitive::Decimal => {
348 matches!(self, Value::Float(_) | Value::Integer(_))
349 }
350 Primitive::String
351 | Primitive::Date
352 | Primitive::DateTime
353 | Primitive::MonthDay
354 | Primitive::Time
355 | Primitive::Duration
356 | Primitive::Uri => matches!(self, Value::Text(_)),
357 }
358 }
359
360 /// A one-word description of what this value is, for diagnostics.
361 pub fn shape(&self) -> &'static str {
362 match self {
363 Value::Boolean(_) => "a boolean",
364 Value::Integer(_) => "an integer",
365 Value::Float(_) => "a float",
366 Value::Text(_) => "text",
367 Value::Enum(_) => "an enumeration literal",
368 Value::Reference(_) => "a reference",
369 Value::Compound(_) => "a compound",
370 }
371 }
372
373 /// Parse element text according to the attribute's primitive type.
374 pub fn parse_primitive(prim: Primitive, text: &str) -> Result<Value, ParseValueError> {
375 let t = text.trim();
376 Ok(match prim {
377 Primitive::Boolean => match t {
378 "true" | "1" => Value::Boolean(true),
379 "false" | "0" => Value::Boolean(false),
380 _ => return Err(ParseValueError::new(prim, text)),
381 },
382 Primitive::Integer => Value::Integer(
383 t.parse::<i64>()
384 // A few exporters write integral values with a decimal point.
385 .or_else(|_| t.parse::<f64>().map(|f| f as i64))
386 .map_err(|_| ParseValueError::new(prim, text))?,
387 ),
388 Primitive::Float | Primitive::Decimal => {
389 let f = parse_float(t).ok_or_else(|| ParseValueError::new(prim, text))?;
390 Value::Float(Real::from_document(f, t, prim))
391 }
392 Primitive::String
393 | Primitive::Date
394 | Primitive::DateTime
395 | Primitive::MonthDay
396 | Primitive::Time
397 | Primitive::Duration
398 | Primitive::Uri => Value::Text(text.into()),
399 })
400 }
401}
402
403// Conversions, so building a model reads like the data rather than like the storage.
404//
405// `Object::set(attrs::ac_line_segment::r, 2.2.into())` beats
406// `Object::set(attrs::ac_line_segment::r, Value::from(2.2))`, and the generated attribute
407// constants already make the *left* side typed. There is deliberately no `From<i32>` or
408// `From<f32>`: CIM's `Integer` is 64-bit and its `Float` is stored as `f64`, and silently
409// widening a narrower literal is how a value ends up a different type than it looks.
410
411impl From<bool> for Value {
412 fn from(b: bool) -> Value {
413 Value::Boolean(b)
414 }
415}
416impl From<i64> for Value {
417 fn from(i: i64) -> Value {
418 Value::Integer(i)
419 }
420}
421impl From<f64> for Value {
422 fn from(f: f64) -> Value {
423 Value::Float(Real::new(f))
424 }
425}
426
427impl From<Real> for Value {
428 fn from(r: Real) -> Value {
429 Value::Float(r)
430 }
431}
432impl From<&str> for Value {
433 fn from(s: &str) -> Value {
434 Value::Text(s.into())
435 }
436}
437impl From<String> for Value {
438 fn from(s: String) -> Value {
439 Value::Text(s.into_boxed_str())
440 }
441}
442impl From<EnumValueId> for Value {
443 fn from(e: EnumValueId) -> Value {
444 Value::Enum(e)
445 }
446}
447impl From<Mrid> for Value {
448 fn from(m: Mrid) -> Value {
449 Value::Reference(m)
450 }
451}
452impl From<Compound> for Value {
453 fn from(c: Compound) -> Value {
454 Value::Compound(Box::new(c))
455 }
456}
457
458/// Parse a float, accepting the forms that appear in published exchange files.
459///
460/// Two deviations are tolerated and a third is deliberately not.
461///
462/// A Fortran-style exponent (`1.5D+3`) is unambiguous, so it is accepted. A comma decimal
463/// mark is *not* unambiguous: `1,234` is `1.234` to a producer with a European locale and
464/// `1234` to one writing a thousands separator, and the two readings differ by a factor of
465/// a thousand on a quantity like a line impedance. It is accepted only where the thousands
466/// reading is impossible — a single comma, no decimal point, and a group of digits after it
467/// that is not three long. Anything still ambiguous is refused, which surfaces as a
468/// [`Rule::InvalidValue`](crate::Rule::InvalidValue) diagnostic naming the text, rather
469/// than as a number that is silently wrong by 1000×.
470fn parse_float(t: &str) -> Option<f64> {
471 if let Ok(f) = t.parse::<f64>() {
472 return Some(f);
473 }
474 let normalized = t.replace(['D', 'd'], "E");
475 if let Ok(f) = normalized.parse::<f64>() {
476 return Some(f);
477 }
478 let (_, tail) = normalized.split_once(',')?;
479 let unambiguous = !normalized.contains('.')
480 && !tail.contains(',')
481 && tail.chars().take_while(char::is_ascii_digit).count() != 3;
482 unambiguous
483 .then(|| normalized.replace(',', ".").parse::<f64>().ok())
484 .flatten()
485}
486
487/// Format a float in the shortest form that round-trips exactly.
488///
489/// `NaN`, `INF` and `-INF` are the lexical forms XML Schema defines for the floating-point
490/// types, which is what CIM `Float` becomes in RDF — see [`Primitive::xsd_datatype`].
491///
492/// Rust's `Display` for `f64` is shortest-round-trip but never uses exponent notation, so
493/// it renders `1.5e300` as a 301-digit integer and `1e-9` as `0.000000001`. Both are legal
494/// `xsd:double` and both re-read exactly, but neither resembles what the producer wrote,
495/// and the first is a denial-of-service-shaped output amplification. Values outside the
496/// range where plain decimal stays compact are therefore written in exponent form, which
497/// is also shortest-round-trip because `LowerExp` shares the same algorithm.
498fn format_float(f: f64) -> String {
499 if f.is_nan() {
500 return "NaN".to_owned();
501 }
502 if f.is_infinite() {
503 return if f > 0.0 { "INF" } else { "-INF" }.to_owned();
504 }
505 let abs = f.abs();
506 // The bounds are where `{}` stops being the shorter rendering of the two.
507 if abs != 0.0 && !(1e-5..1e16).contains(&abs) {
508 return format!("{f:E}");
509 }
510 plain_decimal(f)
511}
512
513/// Format a float without an exponent, which is all `xsd:decimal` allows.
514///
515/// Rust's `Display` for `f64` never uses exponent notation, so it is already the plain
516/// form; only the two spellings of zero need normalizing.
517fn plain_decimal(f: f64) -> String {
518 if !f.is_finite() {
519 // Neither `NaN` nor `INF` is in the decimal lexical space, but losing the value
520 // would be worse than writing what it is.
521 return format_float(f);
522 }
523 let s = f.to_string();
524 if s == "-0" { "0".to_owned() } else { s }
525}
526
527#[derive(Debug, Clone, PartialEq, Eq)]
528pub struct ParseValueError {
529 pub expected: Primitive,
530 pub text: String,
531}
532
533impl ParseValueError {
534 fn new(expected: Primitive, text: &str) -> Self {
535 ParseValueError {
536 expected,
537 // Keep diagnostics bounded even if a file contains a huge text node.
538 text: text.chars().take(64).collect(),
539 }
540 }
541}
542
543impl fmt::Display for ParseValueError {
544 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
545 write!(f, "cannot parse {:?} from {:?}", self.expected, self.text)
546 }
547}
548
549impl std::error::Error for ParseValueError {}
550
551impl fmt::Debug for Value {
552 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
553 match self {
554 Value::Boolean(b) => write!(f, "{b}"),
555 Value::Integer(i) => write!(f, "{i}"),
556 Value::Float(x) => write!(f, "{x}"),
557 Value::Text(s) => write!(f, "{s:?}"),
558 Value::Enum(e) => write!(f, "enum#{}", e.0),
559 Value::Reference(m) => write!(f, "->{m}"),
560 Value::Compound(c) => write!(f, "{{{} fields}}", c.len()),
561 }
562 }
563}
564
565/// Human-readable rendering that resolves enumeration literals through `schema`.
566pub fn display_value(schema: &Schema, v: &Value) -> String {
567 match v {
568 Value::Enum(e) => schema.enum_value(*e).name.to_owned(),
569 Value::Reference(m) => m.canonical(),
570 Value::Compound(c) => {
571 let fields: Vec<String> = c
572 .values()
573 .iter()
574 .map(|(a, v)| format!("{}={}", schema.attr(*a).label, display_value(schema, v)))
575 .collect();
576 format!("{{{}}}", fields.join(", "))
577 }
578 other => other.to_lexical().unwrap_or_default(),
579 }
580}
581
582#[cfg(test)]
583mod tests {
584 use super::*;
585
586 /// A number's spelling is information: the published corpus writes `2.62637E-05` and
587 /// `250.000000`, and re-exporting those as `0.0000262637` and `250` changes 8,623
588 /// values in a model set that is supposed to come back as it went in.
589 #[test]
590 fn a_documents_spelling_of_a_number_survives_a_round_trip() {
591 for (text, prim) in [
592 ("2.62637E-05", Primitive::Float),
593 ("0e+000", Primitive::Float),
594 ("250.000000", Primitive::Float),
595 ("-330.750000", Primitive::Float),
596 ("6.8E-08", Primitive::Float),
597 ("1.0", Primitive::Float),
598 ("250.000000", Primitive::Decimal),
599 ] {
600 let v = Value::parse_primitive(prim, text).unwrap();
601 assert_eq!(
602 v.to_lexical_as(prim).as_deref(),
603 Some(text),
604 "{text:?} as {prim:?}"
605 );
606 }
607 }
608
609 /// Spelling is not value. Two models that differ only in how a producer formatted a
610 /// number are the same model — otherwise every difference report would fill with
611 /// changes nobody made.
612 #[test]
613 fn spelling_is_not_part_of_the_value() {
614 let written = Value::parse_primitive(Primitive::Float, "250.000000").unwrap();
615 let plain = Value::from(250.0);
616 assert_eq!(written, plain);
617 assert_eq!(written.as_f64(), Some(250.0));
618 }
619
620 /// The reader accepts forms that published files deviate with; the writer must not
621 /// hand them on, because output this crate promises is valid has to be valid.
622 #[test]
623 fn a_spelling_is_only_kept_when_it_is_a_conforming_lexical_form() {
624 // A comma decimal mark parses (where it is unambiguous) and is repaired on the
625 // way out, not echoed.
626 let v = Value::parse_primitive(Primitive::Float, "1,5").unwrap();
627 assert_eq!(v.as_f64(), Some(1.5));
628 assert_eq!(v.to_lexical().as_deref(), Some("1.5"));
629 // A Fortran exponent, likewise — and 1500 is inside the range this crate writes
630 // plainly, so the canonical form is not an exponent at all.
631 let v = Value::parse_primitive(Primitive::Float, "1.5D+3").unwrap();
632 assert_eq!(v.to_lexical().as_deref(), Some("1500"));
633 // `xsd:decimal` has no exponent notation, so a float spelling that uses one is not
634 // reused when the profile types the attribute as a decimal.
635 let v = Value::parse_primitive(Primitive::Float, "6.8E-08").unwrap();
636 assert_eq!(
637 v.to_lexical_as(Primitive::Decimal).as_deref(),
638 Some("0.000000068")
639 );
640 }
641
642 /// The fast path may only ever answer "canonical" where the exact comparison would.
643 #[test]
644 fn the_shape_test_never_disagrees_with_formatting() {
645 let texts = [
646 "0",
647 "1",
648 "-1",
649 "250",
650 "2.2",
651 "-330.75",
652 "0.0000262637",
653 "1e5",
654 "1E5",
655 "0e+000",
656 "250.000000",
657 "-0",
658 "007",
659 "1.0",
660 "0.10",
661 "+1",
662 "1.5D+3",
663 "1,5",
664 "12345678901234567",
665 "0.30000000000000004",
666 "1.7976931348623157E308",
667 "5E-324",
668 "-2.62637E-05",
669 ];
670 for text in texts {
671 let Some(v) = parse_float(text) else { continue };
672 for prim in [Primitive::Float, Primitive::Decimal] {
673 if is_canonical_plain(v, text) {
674 assert_eq!(
675 text,
676 canonical(v, prim),
677 "{text:?} claimed canonical for {prim:?}"
678 );
679 }
680 }
681 }
682 }
683
684 #[test]
685 fn parses_the_primitive_forms_used_in_exchange_files() {
686 assert_eq!(
687 Value::parse_primitive(Primitive::Boolean, "true").unwrap(),
688 Value::Boolean(true)
689 );
690 assert_eq!(
691 Value::parse_primitive(Primitive::Boolean, " false ").unwrap(),
692 Value::Boolean(false)
693 );
694 assert_eq!(
695 Value::parse_primitive(Primitive::Integer, "42").unwrap(),
696 Value::Integer(42)
697 );
698 assert_eq!(
699 Value::parse_primitive(Primitive::Float, "-67.2335").unwrap(),
700 Value::from(-67.2335)
701 );
702 assert_eq!(
703 Value::parse_primitive(Primitive::Float, "1.5E3").unwrap(),
704 Value::from(1500.0)
705 );
706 }
707
708 #[test]
709 fn tolerates_non_conforming_numeric_forms() {
710 assert_eq!(
711 Value::parse_primitive(Primitive::Float, "1.5D+3").unwrap(),
712 Value::from(1500.0)
713 );
714 // Integral value written with a decimal point.
715 assert_eq!(
716 Value::parse_primitive(Primitive::Integer, "7.0").unwrap(),
717 Value::Integer(7)
718 );
719 }
720
721 #[test]
722 fn rejects_unparseable_values() {
723 assert!(Value::parse_primitive(Primitive::Boolean, "yes").is_err());
724 assert!(Value::parse_primitive(Primitive::Float, "abc").is_err());
725 }
726
727 /// A comma is a decimal mark to one producer and a thousands separator to another, and
728 /// the two readings differ by a factor of a thousand. Guessing is worse than refusing.
729 #[test]
730 fn a_comma_is_only_read_as_a_decimal_mark_where_it_cannot_be_a_thousands_separator() {
731 let f = |s: &str| Value::parse_primitive(Primitive::Float, s);
732 // Not three digits after the comma: no locale writes a thousands group that way.
733 assert_eq!(f("-67,2335").unwrap(), Value::from(-67.2335));
734 assert_eq!(f("1,5").unwrap(), Value::from(1.5));
735 assert_eq!(f("1,5E3").unwrap(), Value::from(1500.0));
736 // Exactly three: `1,234` is 1.234 or 1234 and nothing in the document says which.
737 assert!(f("1,234").is_err(), "1,234 is ambiguous");
738 assert!(f("1,000").is_err(), "1,000 is ambiguous");
739 // Both marks, or two commas: a grouped number, which CIM/XML never writes.
740 assert!(f("1,234.5").is_err());
741 assert!(f("1,234,567").is_err());
742 }
743
744 #[test]
745 fn ordinary_rust_values_convert_to_the_right_variant() {
746 assert_eq!(Value::from(true), Value::Boolean(true));
747 assert_eq!(Value::from(7i64), Value::Integer(7));
748 assert_eq!(Value::from(2.2f64), Value::from(2.2));
749 assert_eq!(Value::from("BE-Line_1"), Value::Text("BE-Line_1".into()));
750 assert_eq!(
751 Value::from(String::from("owned")),
752 Value::Text("owned".into())
753 );
754 let m = Mrid::parse("70c4656c-f7a0-4319-98bb-84fb5e2e9b37");
755 assert_eq!(Value::from(m.clone()), Value::Reference(m));
756 }
757
758 #[test]
759 fn strings_keep_surrounding_whitespace() {
760 // Names may legitimately contain leading/trailing spaces; only numeric and
761 // boolean parsing trims.
762 assert_eq!(
763 Value::parse_primitive(Primitive::String, " NL LoadArea ").unwrap(),
764 Value::Text(" NL LoadArea ".into())
765 );
766 }
767
768 #[test]
769 fn float_formatting_round_trips() {
770 for f in [
771 0.0,
772 -0.0,
773 1.0,
774 -67.2335,
775 1e-7,
776 1.5e300,
777 8.953211,
778 f64::MIN_POSITIVE,
779 f64::MAX,
780 f64::MIN,
781 1e15,
782 1e16,
783 1e-5,
784 1e-6,
785 ] {
786 let s = format_float(f);
787 assert_eq!(
788 s.parse::<f64>().unwrap(),
789 if f == 0.0 { 0.0 } else { f },
790 "{f} rendered as {s}"
791 );
792 }
793 assert_eq!(format_float(-0.0), "0");
794 }
795
796 #[test]
797 fn extreme_floats_use_exponent_notation_rather_than_hundreds_of_digits() {
798 // `f64::to_string` never uses an exponent, so it renders 1.5e300 as 301 digits.
799 assert_eq!(format_float(1.5e300), "1.5E300");
800 assert_eq!(format_float(1e-9), "1E-9");
801 assert!(format_float(f64::MAX).len() < 24);
802 // The ordinary range keeps its plain decimal form.
803 assert_eq!(format_float(-67.2335), "-67.2335");
804 assert_eq!(format_float(0.0001), "0.0001");
805 }
806
807 #[test]
808 fn non_finite_floats_use_the_xml_schema_lexical_forms() {
809 assert_eq!(format_float(f64::NAN), "NaN");
810 assert_eq!(format_float(f64::INFINITY), "INF");
811 assert_eq!(format_float(f64::NEG_INFINITY), "-INF");
812 // And they read back.
813 for s in ["NaN", "INF", "-INF"] {
814 assert!(
815 Value::parse_primitive(Primitive::Float, s).is_ok(),
816 "{s} should parse"
817 );
818 }
819 }
820}