Skip to main content

relate_model/
value.rs

1use crate::vector::float16::{bfloat16_bits, f16_bits_to_f32, f32_to_f16_bits};
2use chrono::{DateTime, FixedOffset, NaiveDate, NaiveDateTime, NaiveTime};
3use indexmap::IndexMap;
4use std::fmt;
5
6/// ISO 8601 duration with separate month, day, second, and nanosecond components.
7/// chrono::Duration does not support months/years, so we need a custom type.
8#[derive(Debug, Clone, PartialEq)]
9pub struct IsoDuration {
10    pub months: i64,
11    pub days: i64,
12    pub seconds: i64,
13    pub nanoseconds: i64,
14}
15
16impl IsoDuration {
17    pub fn new(months: i64, days: i64, seconds: i64, nanoseconds: i64) -> Self {
18        Self {
19            months,
20            days,
21            seconds,
22            nanoseconds,
23        }
24    }
25
26    pub fn zero() -> Self {
27        Self::new(0, 0, 0, 0)
28    }
29}
30
31impl fmt::Display for IsoDuration {
32    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33        write!(f, "P")?;
34        let years = self.months / 12;
35        let months = self.months % 12;
36        if years != 0 {
37            write!(f, "{years}Y")?;
38        }
39        if months != 0 {
40            write!(f, "{months}M")?;
41        }
42        if self.days != 0 {
43            write!(f, "{}D", self.days)?;
44        }
45
46        // Normalize seconds + nanoseconds: combine into total nanoseconds,
47        // then split back out so signs are consistent.
48        // Engine durations are i128-based (Temporal::Duration.nanos), and
49        // seconds * 1e9 overflows i64 for extreme magnitudes (e.g.
50        // duration({years: 1000000, ...}) scale values from Temporal10),
51        // so the combined math is done in i128, which covers the full
52        // range representable by the i64 fields.
53        let total_nanos = i128::from(self.seconds) * 1_000_000_000 + i128::from(self.nanoseconds);
54        let has_time = total_nanos != 0;
55
56        if has_time || (self.months == 0 && self.days == 0) {
57            write!(f, "T")?;
58
59            let negative = total_nanos < 0;
60            let abs_nanos = total_nanos.unsigned_abs();
61            let abs_seconds = abs_nanos / 1_000_000_000;
62            let frac_nanos = abs_nanos % 1_000_000_000;
63
64            let hours = abs_seconds / 3600;
65            let mins = (abs_seconds % 3600) / 60;
66            let secs = abs_seconds % 60;
67
68            let sign = if negative { "-" } else { "" };
69
70            if hours != 0 {
71                write!(f, "{sign}{hours}H")?;
72            }
73            if mins != 0 {
74                // If hours were written with sign, don't repeat for mins
75                // But Cypher format: each component can have its own sign
76                write!(f, "{sign}{mins}M")?;
77            }
78            if secs != 0 || frac_nanos != 0 || (!has_time && self.months == 0 && self.days == 0) {
79                if frac_nanos != 0 {
80                    let frac = format!("{frac_nanos:09}");
81                    let trimmed = frac.trim_end_matches('0');
82                    write!(f, "{sign}{secs}.{trimmed}S")?;
83                } else {
84                    write!(f, "{sign}{secs}S")?;
85                }
86            }
87        }
88        Ok(())
89    }
90}
91
92/// Cypher point value with SRID and 2D/3D coordinates.
93#[derive(Debug, Clone, PartialEq)]
94pub struct PointValue {
95    pub srid: i32,
96    pub x: f64,
97    pub y: f64,
98    pub z: Option<f64>,
99}
100
101impl PointValue {
102    pub fn cartesian_2d(x: f64, y: f64) -> Self {
103        Self {
104            srid: 7203,
105            x,
106            y,
107            z: None,
108        }
109    }
110
111    pub fn cartesian_3d(x: f64, y: f64, z: f64) -> Self {
112        Self {
113            srid: 9157,
114            x,
115            y,
116            z: Some(z),
117        }
118    }
119
120    pub fn wgs84_2d(longitude: f64, latitude: f64) -> Self {
121        Self {
122            srid: 4326,
123            x: longitude,
124            y: latitude,
125            z: None,
126        }
127    }
128
129    pub fn wgs84_3d(longitude: f64, latitude: f64, height: f64) -> Self {
130        Self {
131            srid: 4979,
132            x: longitude,
133            y: latitude,
134            z: Some(height),
135        }
136    }
137
138    /// True for a point carrying a third coordinate. A point's dimensionality
139    /// is part of its CRS (`4326`/`7203` are 2D, `4979`/`9157` are 3D).
140    pub fn is_3d(&self) -> bool {
141        self.z.is_some()
142    }
143
144    /// The Neo4j CRS name of this point's coordinate space — `wgs-84`,
145    /// `wgs-84-3d`, `cartesian` or `cartesian-3d` — or `None` when the
146    /// srid/dimensionality pair is outside the four `point()` codes (a
147    /// decoder can produce such a value; `point()` cannot). The names come
148    /// from [`crate::wire::crs_name`], the canonical mapping every surface
149    /// shares.
150    pub fn crs_name(&self) -> Option<&'static str> {
151        let canonical_3d = crate::point::srid_dimension(self.srid)? == 3;
152        (canonical_3d == self.is_3d()).then(|| crate::wire::crs_name(self.srid))
153    }
154}
155
156/// The engine's one float rendering policy: `NaN`, `Infinity`, `-Infinity`,
157/// otherwise Rust's shortest round-tripping decimal with a `.0` appended when
158/// `Display` emits no fractional part (so `1.0` never reads as the integer
159/// `1`), never scientific notation. The engine's own text forms — the
160/// `relate_core::Value` display/literal, the Query API v2 `Float` encoding and
161/// EWKT point text — read this one function. The ADR-0280 JSON wire
162/// (`wire::json_f64`, through `CypherValue`'s Display) keeps that ADR's own
163/// `Inf`/`-Inf` spelling by decision, so this is not a claim about it.
164pub fn float_text(f: f64) -> String {
165    if f.is_nan() {
166        return "NaN".into();
167    }
168    if f == f64::INFINITY {
169        return "Infinity".into();
170    }
171    if f == f64::NEG_INFINITY {
172        return "-Infinity".into();
173    }
174    let mut rendered = format!("{f}");
175    if !rendered.contains('.') {
176        rendered.push_str(".0");
177    }
178    rendered
179}
180
181impl fmt::Display for PointValue {
182    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
183        match self.z {
184            Some(z) => write!(
185                f,
186                "point({{srid: {}, x: {}, y: {}, z: {}}})",
187                self.srid, self.x, self.y, z
188            ),
189            None => write!(
190                f,
191                "point({{srid: {}, x: {}, y: {}}})",
192                self.srid, self.x, self.y
193            ),
194        }
195    }
196}
197
198/// A vector coordinate type (CIP-216/CIP-200): the numeric types valid
199/// inside `VECTOR<...>`/`VECTOR(...)`. `Int64`/`Float64` double as ordinary
200/// plain property types (aliases for `INTEGER`/`FLOAT`) outside a vector
201/// type; the others (`Float16`, `BFloat16`, `Float32`, `Int8`/`Int16`/
202/// `Int32`) are valid only as a vector coordinate type. Lives in
203/// `relate-model` (rather than the parser, where it originated) so the
204/// runtime `CypherValue::Vector` variant can carry it without a circular
205/// crate dependency -- the parser re-exports this same type as
206/// `relate_parser::VectorCoordKind`.
207#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
208pub enum VectorCoordKind {
209    Int8,
210    Int16,
211    Int32,
212    Int64,
213    /// IEEE-754 binary16: 10 mantissa bits, range ±65504.
214    Float16,
215    /// bfloat16: the top 16 bits of an IEEE-754 binary32 (8 exponent bits,
216    /// 7 mantissa bits), so its range matches FLOAT32's at lower precision.
217    BFloat16,
218    Float32,
219    Float64,
220}
221
222impl VectorCoordKind {
223    /// CIP-100 "Default type names" table, vector coordinate half: the
224    /// canonical coordinate name rendered inside `VECTOR<...>` and by
225    /// `toString`/Display. `Int64`/`Float64` render as the plain
226    /// `INTEGER`/`FLOAT` names (CIP-216 S-6: they double as ordinary
227    /// property type aliases), not `INTEGER64`/`FLOAT64`.
228    pub fn canonical_name(&self) -> &'static str {
229        match self {
230            VectorCoordKind::Int8 => "INTEGER8",
231            VectorCoordKind::Int16 => "INTEGER16",
232            VectorCoordKind::Int32 => "INTEGER32",
233            VectorCoordKind::Int64 => "INTEGER",
234            VectorCoordKind::Float16 => "FLOAT16",
235            VectorCoordKind::BFloat16 => "BFLOAT16",
236            VectorCoordKind::Float32 => "FLOAT32",
237            VectorCoordKind::Float64 => "FLOAT",
238        }
239    }
240
241    /// Reverse of `canonical_name`, understanding only the canonical
242    /// (non-aliased) spelling -- used to round-trip a rendered type string.
243    pub fn from_canonical_name(name: &str) -> Option<Self> {
244        Some(match name {
245            "INTEGER8" => VectorCoordKind::Int8,
246            "INTEGER16" => VectorCoordKind::Int16,
247            "INTEGER32" => VectorCoordKind::Int32,
248            "INTEGER" => VectorCoordKind::Int64,
249            "FLOAT16" => VectorCoordKind::Float16,
250            "BFLOAT16" => VectorCoordKind::BFloat16,
251            "FLOAT32" => VectorCoordKind::Float32,
252            "FLOAT" => VectorCoordKind::Float64,
253            _ => return None,
254        })
255    }
256
257    /// Resolves the full CIP-200 alias vocabulary accepted by the `vector()`
258    /// constructor's `coordinateType` keyword argument (case-sensitive,
259    /// already-uppercased input expected): every alias in the "Type Name
260    /// Normalization" table, not just the canonical spelling.
261    pub fn from_alias(name: &str) -> Option<Self> {
262        Some(match name {
263            "INT8" | "INTEGER8" => VectorCoordKind::Int8,
264            "INT16" | "INTEGER16" => VectorCoordKind::Int16,
265            "INT32" | "INTEGER32" => VectorCoordKind::Int32,
266            "INT" | "INTEGER" | "INT64" | "INTEGER64" | "SIGNED INTEGER" => VectorCoordKind::Int64,
267            "FLOAT16" => VectorCoordKind::Float16,
268            "BFLOAT16" => VectorCoordKind::BFloat16,
269            "FLOAT32" => VectorCoordKind::Float32,
270            "FLOAT" | "FLOAT64" => VectorCoordKind::Float64,
271            _ => return None,
272        })
273    }
274
275    /// Whether this coordinate kind stores its elements as `CypherValue::Int`
276    /// (the four integer-family kinds) vs `CypherValue::Float` (the two
277    /// floating-point kinds).
278    pub fn is_integer(&self) -> bool {
279        !matches!(
280            self,
281            VectorCoordKind::Float16
282                | VectorCoordKind::BFloat16
283                | VectorCoordKind::Float32
284                | VectorCoordKind::Float64
285        )
286    }
287
288    /// The CIP-200 "Ordering of the Vector Type" coordinate-type rank:
289    /// INTEGER8 < INTEGER16 < INTEGER32 < INTEGER64 < BFLOAT16 < FLOAT16 <
290    /// FLOAT32 < FLOAT64 (Neo4j's `CypherTypeOrder`: BFLOAT16 precedes
291    /// FLOAT16).
292    pub fn order_rank(&self) -> u8 {
293        match self {
294            VectorCoordKind::Int8 => 0,
295            VectorCoordKind::Int16 => 1,
296            VectorCoordKind::Int32 => 2,
297            VectorCoordKind::Int64 => 3,
298            VectorCoordKind::BFloat16 => 4,
299            VectorCoordKind::Float16 => 5,
300            VectorCoordKind::Float32 => 6,
301            VectorCoordKind::Float64 => 7,
302        }
303    }
304
305    /// Narrows a finite `f64` to this kind's floating precision
306    /// (round-to-nearest-even) and returns it widened again — the one
307    /// conversion shared by `vector()` construction, the JSON exactness
308    /// check and JSON decoding. `None` when the input is not finite or the
309    /// narrowing overflows the kind's range. Integer kinds always return
310    /// `None`: their coordinates are integers, converted by their own path.
311    pub fn narrow_float(self, f: f64) -> Option<f64> {
312        if !f.is_finite() {
313            return None;
314        }
315        let narrowed = match self {
316            VectorCoordKind::Float64 => f,
317            VectorCoordKind::Float32 => f as f32 as f64,
318            VectorCoordKind::Float16 => f16_bits_to_f32(f32_to_f16_bits(f as f32)) as f64,
319            VectorCoordKind::BFloat16 => f32::from_bits(bfloat16_bits(f as f32)) as f64,
320            VectorCoordKind::Int8
321            | VectorCoordKind::Int16
322            | VectorCoordKind::Int32
323            | VectorCoordKind::Int64 => return None,
324        };
325        narrowed.is_finite().then_some(narrowed)
326    }
327
328    /// Whether `f` survives this kind's narrowing unchanged: the one
329    /// exactness rule a stored coordinate must satisfy — it spells exactly
330    /// the value the kind holds, not a rounded one. [`Self::narrow_float`]
331    /// is the conversion behind it, so the JSON codec and every surface's
332    /// "can this value be written as this coordinate type" guard share one
333    /// predicate; `float32_exact` is this rule's FLOAT32 case. Always
334    /// `false` for the integer kinds: their coordinates are integers,
335    /// converted by their own path.
336    pub fn is_exact(self, f: f64) -> bool {
337        f.is_finite() && self.narrow_float(f) == Some(f)
338    }
339
340    /// Whether the integer `n` is a coordinate this kind holds — within
341    /// the kind's two's-complement width: the integer half of
342    /// [`Self::is_exact`], the one width predicate the JSON codec and every
343    /// surface's integer-coordinate guard share. Always `false` for the
344    /// floating kinds: their coordinates are floats.
345    pub fn holds_int(self, n: i64) -> bool {
346        match self {
347            VectorCoordKind::Int8 => i8::try_from(n).is_ok(),
348            VectorCoordKind::Int16 => i16::try_from(n).is_ok(),
349            VectorCoordKind::Int32 => i32::try_from(n).is_ok(),
350            VectorCoordKind::Int64 => true,
351            VectorCoordKind::Float16
352            | VectorCoordKind::BFloat16
353            | VectorCoordKind::Float32
354            | VectorCoordKind::Float64 => false,
355        }
356    }
357}
358
359/// Coordinate for geometry types (2D).
360pub type Coord2D = [f64; 2];
361
362/// Extended geometry types beyond Point.
363#[derive(Debug, Clone, PartialEq)]
364pub enum GeometryValue {
365    LineString {
366        coordinates: Vec<Coord2D>,
367        srid: i32,
368    },
369    Polygon {
370        /// Outer ring first, then holes.
371        rings: Vec<Vec<Coord2D>>,
372        srid: i32,
373    },
374    MultiPoint {
375        points: Vec<Coord2D>,
376        srid: i32,
377    },
378    MultiLineString {
379        lines: Vec<Vec<Coord2D>>,
380        srid: i32,
381    },
382    MultiPolygon {
383        polygons: Vec<Vec<Vec<Coord2D>>>,
384        srid: i32,
385    },
386    GeometryCollection {
387        geometries: Vec<GeometryValue>,
388        srid: i32,
389    },
390}
391
392impl GeometryValue {
393    /// Return the SRID of this geometry.
394    pub fn srid(&self) -> i32 {
395        match self {
396            GeometryValue::LineString { srid, .. }
397            | GeometryValue::Polygon { srid, .. }
398            | GeometryValue::MultiPoint { srid, .. }
399            | GeometryValue::MultiLineString { srid, .. }
400            | GeometryValue::MultiPolygon { srid, .. }
401            | GeometryValue::GeometryCollection { srid, .. } => *srid,
402        }
403    }
404
405    /// Return the geometry type name (matching WKT type names).
406    pub fn type_name(&self) -> &'static str {
407        match self {
408            GeometryValue::LineString { .. } => "LineString",
409            GeometryValue::Polygon { .. } => "Polygon",
410            GeometryValue::MultiPoint { .. } => "MultiPoint",
411            GeometryValue::MultiLineString { .. } => "MultiLineString",
412            GeometryValue::MultiPolygon { .. } => "MultiPolygon",
413            GeometryValue::GeometryCollection { .. } => "GeometryCollection",
414        }
415    }
416}
417
418impl fmt::Display for GeometryValue {
419    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
420        match self {
421            GeometryValue::LineString { coordinates, srid } => {
422                write!(f, "linestring({{srid: {srid}, coordinates: [")?;
423                for (i, c) in coordinates.iter().enumerate() {
424                    if i > 0 {
425                        write!(f, ", ")?;
426                    }
427                    write!(f, "[{}, {}]", c[0], c[1])?;
428                }
429                write!(f, "]}})")
430            }
431            GeometryValue::Polygon { rings, srid } => {
432                write!(f, "polygon({{srid: {srid}, coordinates: [")?;
433                for (i, ring) in rings.iter().enumerate() {
434                    if i > 0 {
435                        write!(f, ", ")?;
436                    }
437                    write!(f, "[")?;
438                    for (j, c) in ring.iter().enumerate() {
439                        if j > 0 {
440                            write!(f, ", ")?;
441                        }
442                        write!(f, "[{}, {}]", c[0], c[1])?;
443                    }
444                    write!(f, "]")?;
445                }
446                write!(f, "]}})")
447            }
448            GeometryValue::MultiPoint { points, srid } => {
449                write!(f, "multipoint({{srid: {srid}, coordinates: [")?;
450                for (i, c) in points.iter().enumerate() {
451                    if i > 0 {
452                        write!(f, ", ")?;
453                    }
454                    write!(f, "[{}, {}]", c[0], c[1])?;
455                }
456                write!(f, "]}})")
457            }
458            GeometryValue::MultiLineString { lines: _, srid } => {
459                write!(f, "multilinestring({{srid: {srid}, ...}})")
460            }
461            GeometryValue::MultiPolygon { polygons: _, srid } => {
462                write!(f, "multipolygon({{srid: {srid}, ...}})")
463            }
464            GeometryValue::GeometryCollection { geometries, srid } => {
465                write!(
466                    f,
467                    "geometrycollection({{srid: {}, count: {}}})",
468                    srid,
469                    geometries.len()
470                )
471            }
472        }
473    }
474}
475
476/// The core value type for Relate.
477///
478/// Every value flowing through the query engine is represented as a `CypherValue`.
479/// This replaces Go's `interface{}` with a proper algebraic type.
480#[derive(Debug, Clone)]
481pub enum CypherValue {
482    Null,
483    Bool(bool),
484    Int(i64),
485    Float(f64),
486    Str(String),
487    List(Vec<CypherValue>),
488    Map(IndexMap<String, CypherValue>),
489    Node {
490        id: i64,
491        labels: Vec<String>,
492        properties: IndexMap<String, CypherValue>,
493    },
494    Relationship {
495        id: i64,
496        start_id: i64,
497        end_id: i64,
498        rel_type: String,
499        properties: IndexMap<String, CypherValue>,
500    },
501    Path {
502        nodes: Vec<CypherValue>,
503        relationships: Vec<CypherValue>,
504    },
505    Date(NaiveDate),
506    Time(NaiveTime, Option<FixedOffset>),
507    /// DateTime with fixed offset and optional IANA timezone name (e.g., "Europe/Stockholm").
508    DateTime(DateTime<FixedOffset>, Option<String>),
509    LocalDateTime(NaiveDateTime),
510    Duration(IsoDuration),
511    Point(PointValue),
512    Geometry(GeometryValue),
513    /// CIP-200 VECTOR runtime value: a fixed-length, homogeneously-typed
514    /// numeric vector distinct from `List`. `values` elements are always
515    /// `CypherValue::Int` when `coord.is_integer()`, `CypherValue::Float`
516    /// otherwise (never `Null` or any other variant -- enforced by the
517    /// `vector()` constructor, the only way to produce one). `dim` is
518    /// always `values.len()`.
519    Vector {
520        coord: VectorCoordKind,
521        dim: usize,
522        values: Vec<CypherValue>,
523    },
524}
525
526impl CypherValue {
527    /// Returns true if this value is Null.
528    pub fn is_null(&self) -> bool {
529        matches!(self, CypherValue::Null)
530    }
531
532    /// True for the five temporal variants (`Date`, `Time`, `DateTime`,
533    /// `LocalDateTime`, `Duration`) — the one enumeration of the set, beside
534    /// [`Self::is_null`] and `type_name`; the renderers that classify
535    /// temporals (TOON's scalars-bare token policy) consult this instead of
536    /// re-listing the variants, and a new variant is a compile error here.
537    pub fn is_temporal(&self) -> bool {
538        match self {
539            CypherValue::Date(_)
540            | CypherValue::Time(..)
541            | CypherValue::DateTime(..)
542            | CypherValue::LocalDateTime(_)
543            | CypherValue::Duration(_) => true,
544            CypherValue::Null
545            | CypherValue::Bool(_)
546            | CypherValue::Int(_)
547            | CypherValue::Float(_)
548            | CypherValue::Str(_)
549            | CypherValue::List(_)
550            | CypherValue::Map(_)
551            | CypherValue::Node { .. }
552            | CypherValue::Relationship { .. }
553            | CypherValue::Path { .. }
554            | CypherValue::Geometry(_)
555            | CypherValue::Vector { .. }
556            | CypherValue::Point(_) => false,
557        }
558    }
559
560    /// Returns the type name as a string (for the `type()` function).
561    pub fn type_name(&self) -> &'static str {
562        match self {
563            CypherValue::Null => "NULL",
564            CypherValue::Bool(_) => "BOOLEAN",
565            CypherValue::Int(_) => "INTEGER",
566            CypherValue::Float(_) => "FLOAT",
567            CypherValue::Str(_) => "STRING",
568            CypherValue::List(_) => "LIST",
569            CypherValue::Map(_) => "MAP",
570            CypherValue::Node { .. } => "NODE",
571            CypherValue::Relationship { .. } => "RELATIONSHIP",
572            CypherValue::Path { .. } => "PATH",
573            CypherValue::Date(_) => "DATE",
574            CypherValue::Time(_, _) => "TIME",
575            CypherValue::DateTime(..) => "DATE_TIME",
576            CypherValue::LocalDateTime(_) => "LOCAL_DATE_TIME",
577            CypherValue::Duration(_) => "DURATION",
578            CypherValue::Point(_) => "POINT",
579            CypherValue::Geometry(g) => g.type_name(),
580            CypherValue::Vector { .. } => "VECTOR",
581        }
582    }
583
584    /// Attempts to extract a boolean value.
585    pub fn as_bool(&self) -> Option<bool> {
586        match self {
587            CypherValue::Bool(b) => Some(*b),
588            _ => None,
589        }
590    }
591
592    /// Attempts to extract an integer value.
593    pub fn as_int(&self) -> Option<i64> {
594        match self {
595            CypherValue::Int(i) => Some(*i),
596            _ => None,
597        }
598    }
599
600    /// Attempts to extract a float value, including int-to-float promotion.
601    pub fn as_float(&self) -> Option<f64> {
602        match self {
603            CypherValue::Float(f) => Some(*f),
604            CypherValue::Int(i) => Some(*i as f64),
605            _ => None,
606        }
607    }
608
609    /// Attempts to extract a string reference.
610    pub fn as_str(&self) -> Option<&str> {
611        match self {
612            CypherValue::Str(s) => Some(s),
613            _ => None,
614        }
615    }
616
617    /// Attempts to extract a list reference.
618    pub fn as_list(&self) -> Option<&[CypherValue]> {
619        match self {
620            CypherValue::List(l) => Some(l),
621            _ => None,
622        }
623    }
624
625    /// Attempts to extract a map reference.
626    pub fn as_map(&self) -> Option<&IndexMap<String, CypherValue>> {
627        match self {
628            CypherValue::Map(m) => Some(m),
629            _ => None,
630        }
631    }
632
633    /// Returns true if this value is truthy in Cypher's three-valued logic.
634    /// Null returns None (unknown), true/false return Some(bool).
635    pub fn to_bool_3vl(&self) -> Option<bool> {
636        match self {
637            CypherValue::Null => None,
638            CypherValue::Bool(b) => Some(*b),
639            _ => Some(true), // Non-null, non-bool values are truthy
640        }
641    }
642
643    /// Coerce to a numeric type for arithmetic.
644    /// Returns (value_as_f64, is_integer).
645    pub fn as_numeric(&self) -> Option<(f64, bool)> {
646        match self {
647            CypherValue::Int(i) => Some((*i as f64, true)),
648            CypherValue::Float(f) => Some((*f, false)),
649            _ => None,
650        }
651    }
652}
653
654impl fmt::Display for CypherValue {
655    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
656        match self {
657            CypherValue::Null => write!(f, "null"),
658            CypherValue::Bool(b) => write!(f, "{b}"),
659            CypherValue::Int(i) => write!(f, "{i}"),
660            CypherValue::Float(v) => {
661                if v.is_nan() {
662                    write!(f, "NaN")
663                } else if v.is_infinite() {
664                    write!(f, "{}Inf", if *v < 0.0 { "-" } else { "" })
665                } else if v.fract() == 0.0 {
666                    write!(f, "{v}.0")
667                } else {
668                    write!(f, "{v}")
669                }
670            }
671            CypherValue::Str(s) => write!(f, "\"{s}\""),
672            CypherValue::List(items) => {
673                write!(f, "[")?;
674                for (i, item) in items.iter().enumerate() {
675                    if i > 0 {
676                        write!(f, ", ")?;
677                    }
678                    write!(f, "{item}")?;
679                }
680                write!(f, "]")
681            }
682            CypherValue::Map(map) => {
683                write!(f, "{{")?;
684                for (i, (k, v)) in map.iter().enumerate() {
685                    if i > 0 {
686                        write!(f, ", ")?;
687                    }
688                    write!(f, "{k}: {v}")?;
689                }
690                write!(f, "}}")
691            }
692            CypherValue::Node {
693                labels, properties, ..
694            } => {
695                write!(f, "(:{}", labels.join(":"))?;
696                if !properties.is_empty() {
697                    write!(f, " {{")?;
698                    for (i, (k, v)) in properties.iter().enumerate() {
699                        if i > 0 {
700                            write!(f, ", ")?;
701                        }
702                        write!(f, "{k}: {v}")?;
703                    }
704                    write!(f, "}}")?;
705                }
706                write!(f, ")")
707            }
708            CypherValue::Relationship {
709                rel_type,
710                properties,
711                ..
712            } => {
713                write!(f, "[:{rel_type}")?;
714                if !properties.is_empty() {
715                    write!(f, " {{")?;
716                    for (i, (k, v)) in properties.iter().enumerate() {
717                        if i > 0 {
718                            write!(f, ", ")?;
719                        }
720                        write!(f, "{k}: {v}")?;
721                    }
722                    write!(f, "}}")?;
723                }
724                write!(f, "]")
725            }
726            CypherValue::Path {
727                nodes,
728                relationships,
729            } => {
730                for (i, node) in nodes.iter().enumerate() {
731                    if i > 0 {
732                        if let Some(rel) = relationships.get(i - 1) {
733                            write!(f, "-{rel}-")?;
734                        } else {
735                            write!(f, "--")?;
736                        }
737                    }
738                    write!(f, "{node}")?;
739                }
740                Ok(())
741            }
742            CypherValue::Date(d) => write!(f, "{d}"),
743            CypherValue::Time(t, tz) => {
744                use chrono::Timelike;
745                // Format the time part with trimmed fractional seconds
746                let nanos = t.nanosecond() % 1_000_000_000;
747                if nanos != 0 {
748                    let frac = format!("{nanos:09}");
749                    let trimmed = frac.trim_end_matches('0');
750                    write!(
751                        f,
752                        "{:02}:{:02}:{:02}.{}",
753                        t.hour(),
754                        t.minute(),
755                        t.second(),
756                        trimmed
757                    )?;
758                } else if t.second() != 0 {
759                    write!(f, "{}", t.format("%H:%M:%S"))?;
760                } else {
761                    write!(f, "{}", t.format("%H:%M"))?;
762                }
763                // Format the timezone part
764                if let Some(offset) = tz {
765                    let total_secs = offset.local_minus_utc();
766                    if total_secs == 0 {
767                        write!(f, "Z")
768                    } else {
769                        let sign = if total_secs >= 0 { '+' } else { '-' };
770                        let abs_secs = total_secs.unsigned_abs();
771                        let hours = abs_secs / 3600;
772                        let mins = (abs_secs % 3600) / 60;
773                        let secs = abs_secs % 60;
774                        if secs != 0 {
775                            write!(f, "{sign}{hours:02}:{mins:02}:{secs:02}")
776                        } else {
777                            write!(f, "{sign}{hours:02}:{mins:02}")
778                        }
779                    }
780                } else {
781                    Ok(())
782                }
783            }
784            CypherValue::DateTime(dt, tz_name) => {
785                // Use ISO 8601 format with 'T' separator, trimmed nanos, and compact timezone
786                let nanos = dt.timestamp_subsec_nanos();
787                let date_part = dt.date_naive();
788                let time_part = dt.time();
789                if nanos != 0 {
790                    let frac = format!("{nanos:09}");
791                    let trimmed = frac.trim_end_matches('0');
792                    write!(
793                        f,
794                        "{}T{}.{}",
795                        date_part,
796                        time_part.format("%H:%M:%S"),
797                        trimmed
798                    )?;
799                } else {
800                    write!(f, "{}T{}", date_part, time_part.format("%H:%M:%S"))?;
801                }
802                // Timezone offset
803                let offset = dt.offset();
804                let total_secs = offset.local_minus_utc();
805                if total_secs == 0 {
806                    write!(f, "Z")?;
807                } else {
808                    let sign = if total_secs >= 0 { '+' } else { '-' };
809                    let abs_secs = total_secs.unsigned_abs();
810                    let hours = abs_secs / 3600;
811                    let mins = (abs_secs % 3600) / 60;
812                    let secs_rem = abs_secs % 60;
813                    if secs_rem != 0 {
814                        write!(f, "{sign}{hours:02}:{mins:02}:{secs_rem:02}")?;
815                    } else {
816                        write!(f, "{sign}{hours:02}:{mins:02}")?;
817                    }
818                }
819                // Append IANA timezone name if present
820                if let Some(tz) = tz_name {
821                    write!(f, "[{tz}]")?;
822                }
823                Ok(())
824            }
825            CypherValue::LocalDateTime(dt) => {
826                // Use ISO 8601 format with 'T' separator and trimmed trailing zeros
827                let nanos = dt.and_utc().timestamp_subsec_nanos();
828                if nanos != 0 {
829                    let frac = format!("{nanos:09}");
830                    let trimmed = frac.trim_end_matches('0');
831                    write!(
832                        f,
833                        "{}T{}.{}",
834                        dt.date(),
835                        dt.time().format("%H:%M:%S"),
836                        trimmed
837                    )
838                } else {
839                    write!(f, "{}T{}", dt.date(), dt.time().format("%H:%M:%S"))
840                }
841            }
842            CypherValue::Duration(d) => write!(f, "{d}"),
843            CypherValue::Point(p) => write!(f, "{p}"),
844            CypherValue::Geometry(g) => write!(f, "{g}"),
845            CypherValue::Vector { coord, dim, values } => {
846                write!(f, "vector([")?;
847                for (i, v) in values.iter().enumerate() {
848                    if i > 0 {
849                        write!(f, ", ")?;
850                    }
851                    write!(f, "{v}")?;
852                }
853                write!(f, "], {}, {} NOT NULL)", dim, coord.canonical_name())
854            }
855        }
856    }
857}
858
859impl PartialEq for CypherValue {
860    fn eq(&self, other: &Self) -> bool {
861        match (self, other) {
862            (CypherValue::Null, CypherValue::Null) => true,
863            (CypherValue::Bool(a), CypherValue::Bool(b)) => a == b,
864            (CypherValue::Int(a), CypherValue::Int(b)) => a == b,
865            (CypherValue::Float(a), CypherValue::Float(b)) => a == b,
866            // Exact Int-vs-Float equality: a plain `(a as f64) == b` cast
867            // rounds away low bits for `|a| > 2^53`, which made `=` (and every
868            // scan/residual/MERGE path built on it) disagree with exact
869            // numeric equivalence keys -- so an index's presence could
870            // silently change a MATCH/MERGE result. See
871            // `canonical_key::eq_i64_f64`.
872            (CypherValue::Int(a), CypherValue::Float(b)) => {
873                crate::canonical_key::eq_i64_f64(*a, *b)
874            }
875            (CypherValue::Float(a), CypherValue::Int(b)) => {
876                crate::canonical_key::eq_i64_f64(*b, *a)
877            }
878            (CypherValue::Str(a), CypherValue::Str(b)) => a == b,
879            (CypherValue::List(a), CypherValue::List(b)) => a == b,
880            (CypherValue::Map(a), CypherValue::Map(b)) => a == b,
881            (CypherValue::Node { id: a, .. }, CypherValue::Node { id: b, .. }) => a == b,
882            (CypherValue::Relationship { id: a, .. }, CypherValue::Relationship { id: b, .. }) => {
883                a == b
884            }
885            (CypherValue::Date(a), CypherValue::Date(b)) => a == b,
886            (CypherValue::Time(a, ao), CypherValue::Time(b, bo)) => a == b && ao == bo,
887            (CypherValue::DateTime(a, _), CypherValue::DateTime(b, _)) => a == b,
888            (CypherValue::LocalDateTime(a), CypherValue::LocalDateTime(b)) => a == b,
889            (CypherValue::Duration(a), CypherValue::Duration(b)) => a == b,
890            (CypherValue::Point(a), CypherValue::Point(b)) => a == b,
891            (CypherValue::Geometry(a), CypherValue::Geometry(b)) => a == b,
892            (
893                CypherValue::Vector {
894                    coord: ca,
895                    dim: da,
896                    values: va,
897                },
898                CypherValue::Vector {
899                    coord: cb,
900                    dim: db,
901                    values: vb,
902                },
903            ) => ca == cb && da == db && va == vb,
904            (
905                CypherValue::Path {
906                    nodes: n1,
907                    relationships: r1,
908                },
909                CypherValue::Path {
910                    nodes: n2,
911                    relationships: r2,
912                },
913            ) => n1 == n2 && r1 == r2,
914            _ => false,
915        }
916    }
917}
918
919impl PartialOrd for CypherValue {
920    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
921        match (self, other) {
922            (CypherValue::Int(a), CypherValue::Int(b)) => a.partial_cmp(b),
923            (CypherValue::Float(a), CypherValue::Float(b)) => a.partial_cmp(b),
924            // Exact Int-vs-Float ordering, kept consistent with the equality
925            // above (both route through the same `canonical_key` domain), so
926            // `<`/`ORDER BY` and `=` never disagree past `2^53`.
927            (CypherValue::Int(a), CypherValue::Float(b)) => {
928                crate::canonical_key::cmp_i64_f64(*a, *b)
929            }
930            (CypherValue::Float(a), CypherValue::Int(b)) => {
931                crate::canonical_key::cmp_i64_f64(*b, *a).map(std::cmp::Ordering::reverse)
932            }
933            (CypherValue::Str(a), CypherValue::Str(b)) => a.partial_cmp(b),
934            (CypherValue::Bool(a), CypherValue::Bool(b)) => a.partial_cmp(b),
935            (CypherValue::Date(a), CypherValue::Date(b)) => a.partial_cmp(b),
936            (CypherValue::List(a), CypherValue::List(b)) => {
937                // Lexicographic comparison of lists
938                for (av, bv) in a.iter().zip(b.iter()) {
939                    match av.partial_cmp(bv) {
940                        Some(std::cmp::Ordering::Equal) => continue,
941                        Some(ord) => return Some(ord),
942                        None => return None,
943                    }
944                }
945                a.len().partial_cmp(&b.len())
946            }
947            (CypherValue::Time(a, ao), CypherValue::Time(b, bo)) => {
948                // Sort times by UTC-normalized value
949                match (ao, bo) {
950                    (Some(a_off), Some(b_off)) => {
951                        use chrono::Timelike;
952                        let a_utc_secs =
953                            a.num_seconds_from_midnight() as i64 - a_off.local_minus_utc() as i64;
954                        let b_utc_secs =
955                            b.num_seconds_from_midnight() as i64 - b_off.local_minus_utc() as i64;
956                        match a_utc_secs.partial_cmp(&b_utc_secs) {
957                            Some(std::cmp::Ordering::Equal) => {
958                                // Compare nanoseconds within the second
959                                let a_nanos = a.nanosecond() % 1_000_000_000;
960                                let b_nanos = b.nanosecond() % 1_000_000_000;
961                                a_nanos.partial_cmp(&b_nanos)
962                            }
963                            other => other,
964                        }
965                    }
966                    (None, None) => a.partial_cmp(b),
967                    _ => None,
968                }
969            }
970            (CypherValue::DateTime(a, _), CypherValue::DateTime(b, _)) => a.partial_cmp(b),
971            (CypherValue::LocalDateTime(a), CypherValue::LocalDateTime(b)) => a.partial_cmp(b),
972            _ => None,
973        }
974    }
975}
976
977impl From<bool> for CypherValue {
978    fn from(b: bool) -> Self {
979        CypherValue::Bool(b)
980    }
981}
982
983impl From<i64> for CypherValue {
984    fn from(i: i64) -> Self {
985        CypherValue::Int(i)
986    }
987}
988
989impl From<f64> for CypherValue {
990    fn from(f: f64) -> Self {
991        CypherValue::Float(f)
992    }
993}
994
995impl From<String> for CypherValue {
996    fn from(s: String) -> Self {
997        CypherValue::Str(s)
998    }
999}
1000
1001impl From<&str> for CypherValue {
1002    fn from(s: &str) -> Self {
1003        CypherValue::Str(s.to_string())
1004    }
1005}
1006
1007impl<T: Into<CypherValue>> From<Vec<T>> for CypherValue {
1008    fn from(v: Vec<T>) -> Self {
1009        CypherValue::List(v.into_iter().map(|x| x.into()).collect())
1010    }
1011}
1012
1013impl<T: Into<CypherValue>> From<Option<T>> for CypherValue {
1014    fn from(o: Option<T>) -> Self {
1015        match o {
1016            Some(v) => v.into(),
1017            None => CypherValue::Null,
1018        }
1019    }
1020}
1021
1022#[cfg(test)]
1023mod tests {
1024    use super::*;
1025
1026    #[test]
1027    #[allow(clippy::approx_constant)]
1028    fn test_type_names() {
1029        assert_eq!(CypherValue::Null.type_name(), "NULL");
1030        assert_eq!(CypherValue::Bool(true).type_name(), "BOOLEAN");
1031        assert_eq!(CypherValue::Int(42).type_name(), "INTEGER");
1032        assert_eq!(CypherValue::Float(3.14).type_name(), "FLOAT");
1033        assert_eq!(CypherValue::Str("hello".into()).type_name(), "STRING");
1034        assert_eq!(CypherValue::List(vec![]).type_name(), "LIST");
1035        assert_eq!(CypherValue::Map(IndexMap::new()).type_name(), "MAP");
1036    }
1037
1038    #[test]
1039    fn point_crs_name_classifies_the_four_point_codes() {
1040        let cases = [
1041            (PointValue::cartesian_2d(1.0, 2.0), "cartesian", false),
1042            (
1043                PointValue::cartesian_3d(1.0, 2.0, 3.0),
1044                "cartesian-3d",
1045                true,
1046            ),
1047            (PointValue::wgs84_2d(1.0, 2.0), "wgs-84", false),
1048            (PointValue::wgs84_3d(1.0, 2.0, 3.0), "wgs-84-3d", true),
1049        ];
1050        for (point, name, is_3d) in cases {
1051            assert_eq!(point.crs_name(), Some(name), "{point:?}");
1052            assert_eq!(point.is_3d(), is_3d, "{point:?}");
1053        }
1054        // A srid/dimensionality pair outside the four point() codes (only a
1055        // decoder can build one) has no CRS name.
1056        let unknown = PointValue {
1057            srid: 1234,
1058            x: 1.0,
1059            y: 2.0,
1060            z: None,
1061        };
1062        assert_eq!(unknown.crs_name(), None);
1063        let wrong_dimension = PointValue {
1064            srid: 7203,
1065            x: 1.0,
1066            y: 2.0,
1067            z: Some(3.0),
1068        };
1069        assert_eq!(wrong_dimension.crs_name(), None);
1070    }
1071
1072    #[test]
1073    fn test_int_float_equality() {
1074        assert_eq!(CypherValue::Int(1), CypherValue::Float(1.0));
1075        assert_eq!(CypherValue::Float(1.0), CypherValue::Int(1));
1076        assert_ne!(CypherValue::Int(1), CypherValue::Float(1.5));
1077    }
1078
1079    #[test]
1080    fn test_partial_ord() {
1081        assert!(CypherValue::Int(1) < CypherValue::Int(2));
1082        assert!(CypherValue::Int(1) < CypherValue::Float(1.5));
1083        assert!(CypherValue::Str("a".into()) < CypherValue::Str("b".into()));
1084    }
1085
1086    #[test]
1087    fn int_float_equality_is_exact_past_2_pow_53() {
1088        // `9007199254740993` (= 2^53 + 1) is an exact i64 but rounds to
1089        // `9007199254740992.0` (= 2^53) as an f64. A lossy `(a as f64) == b`
1090        // cast made these compare EQUAL, which disagreed with the exact
1091        // numeric equivalence keys (so an index's presence silently changed
1092        // MATCH/MERGE results). They denote different numbers, so `=` must
1093        // say NOT equal.
1094        let big_int = CypherValue::Int(9_007_199_254_740_993);
1095        let near_float = CypherValue::Float(9_007_199_254_740_992.0);
1096        assert_ne!(big_int, near_float);
1097        assert_ne!(near_float, big_int);
1098
1099        // The float DOES still equal the integer it exactly represents.
1100        assert_eq!(
1101            CypherValue::Int(9_007_199_254_740_992),
1102            CypherValue::Float(9_007_199_254_740_992.0)
1103        );
1104
1105        // Small integral floats keep the ordinary `1 = 1.0` behavior.
1106        assert_eq!(CypherValue::Int(1), CypherValue::Float(1.0));
1107        assert_eq!(CypherValue::Int(0), CypherValue::Float(-0.0));
1108    }
1109
1110    #[test]
1111    fn int_float_ordering_stays_consistent_with_equality() {
1112        // Whenever `partial_cmp` reports `Equal`, `==` must agree, and vice
1113        // versa, across the whole large-magnitude boundary. A stray `Equal`
1114        // from a lossy ordering cast (while `=` became exact) would be a latent
1115        // inconsistency.
1116        let probes = [
1117            (9_007_199_254_740_993_i64, 9_007_199_254_740_992.0_f64),
1118            (9_007_199_254_740_992, 9_007_199_254_740_992.0),
1119            (i64::MAX, 9_223_372_036_854_775_808.0), // 2^63, out of exact range
1120            (i64::MIN, -9_223_372_036_854_775_808.0), // -2^63, in exact range
1121            (0, -0.0),
1122            (1, 1.0),
1123            (2, 1.5),
1124            (1, 1.5),
1125        ];
1126        for (i, f) in probes {
1127            let iv = CypherValue::Int(i);
1128            let fv = CypherValue::Float(f);
1129            let eq = iv == fv;
1130            let cmp_eq = iv.partial_cmp(&fv) == Some(std::cmp::Ordering::Equal);
1131            assert_eq!(eq, cmp_eq, "eq/ord disagree for Int({i}) vs Float({f})");
1132            // Reverse direction must be the mirror image.
1133            let rev = fv.partial_cmp(&iv);
1134            assert_eq!(
1135                iv.partial_cmp(&fv),
1136                rev.map(std::cmp::Ordering::reverse),
1137                "forward/reverse ordering not antisymmetric for {i}/{f}"
1138            );
1139        }
1140        // 2^53 + 1 (Int) sits strictly above 2^53 (Float).
1141        assert!(
1142            CypherValue::Int(9_007_199_254_740_993) > CypherValue::Float(9_007_199_254_740_992.0)
1143        );
1144    }
1145
1146    #[test]
1147    fn test_display() {
1148        assert_eq!(format!("{}", CypherValue::Null), "null");
1149        assert_eq!(format!("{}", CypherValue::Bool(true)), "true");
1150        assert_eq!(format!("{}", CypherValue::Int(42)), "42");
1151        assert_eq!(format!("{}", CypherValue::Float(3.0)), "3.0");
1152        assert_eq!(format!("{}", CypherValue::Str("hi".into())), "\"hi\"");
1153    }
1154
1155    #[test]
1156    #[allow(clippy::approx_constant)]
1157    fn test_as_float_promotion() {
1158        assert_eq!(CypherValue::Int(5).as_float(), Some(5.0));
1159        assert_eq!(CypherValue::Float(3.14).as_float(), Some(3.14));
1160        assert_eq!(CypherValue::Str("x".into()).as_float(), None);
1161    }
1162
1163    #[test]
1164    fn test_three_valued_logic() {
1165        assert_eq!(CypherValue::Null.to_bool_3vl(), None);
1166        assert_eq!(CypherValue::Bool(true).to_bool_3vl(), Some(true));
1167        assert_eq!(CypherValue::Bool(false).to_bool_3vl(), Some(false));
1168        assert_eq!(CypherValue::Int(0).to_bool_3vl(), Some(true));
1169    }
1170
1171    #[test]
1172    fn test_iso_duration_display() {
1173        assert_eq!(format!("{}", IsoDuration::new(0, 0, 0, 0)), "PT0S");
1174        assert_eq!(format!("{}", IsoDuration::new(14, 0, 0, 0)), "P1Y2M");
1175        assert_eq!(format!("{}", IsoDuration::new(0, 5, 3661, 0)), "P5DT1H1M1S");
1176        // Negative time components carry the sign per component.
1177        assert_eq!(
1178            format!("{}", IsoDuration::new(0, 0, -3661, -500_000_000)),
1179            "PT-1H-1M-1.5S"
1180        );
1181        // Mixed-sign seconds/nanoseconds normalize to a single sign.
1182        assert_eq!(
1183            format!("{}", IsoDuration::new(0, 0, 1, -1_500_000_000)),
1184            "PT-0.5S"
1185        );
1186    }
1187
1188    #[test]
1189    fn test_iso_duration_display_extreme_magnitudes() {
1190        // Temporal10 [10] magnitude: duration({years: 1000000, ...}).
1191        assert_eq!(
1192            format!("{}", IsoDuration::new(12_000_000, 0, 0, 0)),
1193            "P1000000Y"
1194        );
1195        assert_eq!(
1196            format!("{}", IsoDuration::new(-12_000_000, 0, 0, 0)),
1197            "P-1000000Y"
1198        );
1199        // seconds * 1e9 overflows i64 at these magnitudes; the combined
1200        // seconds/nanos math must stay correct via i128 intermediates.
1201        assert_eq!(
1202            format!("{}", IsoDuration::new(0, 0, i64::MAX, 999_999_999)),
1203            "PT2562047788015215H30M7.999999999S"
1204        );
1205        assert_eq!(
1206            format!("{}", IsoDuration::new(0, 0, i64::MIN, -999_999_999)),
1207            "PT-2562047788015215H-30M-8.999999999S"
1208        );
1209        // Full engine-representable stack: 1e6-scale years plus extreme time.
1210        assert_eq!(
1211            format!("{}", IsoDuration::new(12_000_000, 0, i64::MAX, 999_999_999)),
1212            "P1000000YT2562047788015215H30M7.999999999S"
1213        );
1214        assert_eq!(
1215            format!(
1216                "{}",
1217                IsoDuration::new(-12_000_000, 0, i64::MIN, -999_999_999)
1218            ),
1219            "P-1000000YT-2562047788015215H-30M-8.999999999S"
1220        );
1221    }
1222
1223    #[test]
1224    fn test_point_display() {
1225        let p = PointValue::wgs84_2d(-73.9857, 40.7484);
1226        assert_eq!(
1227            format!("{p}"),
1228            "point({srid: 4326, x: -73.9857, y: 40.7484})"
1229        );
1230    }
1231
1232    #[test]
1233    fn test_from_conversions() {
1234        let v: CypherValue = 42i64.into();
1235        assert_eq!(v, CypherValue::Int(42));
1236
1237        let v: CypherValue = "hello".into();
1238        assert_eq!(v, CypherValue::Str("hello".to_string()));
1239
1240        let v: CypherValue = true.into();
1241        assert_eq!(v, CypherValue::Bool(true));
1242
1243        let v: CypherValue = None::<i64>.into();
1244        assert_eq!(v, CypherValue::Null);
1245    }
1246
1247    #[test]
1248    fn test_float_display_infinity_and_nan() {
1249        // CIP-55: the special float values render as `Inf`/`-Inf`/`NaN`,
1250        // matching Neo4j's `RETURN Infinity` result rendering (as opposed
1251        // to `toString()`, which spells them out as `'Infinity'`).
1252        assert_eq!(format!("{}", CypherValue::Float(f64::INFINITY)), "Inf");
1253        assert_eq!(format!("{}", CypherValue::Float(f64::NEG_INFINITY)), "-Inf");
1254        assert_eq!(format!("{}", CypherValue::Float(f64::NAN)), "NaN");
1255        // Ordinary finite floats are unaffected.
1256        assert_eq!(format!("{}", CypherValue::Float(2.0)), "2.0");
1257        assert_eq!(format!("{}", CypherValue::Float(1.5)), "1.5");
1258    }
1259
1260    // ---- CIP-200 VECTOR runtime value type ----
1261
1262    #[test]
1263    fn test_vector_display() {
1264        let v = CypherValue::Vector {
1265            coord: VectorCoordKind::Int64,
1266            dim: 3,
1267            values: vec![
1268                CypherValue::Int(1),
1269                CypherValue::Int(2),
1270                CypherValue::Int(3),
1271            ],
1272        };
1273        assert_eq!(format!("{v}"), "vector([1, 2, 3], 3, INTEGER NOT NULL)");
1274
1275        let float_v = CypherValue::Vector {
1276            coord: VectorCoordKind::Float32,
1277            dim: 2,
1278            values: vec![CypherValue::Float(1.0), CypherValue::Float(2.5)],
1279        };
1280        assert_eq!(
1281            format!("{float_v}"),
1282            "vector([1.0, 2.5], 2, FLOAT32 NOT NULL)"
1283        );
1284    }
1285
1286    #[test]
1287    fn test_vector_equality_compares_coord_dim_and_values() {
1288        let a = CypherValue::Vector {
1289            coord: VectorCoordKind::Int32,
1290            dim: 2,
1291            values: vec![CypherValue::Int(1), CypherValue::Int(2)],
1292        };
1293        let same = a.clone();
1294        assert_eq!(a, same);
1295
1296        let different_coord = CypherValue::Vector {
1297            coord: VectorCoordKind::Int64,
1298            dim: 2,
1299            values: vec![CypherValue::Int(1), CypherValue::Int(2)],
1300        };
1301        assert_ne!(a, different_coord);
1302
1303        let different_values = CypherValue::Vector {
1304            coord: VectorCoordKind::Int32,
1305            dim: 2,
1306            values: vec![CypherValue::Int(2), CypherValue::Int(1)],
1307        };
1308        assert_ne!(a, different_values);
1309
1310        // A vector is never equal to a plain list, even with identical
1311        // element values.
1312        let list = CypherValue::List(vec![CypherValue::Int(1), CypherValue::Int(2)]);
1313        assert_ne!(a, list);
1314    }
1315
1316    #[test]
1317    fn test_vector_type_name_and_ordering_is_unordered() {
1318        let a = CypherValue::Vector {
1319            coord: VectorCoordKind::Int32,
1320            dim: 1,
1321            values: vec![CypherValue::Int(1)],
1322        };
1323        let b = a.clone();
1324        assert_eq!(a.type_name(), "VECTOR");
1325        // `CypherValue::partial_cmp` deliberately has no Vector<->Vector
1326        // arm: the CIP-200 `</>/<=/>=` three-valued-logic special case
1327        // (always null except `<=`/`>=` on equal vectors) is handled at
1328        // the comparison-operator level, not via `PartialOrd`.
1329        assert_eq!(a.partial_cmp(&b), None);
1330    }
1331
1332    #[test]
1333    fn test_vector_coord_kind_aliases_and_canonical_names() {
1334        assert_eq!(
1335            VectorCoordKind::from_alias("INT8"),
1336            Some(VectorCoordKind::Int8)
1337        );
1338        assert_eq!(
1339            VectorCoordKind::from_alias("INTEGER8"),
1340            Some(VectorCoordKind::Int8)
1341        );
1342        assert_eq!(
1343            VectorCoordKind::from_alias("SIGNED INTEGER"),
1344            Some(VectorCoordKind::Int64)
1345        );
1346        assert_eq!(
1347            VectorCoordKind::from_alias("FLOAT64"),
1348            Some(VectorCoordKind::Float64)
1349        );
1350        assert_eq!(VectorCoordKind::from_alias("STRING"), None);
1351
1352        assert_eq!(VectorCoordKind::Int64.canonical_name(), "INTEGER");
1353        assert_eq!(VectorCoordKind::Float64.canonical_name(), "FLOAT");
1354        assert_eq!(VectorCoordKind::Float32.canonical_name(), "FLOAT32");
1355
1356        // Coordinate-type ordering rank (CIP-200 "Ordering of the Vector
1357        // Type"): INTEGER8 < INTEGER16 < INTEGER32 < INTEGER64 < BFLOAT16
1358        // < FLOAT16 < FLOAT32 < FLOAT64.
1359        assert!(VectorCoordKind::Int8.order_rank() < VectorCoordKind::Int16.order_rank());
1360        assert!(VectorCoordKind::Int16.order_rank() < VectorCoordKind::Int32.order_rank());
1361        assert!(VectorCoordKind::Int32.order_rank() < VectorCoordKind::Int64.order_rank());
1362        assert!(VectorCoordKind::Int64.order_rank() < VectorCoordKind::BFloat16.order_rank());
1363        assert!(VectorCoordKind::BFloat16.order_rank() < VectorCoordKind::Float16.order_rank());
1364        assert!(VectorCoordKind::Float16.order_rank() < VectorCoordKind::Float32.order_rank());
1365        assert!(VectorCoordKind::Float32.order_rank() < VectorCoordKind::Float64.order_rank());
1366    }
1367
1368    #[test]
1369    fn narrow_float_rounds_to_the_coordinate_precision() {
1370        use VectorCoordKind::*;
1371        // FLOAT16: 10 mantissa bits (0.1 -> 0.0999755859375), range ±65504.
1372        assert_eq!(Float16.narrow_float(1.0), Some(1.0));
1373        assert_eq!(Float16.narrow_float(0.1), Some(0.0999755859375));
1374        assert_eq!(Float16.narrow_float(65504.0), Some(65504.0));
1375        assert_eq!(Float16.narrow_float(65520.0), None);
1376        assert_eq!(Float16.narrow_float(2f64.powi(-24)), Some(2f64.powi(-24)));
1377        assert_eq!(Float16.narrow_float(2f64.powi(-25)), Some(0.0));
1378        // BFLOAT16: the top 16 bits of a binary32, subnormals included.
1379        assert_eq!(BFloat16.narrow_float(1.0), Some(1.0));
1380        assert_eq!(BFloat16.narrow_float(257.0), Some(256.0));
1381        assert_eq!(
1382            BFloat16.narrow_float(3.3895314e38),
1383            Some(3.3895314e38f32 as f64)
1384        );
1385        assert_eq!(BFloat16.narrow_float(1e39), None);
1386        // 9.18e-41 is a bfloat16 subnormal: the smallest one, 2^-136.
1387        assert_eq!(BFloat16.narrow_float(9.18e-41), Some(9.183549615799121e-41));
1388        // FLOAT32/FLOAT64 and the integer kinds.
1389        assert_eq!(Float32.narrow_float(0.1), Some(0.1f32 as f64));
1390        assert_eq!(Float64.narrow_float(0.1), Some(0.1));
1391        assert_eq!(Int8.narrow_float(1.0), None);
1392        assert_eq!(Float16.narrow_float(f64::NAN), None);
1393    }
1394
1395    #[test]
1396    fn is_exact_holds_only_for_values_the_kind_spells_unchanged() {
1397        use VectorCoordKind::*;
1398        // 0.1 loses precision in every narrower kind; FLOAT64 keeps every
1399        // finite value, so only its non-finite input is inexact.
1400        assert!(!Float16.is_exact(0.1));
1401        assert!(!BFloat16.is_exact(0.1));
1402        assert!(!Float32.is_exact(0.1));
1403        assert!(Float64.is_exact(0.1));
1404        assert!(Float16.is_exact(0.0999755859375));
1405        assert!(BFloat16.is_exact(256.0));
1406        assert!(Float32.is_exact(0.1f32 as f64));
1407        for kind in [Float16, BFloat16, Float32, Float64] {
1408            assert!(!kind.is_exact(f64::INFINITY), "{kind:?}");
1409            assert!(!kind.is_exact(f64::NAN), "{kind:?}");
1410        }
1411        // Integer kinds never admit a float coordinate.
1412        assert!(!Int8.is_exact(1.0));
1413    }
1414}