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`].
472pub fn point_component(p: &PointValue, key: &str) -> Result<Value, Error> {
473    let name = key.to_ascii_lowercase();
474    Ok(match name.as_str() {
475        "srid" => Value::Int(i64::from(p.srid)),
476        // The canonical CRS spelling; a decoder-supplied srid/dimensionality
477        // pair outside the four canonical codes keeps the srid table's
478        // spelling rather than claiming no CRS.
479        "crs" => Value::String(
480            p.crs_name()
481                .unwrap_or_else(|| relate_model::wire::crs_name(p.srid))
482                .into(),
483        ),
484        _ => {
485            let Some(axis) = relate_model::point::point_axis(&name) else {
486                // 22G03 invalid argument, not a runtime TypeError.
487                return Err(Error::argument_error(format!(
488                    "no such component '{key}' on a point value"
489                )));
490            };
491            match axis.index {
492                0 => Value::Float(p.x),
493                1 => Value::Float(p.y),
494                _ => p.z.map(Value::Float).unwrap_or(Value::Null),
495            }
496        }
497    })
498}
499
500/// The Neo4j text form of a point (the CIP-271 display policy `toString()`
501/// and string concatenation use): `point({x: 1.0, y: 2.0, crs:
502/// 'cartesian'})`. Coordinates render through the float-literal policy (so
503/// an integral coordinate keeps its `.0`), a 3D point adds `z`, and the CRS
504/// name comes from [`PointValue::crs_name`]. A srid/dimensionality pair
505/// outside the four `point()` codes — only reachable from a decoder, never
506/// from `point()` — renders the srid spelling rather than claiming a CRS
507/// the value does not have.
508fn point_display(p: &PointValue) -> String {
509    let coord = |value: f64| Value::Float(value).to_cypher_literal();
510    match (p.crs_name(), p.z) {
511        (Some(crs), Some(z)) => format!(
512            "point({{x: {}, y: {}, z: {}, crs: '{crs}'}})",
513            coord(p.x),
514            coord(p.y),
515            coord(z)
516        ),
517        (Some(crs), None) => format!(
518            "point({{x: {}, y: {}, crs: '{crs}'}})",
519            coord(p.x),
520            coord(p.y)
521        ),
522        (None, Some(z)) => format!(
523            "point({{srid: {}, x: {}, y: {}, z: {}}})",
524            p.srid,
525            coord(p.x),
526            coord(p.y),
527            coord(z)
528        ),
529        (None, None) => format!(
530            "point({{srid: {}, x: {}, y: {}}})",
531            p.srid,
532            coord(p.x),
533            coord(p.y)
534        ),
535    }
536}
537
538/// The `vector([…], N, COORD)` text shape shared by the literal and
539/// display renderers; `elements` are the already-rendered coordinates.
540/// The round-trippable value-constructor form (CIP-271): a vector VALUE
541/// renders as `vector([1, 2], 2, INTEGER8)` — the coordinate type is the
542/// third argument, not a `NOT NULL`-suffixed type expression (that is the
543/// TYPE rendering's own path, e.g. `valueType()`).
544fn vector_text(elements: &[String], coord: VectorCoordKind) -> String {
545    format!(
546        "vector([{}], {}, {})",
547        elements.join(", "),
548        elements.len(),
549        coord.canonical_name()
550    )
551}
552
553impl Node {
554    pub fn to_cypher_literal(&self) -> String {
555        self.to_cypher_literal_at(0)
556    }
557
558    /// [`Node::to_cypher_literal`] with the ADR-0462 `depth` (the number of
559    /// containers enclosing this node).
560    fn to_cypher_literal_at(&self, depth: u32) -> String {
561        let Some(next) = next_depth(depth) else {
562            return DEPTH_LIMIT_MARKER.into();
563        };
564        let labels: String = self.labels.iter().map(|l| format!(":{l}")).collect();
565        let props = props_suffix(&self.properties, next);
566        format!("({labels}{props})")
567    }
568}
569
570impl Relationship {
571    pub fn to_cypher_literal(&self) -> String {
572        self.to_cypher_literal_at(0)
573    }
574
575    /// [`Relationship::to_cypher_literal`] with the ADR-0462 `depth`.
576    fn to_cypher_literal_at(&self, depth: u32) -> String {
577        let Some(next) = next_depth(depth) else {
578            return DEPTH_LIMIT_MARKER.into();
579        };
580        let props = props_suffix(&self.properties, next);
581        format!("[:{}{}]", self.rel_type, props)
582    }
583}
584
585impl Path {
586    pub fn to_cypher_literal(&self) -> String {
587        self.to_cypher_literal_at(0)
588    }
589
590    /// [`Path::to_cypher_literal`] with the ADR-0462 `depth`.
591    fn to_cypher_literal_at(&self, depth: u32) -> String {
592        // The path itself is the container (`depth + 1`); its embedded
593        // entities are not an extra level, so they get `depth`.
594        if next_depth(depth).is_none() {
595            return DEPTH_LIMIT_MARKER.into();
596        }
597        format!(
598            "<{}>",
599            self.walk(
600                |n| n.to_cypher_literal_at(depth),
601                |r| r.to_cypher_literal_at(depth)
602            )
603        )
604    }
605
606    /// The CIP-271 `toString()` form of a path: no enclosing `<…>` and no
607    /// properties — the same label-only / type-only element rendering a
608    /// standalone node or relationship gets (Neo4j 2026.10.1 renders
609    /// `toString(path)` as `(:A)-[:FIRST]->(:B)<-[:SECOND]-(:C)`). The
610    /// display walk renders no properties, so nothing recurses and no
611    /// depth budget applies — the literal twin's guard bounds its own
612    /// property-rendering recursion, not this walk.
613    fn display_string(&self) -> String {
614        self.walk(node_display, relationship_display)
615    }
616
617    /// The path's element chain — one node then, if the path continues past
618    /// it, the relationship traversed from it, with the arrows of the
619    /// direction actually stored. `node`/`rel` render one element, so the
620    /// literal and display walks share the direction policy.
621    fn walk(
622        &self,
623        node: impl Fn(&Node) -> String,
624        rel: impl Fn(&Relationship) -> String,
625    ) -> String {
626        let mut s = String::new();
627        for (i, n) in self.nodes.iter().enumerate() {
628            s.push_str(&node(n));
629            if let Some(r) = self.rels.get(i) {
630                // `rels[i]` connects `nodes[i]` and `nodes[i+1]`, so the
631                // arrow is the one bit that is always defined: which
632                // endpoint is the current node. A self-loop is outgoing.
633                let (left, right) = if r.start == n.id {
634                    ("-", "->")
635                } else {
636                    ("<-", "-")
637                };
638                s.push_str(&format!("{left}{}{right}", rel(r)));
639            }
640        }
641        s
642    }
643}
644
645/// Labels only, no properties, alphabetically (CIP-271): Neo4j 2026.09.0
646/// renders `toString(node-with-props)` as `(:X)` and a multi-label node as
647/// `(:A:B:C)` whatever the creation order.
648fn node_display(n: &Node) -> String {
649    let mut labels: Vec<&str> = n.labels.iter().map(String::as_str).collect();
650    labels.sort_unstable();
651    let labels: String = labels
652        .iter()
653        .map(|l| format!(":{}", quote_identifier_shaped(l)))
654        .collect();
655    format!("({labels})")
656}
657
658/// Type only, no properties (CIP-271), the relationship half of
659/// [`node_display`].
660fn relationship_display(r: &Relationship) -> String {
661    format!("[:{}]", quote_identifier_shaped(&r.rel_type))
662}
663
664impl fmt::Display for Value {
665    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
666        write!(f, "{}", self.to_cypher_literal())
667    }
668}
669
670/// Cypher has no byte-array literal: a [`Value::Bytes`] renders as the list
671/// of its byte values 0-255 (`[0, 1, 255]`), the same shape it crosses the
672/// `value_to_cypher` bridge in (ADR-0327).
673fn bytes_as_int_list(bytes: &[u8]) -> String {
674    let inner: Vec<_> = bytes.iter().map(u8::to_string).collect();
675    format!("[{}]", inner.join(", "))
676}
677
678fn escape_cypher_string(s: &str) -> String {
679    s.replace('\\', "\\\\").replace('\'', "\\'")
680}
681
682/// The ` {…}` property suffix shared by the node and relationship literal
683/// renderers (one owner for the policy and the ADR-0462 depth hand-off);
684/// empty when the entity has no properties. `depth` is the property values'
685/// enclosing-container count.
686fn props_suffix(props: &PropertyMap, depth: u32) -> String {
687    if props.is_empty() {
688        String::new()
689    } else {
690        format!(" {}", map_to_cypher_literal(props.iter(), depth))
691    }
692}
693
694fn map_to_cypher_literal<'a>(
695    m: impl IntoIterator<Item = (&'a String, &'a Value)>,
696    depth: u32,
697) -> String {
698    let inner: Vec<_> = m
699        .into_iter()
700        .map(|(k, v)| format!("{}: {}", k, v.to_cypher_literal_at(depth)))
701        .collect();
702    format!("{{{}}}", inner.join(", "))
703}
704
705/// Render a 128-bit UUID value as the canonical lowercase hyphenated
706/// string (8-4-4-4-12, CIP-246 / RFC 4122).
707pub fn uuid_hyphenated(u: u128) -> String {
708    let hex = format!("{u:032x}");
709    format!(
710        "{}-{}-{}-{}-{}",
711        &hex[0..8],
712        &hex[8..12],
713        &hex[12..16],
714        &hex[16..20],
715        &hex[20..32]
716    )
717}
718
719/// Parse an RFC-4122-shaped UUID string (case-insensitive, hyphens
720/// required, 8-4-4-4-12 groups) into its 128-bit value. `None` on any
721/// non-conforming input, mirroring Java's `UUID.fromString` strictness
722/// (CIP-246).
723pub fn uuid_parse(s: &str) -> Option<u128> {
724    // Allocation-free single pass over the original string: `to_digit(16)`
725    // accepts both hex cases, so no lowercasing or concatenation is needed.
726    // Strictness is unchanged -- exactly five groups of 8-4-4-4-12 hex digits
727    // separated by four hyphens, with nothing before or after.
728    const GROUP_LEN: [usize; 5] = [8, 4, 4, 4, 12];
729    let mut chars = s.chars();
730    let mut u: u128 = 0;
731    for (i, &len) in GROUP_LEN.iter().enumerate() {
732        if i > 0 && chars.next()? != '-' {
733            return None;
734        }
735        for _ in 0..len {
736            u = (u << 4) | chars.next()?.to_digit(16)? as u128;
737        }
738    }
739    if chars.next().is_some() {
740        return None;
741    }
742    Some(u)
743}
744
745#[cfg(test)]
746mod depth_tests;
747#[cfg(test)]
748mod tests;