Skip to main content

relate_core/value/
mod.rs

1use std::collections::BTreeMap;
2use std::fmt;
3use std::ops::ControlFlow;
4use std::sync::Arc;
5
6pub use relate_model::value::PointValue;
7pub use relate_model::VectorCoordKind;
8
9use relate_model::identifier::quote_identifier_shaped;
10
11use crate::temporal::Temporal;
12use crate::{Error, NodeId, RelId};
13
14mod depth;
15mod json;
16mod ordering;
17mod props;
18pub(crate) use depth::{descends, DEPTH_LIMIT_MARKER};
19pub use depth::{next_depth, value_depth_exceeded, MAX_VALUE_DEPTH};
20pub use json::{tagged_str, TaggedStr};
21pub use props::PropertyMap;
22
23#[derive(Debug, Clone, PartialEq)]
24pub struct Node {
25    pub id: NodeId,
26    pub labels: Arc<Vec<String>>,
27    pub properties: Arc<PropertyMap>,
28}
29
30#[derive(Debug, Clone, PartialEq)]
31pub struct Relationship {
32    pub id: RelId,
33    pub start: NodeId,
34    pub end: NodeId,
35    pub rel_type: String,
36    pub properties: Arc<PropertyMap>,
37}
38
39#[derive(Debug, Clone, PartialEq)]
40pub struct Path {
41    pub nodes: Vec<Node>,
42    pub rels: Vec<Relationship>,
43}
44
45/// OpenCypher runtime value.
46#[derive(Debug, Clone, PartialEq, Default)]
47pub enum Value {
48    #[default]
49    Null,
50    Bool(bool),
51    Int(i64),
52    Float(f64),
53    String(Arc<str>),
54    List(Arc<Vec<Value>>),
55    Map(Arc<BTreeMap<String, Value>>),
56    Node(Arc<Node>),
57    Relationship(Arc<Relationship>),
58    Path(Arc<Path>),
59    Temporal(Temporal),
60    Point(PointValue),
61    /// CIP-246 UUID: 128-bit value, rendered as the canonical lowercase
62    /// hyphenated string (`to_display_string`/`iso`-style bare form) and
63    /// constructible from a string or two 64-bit halves.
64    Uuid(u128),
65    Vector {
66        coord: VectorCoordKind,
67        values: Arc<Vec<Value>>,
68    },
69    /// A byte array (ADR-0327). Statement-scoped: it enters only as a query
70    /// parameter (Bolt PackStream Bytes) and flows through expressions,
71    /// lists and maps into results; storing it as a property fails with a
72    /// typed `TypeError`. Shared payload like `String` (ADR-0170).
73    Bytes(Arc<[u8]>),
74}
75
76// Query results cross worker threads, so the shared payloads must keep
77// `Value: Send + Sync` (ADR-0170).
78const _: () = {
79    const fn assert_send_sync<T: Send + Sync>() {}
80    assert_send_sync::<Value>();
81};
82
83/// Whether the summed logical bytes (ADR-0042, as
84/// [`Value::logical_bytes`]) of `values` stay within `limit`, or `None`
85/// once the running total exceeds it. The one early-stopping logical-bytes
86/// walk (ADR-0341): the total stops being computed as soon as it exceeds
87/// `limit` instead of walking every value.
88///
89/// Shared payloads (ADR-0170) still count once per reference: many rows
90/// holding one large list are small in memory but large in logical bytes,
91/// and an unbounded sum over them does work proportional to the product.
92/// The Bolt server sums its open results against one connection-wide cap
93/// with it (ADR-0311).
94pub fn logical_bytes_within<'a>(
95    values: impl IntoIterator<Item = &'a Value>,
96    limit: u64,
97) -> Option<u64> {
98    let mut total = 0;
99    let over = values
100        .into_iter()
101        .try_for_each(|v| v.add_logical_bytes(&mut total, limit, 0))
102        .is_break();
103    (!over).then_some(total)
104}
105
106/// Adds `bytes` to `acc` (saturating) and breaks once `acc` exceeds `budget`.
107fn add_bytes(acc: &mut u64, bytes: u64, budget: u64) -> ControlFlow<()> {
108    *acc = acc.saturating_add(bytes);
109    if *acc > budget {
110        ControlFlow::Break(())
111    } else {
112        ControlFlow::Continue(())
113    }
114}
115
116/// Add one string's logical size — [`str_logical_bytes`] is the one
117/// spelling of the size; this is only its budgeted accumulation.
118fn add_str_bytes(s: &str, acc: &mut u64, budget: u64) -> ControlFlow<()> {
119    add_bytes(acc, str_logical_bytes(s), budget)
120}
121
122/// Add one byte payload's logical size (`Value::Bytes`): header 16 plus
123/// its length — the same shape [`str_logical_bytes`] spells for a
124/// string's UTF-8 bytes.
125fn add_payload_bytes(payload: &[u8], acc: &mut u64, budget: u64) -> ControlFlow<()> {
126    add_bytes(acc, bytes_logical_bytes(payload), budget)
127}
128
129fn add_property_bytes<'a>(
130    props: impl IntoIterator<Item = (&'a String, &'a Value)>,
131    acc: &mut u64,
132    budget: u64,
133    depth: u32,
134) -> ControlFlow<()> {
135    props.into_iter().try_for_each(|(k, v)| {
136        add_str_bytes(k, acc, budget)?;
137        v.add_logical_bytes(acc, budget, depth)
138    })
139}
140
141fn add_node_bytes(n: &Node, acc: &mut u64, budget: u64, depth: u32) -> ControlFlow<()> {
142    n.labels
143        .iter()
144        .try_for_each(|l| add_str_bytes(l, acc, budget))?;
145    add_property_bytes(n.properties.iter(), acc, budget, depth)
146}
147
148fn add_rel_bytes(r: &Relationship, acc: &mut u64, budget: u64, depth: u32) -> ControlFlow<()> {
149    add_str_bytes(&r.rel_type, acc, budget)?;
150    add_property_bytes(r.properties.iter(), acc, budget, depth)
151}
152
153/// A string's documented logical size (ADR-0042): the 16-byte header
154/// plus its UTF-8 bytes — the one spelling every string-size sum reads
155/// (row keys, node and relationship property keys), beside
156/// [`Value::logical_bytes`].
157#[inline]
158pub fn str_logical_bytes(s: &str) -> u64 {
159    16 + s.len() as u64
160}
161
162/// A byte payload's documented logical size (ADR-0042): the 16-byte header
163/// plus its bytes — the one spelling every payload-size site reads, beside
164/// [`str_logical_bytes`] and [`Value::logical_bytes`].
165#[inline]
166pub fn bytes_logical_bytes(payload: &[u8]) -> u64 {
167    16 + payload.len() as u64
168}
169
170/// The one float rendering policy: `NaN`, `±Infinity`, otherwise Rust's
171/// shortest round-tripping decimal form with a `.0` appended when `Display`
172/// emits no fractional part (so `1.0` never reads as the integer `1`).
173///
174/// Never scientific: the decimal form parses back to the same `f64`, and a
175/// second exponent policy for vector coordinates (the historical `1e16`
176/// threshold) made a value's literal and display forms disagree. Both
177/// [`Value::to_cypher_literal_at`] (its scalar and vector-coordinate arms)
178/// and [`Value::to_display_string_at`] call this, so scalar and vector
179/// coordinates share one spelling.
180fn float_literal(f: f64) -> String {
181    if f.is_nan() {
182        return "NaN".into();
183    }
184    if f == f64::INFINITY {
185        return "Infinity".into();
186    }
187    if f == f64::NEG_INFINITY {
188        return "-Infinity".into();
189    }
190    let mut rendered = format!("{f}");
191    if !rendered.contains('.') {
192        rendered.push_str(".0");
193    }
194    rendered
195}
196
197impl Value {
198    /// Share one node across every row that clones this value.
199    pub fn from_node(node: Node) -> Self {
200        Value::Node(Arc::new(node))
201    }
202
203    /// Share one relationship across every row that clones this value.
204    pub fn from_relationship(rel: Relationship) -> Self {
205        Value::Relationship(Arc::new(rel))
206    }
207
208    /// Share one path across every row that clones this value.
209    pub fn from_path(path: Path) -> Self {
210        Value::Path(Arc::new(path))
211    }
212
213    /// Documented logical payload size (ADR-0042) — the per-variant
214    /// accumulation of the sizes [`str_logical_bytes`] spells for
215    /// strings.
216    pub fn logical_bytes(&self) -> u64 {
217        let mut total = 0;
218        let flow = self.add_logical_bytes(&mut total, u64::MAX, 0);
219        // The byte budget is `u64::MAX`, so the only reachable `Break` is
220        // the ADR-0462 depth guard: were it to fire (unreachable behind the
221        // checked constructors) the result would be the partial sum counted
222        // down to the cap rather than a panic, since this walk has no error
223        // channel.
224        debug_assert!(
225            flow.is_continue(),
226            "logical_bytes broke on the ADR-0462 depth guard at the cap"
227        );
228        total
229    }
230
231    /// The single implementation of the ADR-0042 formula, shared by
232    /// [`Value::logical_bytes`] (budget `u64::MAX`, never breaks) and
233    /// [`logical_bytes_within`]: adds this value's logical bytes to `acc`
234    /// and breaks as soon as `acc` exceeds `budget`.
235    ///
236    /// `depth` is the level of the container whose contents are being
237    /// added; past [`MAX_VALUE_DEPTH`] the walk breaks (ADR-0462). The
238    /// guard is unreachable behind the checked constructors and only keeps
239    /// an over-deep value from recursing without a byte budget to stop it.
240    fn add_logical_bytes(&self, acc: &mut u64, budget: u64, depth: u32) -> ControlFlow<()> {
241        match self {
242            Value::Null | Value::Bool(_) => add_bytes(acc, 1, budget),
243            Value::Int(_) | Value::Float(_) => add_bytes(acc, 8, budget),
244            Value::String(s) => add_str_bytes(s, acc, budget),
245            Value::Bytes(b) => add_payload_bytes(b, acc, budget),
246            Value::List(xs) | Value::Vector { values: xs, .. } => {
247                let Some(next) = next_depth(depth) else {
248                    return ControlFlow::Break(());
249                };
250                add_bytes(acc, 16, budget)?;
251                xs.iter()
252                    .try_for_each(|x| x.add_logical_bytes(acc, budget, next))
253            }
254            Value::Map(m) => {
255                let Some(next) = next_depth(depth) else {
256                    return ControlFlow::Break(());
257                };
258                add_bytes(acc, 16, budget)?;
259                add_property_bytes(m.iter(), acc, budget, next)
260            }
261            Value::Node(n) => {
262                let Some(next) = next_depth(depth) else {
263                    return ControlFlow::Break(());
264                };
265                add_node_bytes(n, acc, budget, next)
266            }
267            Value::Relationship(r) => {
268                let Some(next) = next_depth(depth) else {
269                    return ControlFlow::Break(());
270                };
271                add_rel_bytes(r, acc, budget, next)
272            }
273            Value::Path(p) => {
274                let Some(next) = next_depth(depth) else {
275                    return ControlFlow::Break(());
276                };
277                p.nodes
278                    .iter()
279                    .try_for_each(|n| add_node_bytes(n, acc, budget, next))?;
280                p.rels
281                    .iter()
282                    .try_for_each(|r| add_rel_bytes(r, acc, budget, next))
283            }
284            Value::Temporal(_) => add_bytes(acc, 24, budget),
285            Value::Point(_) => add_bytes(acc, 32, budget),
286            Value::Uuid(_) => add_bytes(acc, 16, budget),
287        }
288    }
289
290    pub fn as_temporal(&self) -> Option<&Temporal> {
291        match self {
292            Value::Temporal(t) => Some(t),
293            _ => None,
294        }
295    }
296
297    pub fn as_string(&self) -> Option<&str> {
298        match self {
299            Value::String(s) => Some(&**s),
300            _ => None,
301        }
302    }
303
304    pub fn is_null(&self) -> bool {
305        matches!(self, Value::Null)
306    }
307
308    pub fn as_bool(&self) -> Option<bool> {
309        match self {
310            Value::Bool(b) => Some(*b),
311            _ => None,
312        }
313    }
314
315    /// Cypher toBoolean-ish: true/false stay, null stays none.
316    pub fn truthy(&self) -> Option<bool> {
317        match self {
318            Value::Bool(b) => Some(*b),
319            Value::Null => None,
320            _ => None,
321        }
322    }
323
324    pub fn as_number(&self) -> Option<f64> {
325        match self {
326            Value::Int(i) => Some(*i as f64),
327            Value::Float(f) => Some(*f),
328            _ => None,
329        }
330    }
331
332    pub fn as_int(&self) -> Option<i64> {
333        match self {
334            Value::Int(i) => Some(*i),
335            Value::Float(f)
336                if f.fract() == 0.0 && *f >= i64::MIN as f64 && *f <= i64::MAX as f64 =>
337            {
338                Some(*f as i64)
339            }
340            _ => None,
341        }
342    }
343
344    pub fn to_cypher_literal(&self) -> String {
345        self.to_cypher_literal_at(0)
346    }
347
348    /// [`Value::to_cypher_literal`] with the ADR-0462 depth guard: a
349    /// container past [`MAX_VALUE_DEPTH`] renders
350    /// [`DEPTH_LIMIT_MARKER`] instead of recursing. `depth` is the number of
351    /// containers enclosing `self`, so a root is 0 and its children 1.
352    fn to_cypher_literal_at(&self, depth: u32) -> String {
353        match self {
354            Value::Null => "null".into(),
355            Value::Bool(true) => "true".into(),
356            Value::Bool(false) => "false".into(),
357            Value::Int(i) => i.to_string(),
358            Value::Float(f) => float_literal(*f),
359            Value::String(s) => format!("'{}'", escape_cypher_string(s)),
360            Value::Bytes(b) => bytes_as_int_list(b),
361            Value::List(xs) => {
362                let Some(next) = next_depth(depth) else {
363                    return DEPTH_LIMIT_MARKER.into();
364                };
365                let inner: Vec<_> = xs.iter().map(|v| v.to_cypher_literal_at(next)).collect();
366                format!("[{}]", inner.join(", "))
367            }
368            Value::Map(m) => {
369                let Some(next) = next_depth(depth) else {
370                    return DEPTH_LIMIT_MARKER.into();
371                };
372                map_to_cypher_literal(m.iter(), next)
373            }
374            Value::Node(n) => n.to_cypher_literal_at(depth),
375            Value::Relationship(r) => r.to_cypher_literal_at(depth),
376            Value::Path(p) => p.to_cypher_literal_at(depth),
377            Value::Temporal(t) => format!("'{}'", escape_cypher_string(&t.iso_string())),
378            // Round-trippable form like VECTOR: uuid('...') (CIP-246).
379            Value::Uuid(u) => format!("uuid('{}')", uuid_hyphenated(*u)),
380            Value::Point(p) => p.to_string(),
381            Value::Vector { coord, values } => {
382                let Some(next) = next_depth(depth) else {
383                    return DEPTH_LIMIT_MARKER.into();
384                };
385                let inner = values
386                    .iter()
387                    .map(|value| value.to_cypher_literal_at(next))
388                    .collect::<Vec<_>>();
389                vector_text(&inner, *coord)
390            }
391        }
392    }
393
394    /// The CIP-271 `toString()` rendering: the cypher-shell display form
395    /// rather than the round-trippable literal form — strings are unquoted,
396    /// temporals are bare full-precision ISO strings (ADR-0448), and
397    /// maps/lists render recursively with `, ` separators (verified
398    /// against Neo4j 2026.09.0).
399    pub fn to_display_string(&self) -> String {
400        self.to_display_string_at(0)
401    }
402
403    /// [`Value::to_display_string`] with the ADR-0462 `depth` guard (the
404    /// number of containers enclosing `self`); a container past
405    /// [`MAX_VALUE_DEPTH`] renders [`DEPTH_LIMIT_MARKER`].
406    fn to_display_string_at(&self, depth: u32) -> String {
407        match self {
408            Value::Null => "null".into(),
409            Value::Bool(b) => b.to_string(),
410            Value::Int(i) => i.to_string(),
411            Value::Float(f) => float_literal(*f),
412            // Unquoted: Neo4j 2026.09.0 renders toString({a:'x y'}) as
413            // "{a: x y}".
414            Value::String(s) => String::from(&**s),
415            Value::Bytes(b) => bytes_as_int_list(b),
416            Value::List(xs) => {
417                let Some(next) = next_depth(depth) else {
418                    return DEPTH_LIMIT_MARKER.into();
419                };
420                let inner: Vec<_> = xs.iter().map(|v| v.to_display_string_at(next)).collect();
421                format!("[{}]", inner.join(", "))
422            }
423            // A key outside the plain identifier shape is backticked
424            // (CIP-271: `{`123`: digit key, `a.b`: dot, `first name`:
425            // Alice}`); the map's own iteration order is already the
426            // sorted one.
427            Value::Map(m) => {
428                let Some(next) = next_depth(depth) else {
429                    return DEPTH_LIMIT_MARKER.into();
430                };
431                let inner: Vec<_> = m
432                    .iter()
433                    .map(|(k, v)| {
434                        format!(
435                            "{}: {}",
436                            quote_identifier_shaped(k),
437                            v.to_display_string_at(next)
438                        )
439                    })
440                    .collect();
441                format!("{{{}}}", inner.join(", "))
442            }
443            Value::Node(n) => node_display(n),
444            Value::Relationship(r) => relationship_display(r),
445            // No depth: the display walk renders no properties, so it never
446            // recurses and has no ADR-0462 budget to thread.
447            Value::Path(p) => p.display_string(),
448            Value::Temporal(t) => t.full_seconds_string(),
449            // Bare hyphenated string (verified on 2026.09.0).
450            Value::Uuid(u) => uuid_hyphenated(*u),
451            Value::Point(pt) => point_display(pt),
452            Value::Vector { coord, values } => {
453                let Some(next) = next_depth(depth) else {
454                    return DEPTH_LIMIT_MARKER.into();
455                };
456                let inner: Vec<_> = values
457                    .iter()
458                    .map(|v| v.to_display_string_at(next))
459                    .collect();
460                vector_text(&inner, *coord)
461            }
462        }
463    }
464}
465
466/// One component accessor of a point (`p.x`, `p.longitude`, `p.crs`, …) —
467/// the one point-accessor vocabulary, the data-model sibling of the
468/// temporal accessor ([`crate::temporal::Temporal::component`]): a key no
469/// component names is the same typed rejection the temporal reader answers,
470/// never a silently null read. The coordinate aliases (`x` is `longitude`)
471/// are the shared axis vocabulary beside [`PointValue`].
472///
473/// Which axis spellings a point exposes is live Neo4j 2026.10.1's rule
474/// (probed 2026-11-11): a cartesian point has only the cartesian
475/// spellings (`x`/`y`/`z`), a geographic point accepts both (`x` and
476/// `longitude`, …), and the third axis exists only on a 3D point. An
477/// unavailable spelling is `ArgumentError` "Field: <key> is not
478/// available", not a null read.
479pub fn point_component(p: &PointValue, key: &str) -> Result<Value, Error> {
480    let name = key.to_ascii_lowercase();
481    Ok(match name.as_str() {
482        "srid" => Value::Int(i64::from(p.srid)),
483        // The canonical CRS spelling; a decoder-supplied srid/dimensionality
484        // pair outside the four canonical codes keeps the srid table's
485        // spelling rather than claiming no CRS.
486        "crs" => Value::String(
487            p.crs_name()
488                .unwrap_or_else(|| relate_model::wire::crs_name(p.srid))
489                .into(),
490        ),
491        _ => {
492            let Some(axis) = relate_model::point::point_axis(&name) else {
493                // 22G03 invalid argument, not a runtime TypeError.
494                return Err(Error::argument_error(format!(
495                    "no such component '{key}' on a point value"
496                )));
497            };
498            // A cartesian point has no geographic spelling; any point has
499            // the third axis only when it is 3D (`p.z` is its presence).
500            let cartesian = !relate_model::point::is_geographic(p.srid);
501            let unavailable =
502                (cartesian && axis.key(true) == name) || (axis.index == 2 && p.z.is_none());
503            if unavailable {
504                return Err(Error::argument_error(format!(
505                    "Field: {key} is not available on a point value"
506                )));
507            }
508            match axis.index {
509                0 => Value::Float(p.x),
510                1 => Value::Float(p.y),
511                _ => Value::Float(p.z.expect("the 3D check admitted only a present z")),
512            }
513        }
514    })
515}
516
517/// The Neo4j text form of a point (the CIP-271 display policy `toString()`
518/// and string concatenation use): `point({x: 1.0, y: 2.0, crs:
519/// 'cartesian'})`. Coordinates render through the float-literal policy (so
520/// an integral coordinate keeps its `.0`), a 3D point adds `z`, and the CRS
521/// name comes from [`PointValue::crs_name`]. A srid/dimensionality pair
522/// outside the four `point()` codes — only reachable from a decoder, never
523/// from `point()` — renders the srid spelling rather than claiming a CRS
524/// the value does not have.
525fn point_display(p: &PointValue) -> String {
526    let coord = |value: f64| Value::Float(value).to_cypher_literal();
527    match (p.crs_name(), p.z) {
528        (Some(crs), Some(z)) => format!(
529            "point({{x: {}, y: {}, z: {}, crs: '{crs}'}})",
530            coord(p.x),
531            coord(p.y),
532            coord(z)
533        ),
534        (Some(crs), None) => format!(
535            "point({{x: {}, y: {}, crs: '{crs}'}})",
536            coord(p.x),
537            coord(p.y)
538        ),
539        (None, Some(z)) => format!(
540            "point({{srid: {}, x: {}, y: {}, z: {}}})",
541            p.srid,
542            coord(p.x),
543            coord(p.y),
544            coord(z)
545        ),
546        (None, None) => format!(
547            "point({{srid: {}, x: {}, y: {}}})",
548            p.srid,
549            coord(p.x),
550            coord(p.y)
551        ),
552    }
553}
554
555/// The `vector([…], N, COORD)` text shape shared by the literal and
556/// display renderers; `elements` are the already-rendered coordinates.
557/// The round-trippable value-constructor form (CIP-271): a vector VALUE
558/// renders as `vector([1, 2], 2, INTEGER8)` — the coordinate type is the
559/// third argument, not a `NOT NULL`-suffixed type expression (that is the
560/// TYPE rendering's own path, e.g. `valueType()`).
561fn vector_text(elements: &[String], coord: VectorCoordKind) -> String {
562    format!(
563        "vector([{}], {}, {})",
564        elements.join(", "),
565        elements.len(),
566        coord.canonical_name()
567    )
568}
569
570impl Node {
571    pub fn to_cypher_literal(&self) -> String {
572        self.to_cypher_literal_at(0)
573    }
574
575    /// [`Node::to_cypher_literal`] with the ADR-0462 `depth` (the number of
576    /// containers enclosing this node).
577    fn to_cypher_literal_at(&self, depth: u32) -> String {
578        let Some(next) = next_depth(depth) else {
579            return DEPTH_LIMIT_MARKER.into();
580        };
581        let labels: String = self.labels.iter().map(|l| format!(":{l}")).collect();
582        let props = props_suffix(&self.properties, next);
583        format!("({labels}{props})")
584    }
585}
586
587impl Relationship {
588    pub fn to_cypher_literal(&self) -> String {
589        self.to_cypher_literal_at(0)
590    }
591
592    /// [`Relationship::to_cypher_literal`] with the ADR-0462 `depth`.
593    fn to_cypher_literal_at(&self, depth: u32) -> String {
594        let Some(next) = next_depth(depth) else {
595            return DEPTH_LIMIT_MARKER.into();
596        };
597        let props = props_suffix(&self.properties, next);
598        format!("[:{}{}]", self.rel_type, props)
599    }
600}
601
602impl Path {
603    pub fn to_cypher_literal(&self) -> String {
604        self.to_cypher_literal_at(0)
605    }
606
607    /// [`Path::to_cypher_literal`] with the ADR-0462 `depth`.
608    fn to_cypher_literal_at(&self, depth: u32) -> String {
609        // The path itself is the container (`depth + 1`); its embedded
610        // entities are not an extra level, so they get `depth`.
611        if next_depth(depth).is_none() {
612            return DEPTH_LIMIT_MARKER.into();
613        }
614        format!(
615            "<{}>",
616            self.walk(
617                |n| n.to_cypher_literal_at(depth),
618                |r| r.to_cypher_literal_at(depth)
619            )
620        )
621    }
622
623    /// The CIP-271 `toString()` form of a path: no enclosing `<…>` and no
624    /// properties — the same label-only / type-only element rendering a
625    /// standalone node or relationship gets (Neo4j 2026.10.1 renders
626    /// `toString(path)` as `(:A)-[:FIRST]->(:B)<-[:SECOND]-(:C)`). The
627    /// display walk renders no properties, so nothing recurses and no
628    /// depth budget applies — the literal twin's guard bounds its own
629    /// property-rendering recursion, not this walk.
630    fn display_string(&self) -> String {
631        self.walk(node_display, relationship_display)
632    }
633
634    /// The path's element chain — one node then, if the path continues past
635    /// it, the relationship traversed from it, with the arrows of the
636    /// direction actually stored. `node`/`rel` render one element, so the
637    /// literal and display walks share the direction policy.
638    fn walk(
639        &self,
640        node: impl Fn(&Node) -> String,
641        rel: impl Fn(&Relationship) -> String,
642    ) -> String {
643        let mut s = String::new();
644        for (i, n) in self.nodes.iter().enumerate() {
645            s.push_str(&node(n));
646            if let Some(r) = self.rels.get(i) {
647                // `rels[i]` connects `nodes[i]` and `nodes[i+1]`, so the
648                // arrow is the one bit that is always defined: which
649                // endpoint is the current node. A self-loop is outgoing.
650                let (left, right) = if r.start == n.id {
651                    ("-", "->")
652                } else {
653                    ("<-", "-")
654                };
655                s.push_str(&format!("{left}{}{right}", rel(r)));
656            }
657        }
658        s
659    }
660}
661
662/// Labels only, no properties, alphabetically (CIP-271): Neo4j 2026.09.0
663/// renders `toString(node-with-props)` as `(:X)` and a multi-label node as
664/// `(:A:B:C)` whatever the creation order.
665fn node_display(n: &Node) -> String {
666    let mut labels: Vec<&str> = n.labels.iter().map(String::as_str).collect();
667    labels.sort_unstable();
668    let labels: String = labels
669        .iter()
670        .map(|l| format!(":{}", quote_identifier_shaped(l)))
671        .collect();
672    format!("({labels})")
673}
674
675/// Type only, no properties (CIP-271), the relationship half of
676/// [`node_display`].
677fn relationship_display(r: &Relationship) -> String {
678    format!("[:{}]", quote_identifier_shaped(&r.rel_type))
679}
680
681impl fmt::Display for Value {
682    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
683        write!(f, "{}", self.to_cypher_literal())
684    }
685}
686
687/// Cypher has no byte-array literal: a [`Value::Bytes`] renders as the list
688/// of its byte values 0-255 (`[0, 1, 255]`), the same shape it crosses the
689/// `value_to_cypher` bridge in (ADR-0327).
690fn bytes_as_int_list(bytes: &[u8]) -> String {
691    let inner: Vec<_> = bytes.iter().map(u8::to_string).collect();
692    format!("[{}]", inner.join(", "))
693}
694
695fn escape_cypher_string(s: &str) -> String {
696    s.replace('\\', "\\\\").replace('\'', "\\'")
697}
698
699/// The ` {…}` property suffix shared by the node and relationship literal
700/// renderers (one owner for the policy and the ADR-0462 depth hand-off);
701/// empty when the entity has no properties. `depth` is the property values'
702/// enclosing-container count.
703fn props_suffix(props: &PropertyMap, depth: u32) -> String {
704    if props.is_empty() {
705        String::new()
706    } else {
707        format!(" {}", map_to_cypher_literal(props.iter(), depth))
708    }
709}
710
711fn map_to_cypher_literal<'a>(
712    m: impl IntoIterator<Item = (&'a String, &'a Value)>,
713    depth: u32,
714) -> String {
715    let inner: Vec<_> = m
716        .into_iter()
717        .map(|(k, v)| format!("{}: {}", k, v.to_cypher_literal_at(depth)))
718        .collect();
719    format!("{{{}}}", inner.join(", "))
720}
721
722/// Render a 128-bit UUID value as the canonical lowercase hyphenated
723/// string (8-4-4-4-12, CIP-246 / RFC 4122).
724pub fn uuid_hyphenated(u: u128) -> String {
725    let hex = format!("{u:032x}");
726    format!(
727        "{}-{}-{}-{}-{}",
728        &hex[0..8],
729        &hex[8..12],
730        &hex[12..16],
731        &hex[16..20],
732        &hex[20..32]
733    )
734}
735
736/// Parse an RFC-4122-shaped UUID string (case-insensitive, hyphens
737/// required, 8-4-4-4-12 groups) into its 128-bit value. `None` on any
738/// non-conforming input, mirroring Java's `UUID.fromString` strictness
739/// (CIP-246).
740pub fn uuid_parse(s: &str) -> Option<u128> {
741    // Allocation-free single pass over the original string: `to_digit(16)`
742    // accepts both hex cases, so no lowercasing or concatenation is needed.
743    // Strictness is unchanged -- exactly five groups of 8-4-4-4-12 hex digits
744    // separated by four hyphens, with nothing before or after.
745    const GROUP_LEN: [usize; 5] = [8, 4, 4, 4, 12];
746    let mut chars = s.chars();
747    let mut u: u128 = 0;
748    for (i, &len) in GROUP_LEN.iter().enumerate() {
749        if i > 0 && chars.next()? != '-' {
750            return None;
751        }
752        for _ in 0..len {
753            u = (u << 4) | chars.next()?.to_digit(16)? as u128;
754        }
755    }
756    if chars.next().is_some() {
757        return None;
758    }
759    Some(u)
760}
761
762#[cfg(test)]
763mod depth_tests;
764#[cfg(test)]
765mod point_tests;
766#[cfg(test)]
767mod tests;