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
170impl Value {
171    /// Share one node across every row that clones this value.
172    pub fn from_node(node: Node) -> Self {
173        Value::Node(Arc::new(node))
174    }
175
176    /// Share one relationship across every row that clones this value.
177    pub fn from_relationship(rel: Relationship) -> Self {
178        Value::Relationship(Arc::new(rel))
179    }
180
181    /// Share one path across every row that clones this value.
182    pub fn from_path(path: Path) -> Self {
183        Value::Path(Arc::new(path))
184    }
185
186    /// Documented logical payload size (ADR-0042) — the per-variant
187    /// accumulation of the sizes [`str_logical_bytes`] spells for
188    /// strings.
189    pub fn logical_bytes(&self) -> u64 {
190        let mut total = 0;
191        let flow = self.add_logical_bytes(&mut total, u64::MAX, 0);
192        // The byte budget is `u64::MAX`, so the only reachable `Break` is
193        // the ADR-0462 depth guard: were it to fire (unreachable behind the
194        // checked constructors) the result would be the partial sum counted
195        // down to the cap rather than a panic, since this walk has no error
196        // channel.
197        debug_assert!(
198            flow.is_continue(),
199            "logical_bytes broke on the ADR-0462 depth guard at the cap"
200        );
201        total
202    }
203
204    /// The single implementation of the ADR-0042 formula, shared by
205    /// [`Value::logical_bytes`] (budget `u64::MAX`, never breaks) and
206    /// [`logical_bytes_within`]: adds this value's logical bytes to `acc`
207    /// and breaks as soon as `acc` exceeds `budget`.
208    ///
209    /// `depth` is the level of the container whose contents are being
210    /// added; past [`MAX_VALUE_DEPTH`] the walk breaks (ADR-0462). The
211    /// guard is unreachable behind the checked constructors and only keeps
212    /// an over-deep value from recursing without a byte budget to stop it.
213    fn add_logical_bytes(&self, acc: &mut u64, budget: u64, depth: u32) -> ControlFlow<()> {
214        match self {
215            Value::Null | Value::Bool(_) => add_bytes(acc, 1, budget),
216            Value::Int(_) | Value::Float(_) => add_bytes(acc, 8, budget),
217            Value::String(s) => add_str_bytes(s, acc, budget),
218            Value::Bytes(b) => add_payload_bytes(b, acc, budget),
219            Value::List(xs) | Value::Vector { values: xs, .. } => {
220                let Some(next) = next_depth(depth) else {
221                    return ControlFlow::Break(());
222                };
223                add_bytes(acc, 16, budget)?;
224                xs.iter()
225                    .try_for_each(|x| x.add_logical_bytes(acc, budget, next))
226            }
227            Value::Map(m) => {
228                let Some(next) = next_depth(depth) else {
229                    return ControlFlow::Break(());
230                };
231                add_bytes(acc, 16, budget)?;
232                add_property_bytes(m.iter(), acc, budget, next)
233            }
234            Value::Node(n) => {
235                let Some(next) = next_depth(depth) else {
236                    return ControlFlow::Break(());
237                };
238                add_node_bytes(n, acc, budget, next)
239            }
240            Value::Relationship(r) => {
241                let Some(next) = next_depth(depth) else {
242                    return ControlFlow::Break(());
243                };
244                add_rel_bytes(r, acc, budget, next)
245            }
246            Value::Path(p) => {
247                let Some(next) = next_depth(depth) else {
248                    return ControlFlow::Break(());
249                };
250                p.nodes
251                    .iter()
252                    .try_for_each(|n| add_node_bytes(n, acc, budget, next))?;
253                p.rels
254                    .iter()
255                    .try_for_each(|r| add_rel_bytes(r, acc, budget, next))
256            }
257            Value::Temporal(_) => add_bytes(acc, 24, budget),
258            Value::Point(_) => add_bytes(acc, 32, budget),
259            Value::Uuid(_) => add_bytes(acc, 16, budget),
260        }
261    }
262
263    pub fn as_temporal(&self) -> Option<&Temporal> {
264        match self {
265            Value::Temporal(t) => Some(t),
266            _ => None,
267        }
268    }
269
270    pub fn as_string(&self) -> Option<&str> {
271        match self {
272            Value::String(s) => Some(&**s),
273            _ => None,
274        }
275    }
276
277    pub fn is_null(&self) -> bool {
278        matches!(self, Value::Null)
279    }
280
281    pub fn as_bool(&self) -> Option<bool> {
282        match self {
283            Value::Bool(b) => Some(*b),
284            _ => None,
285        }
286    }
287
288    /// Cypher toBoolean-ish: true/false stay, null stays none.
289    pub fn truthy(&self) -> Option<bool> {
290        match self {
291            Value::Bool(b) => Some(*b),
292            Value::Null => None,
293            _ => None,
294        }
295    }
296
297    pub fn as_number(&self) -> Option<f64> {
298        match self {
299            Value::Int(i) => Some(*i as f64),
300            Value::Float(f) => Some(*f),
301            _ => None,
302        }
303    }
304
305    pub fn as_int(&self) -> Option<i64> {
306        match self {
307            Value::Int(i) => Some(*i),
308            Value::Float(f)
309                if f.fract() == 0.0 && *f >= i64::MIN as f64 && *f <= i64::MAX as f64 =>
310            {
311                Some(*f as i64)
312            }
313            _ => None,
314        }
315    }
316
317    pub fn to_cypher_literal(&self) -> String {
318        self.to_cypher_literal_at(0)
319    }
320
321    /// [`Value::to_cypher_literal`] with the ADR-0462 depth guard: a
322    /// container past [`MAX_VALUE_DEPTH`] renders
323    /// [`DEPTH_LIMIT_MARKER`] instead of recursing. `depth` is the number of
324    /// containers enclosing `self`, so a root is 0 and its children 1.
325    fn to_cypher_literal_at(&self, depth: u32) -> String {
326        match self {
327            Value::Null => "null".into(),
328            Value::Bool(true) => "true".into(),
329            Value::Bool(false) => "false".into(),
330            Value::Int(i) => i.to_string(),
331            Value::Float(f) => relate_model::value::float_text(*f),
332            Value::String(s) => format!("'{}'", escape_cypher_string(s)),
333            Value::Bytes(b) => bytes_as_int_list(b),
334            Value::List(xs) => {
335                let Some(next) = next_depth(depth) else {
336                    return DEPTH_LIMIT_MARKER.into();
337                };
338                let inner: Vec<_> = xs.iter().map(|v| v.to_cypher_literal_at(next)).collect();
339                format!("[{}]", inner.join(", "))
340            }
341            Value::Map(m) => {
342                let Some(next) = next_depth(depth) else {
343                    return DEPTH_LIMIT_MARKER.into();
344                };
345                map_to_cypher_literal(m.iter(), next)
346            }
347            Value::Node(n) => n.to_cypher_literal_at(depth),
348            Value::Relationship(r) => r.to_cypher_literal_at(depth),
349            Value::Path(p) => p.to_cypher_literal_at(depth),
350            Value::Temporal(t) => format!("'{}'", escape_cypher_string(&t.iso_string())),
351            // Round-trippable form like VECTOR: uuid('...') (CIP-246).
352            Value::Uuid(u) => format!("uuid('{}')", uuid_hyphenated(*u)),
353            Value::Point(p) => p.to_string(),
354            Value::Vector { coord, values } => {
355                let Some(next) = next_depth(depth) else {
356                    return DEPTH_LIMIT_MARKER.into();
357                };
358                let inner = values
359                    .iter()
360                    .map(|value| value.to_cypher_literal_at(next))
361                    .collect::<Vec<_>>();
362                vector_text(&inner, *coord)
363            }
364        }
365    }
366
367    /// The CIP-271 `toString()` rendering: the cypher-shell display form
368    /// rather than the round-trippable literal form — strings are unquoted,
369    /// temporals are bare full-precision ISO strings (ADR-0448), and
370    /// maps/lists render recursively with `, ` separators (verified
371    /// against Neo4j 2026.09.0).
372    pub fn to_display_string(&self) -> String {
373        self.to_display_string_at(0)
374    }
375
376    /// [`Value::to_display_string`] with the ADR-0462 `depth` guard (the
377    /// number of containers enclosing `self`); a container past
378    /// [`MAX_VALUE_DEPTH`] renders [`DEPTH_LIMIT_MARKER`].
379    fn to_display_string_at(&self, depth: u32) -> String {
380        match self {
381            Value::Null => "null".into(),
382            Value::Bool(b) => b.to_string(),
383            Value::Int(i) => i.to_string(),
384            Value::Float(f) => relate_model::value::float_text(*f),
385            // Unquoted: Neo4j 2026.09.0 renders toString({a:'x y'}) as
386            // "{a: x y}".
387            Value::String(s) => String::from(&**s),
388            Value::Bytes(b) => bytes_as_int_list(b),
389            Value::List(xs) => {
390                let Some(next) = next_depth(depth) else {
391                    return DEPTH_LIMIT_MARKER.into();
392                };
393                let inner: Vec<_> = xs.iter().map(|v| v.to_display_string_at(next)).collect();
394                format!("[{}]", inner.join(", "))
395            }
396            // A key outside the plain identifier shape is backticked
397            // (CIP-271: `{`123`: digit key, `a.b`: dot, `first name`:
398            // Alice}`); the map's own iteration order is already the
399            // sorted one.
400            Value::Map(m) => {
401                let Some(next) = next_depth(depth) else {
402                    return DEPTH_LIMIT_MARKER.into();
403                };
404                let inner: Vec<_> = m
405                    .iter()
406                    .map(|(k, v)| {
407                        format!(
408                            "{}: {}",
409                            quote_identifier_shaped(k),
410                            v.to_display_string_at(next)
411                        )
412                    })
413                    .collect();
414                format!("{{{}}}", inner.join(", "))
415            }
416            Value::Node(n) => node_display(n),
417            Value::Relationship(r) => relationship_display(r),
418            // No depth: the display walk renders no properties, so it never
419            // recurses and has no ADR-0462 budget to thread.
420            Value::Path(p) => p.display_string(),
421            Value::Temporal(t) => t.full_seconds_string(),
422            // Bare hyphenated string (verified on 2026.09.0).
423            Value::Uuid(u) => uuid_hyphenated(*u),
424            Value::Point(pt) => point_display(pt),
425            Value::Vector { coord, values } => {
426                let Some(next) = next_depth(depth) else {
427                    return DEPTH_LIMIT_MARKER.into();
428                };
429                let inner: Vec<_> = values
430                    .iter()
431                    .map(|v| v.to_display_string_at(next))
432                    .collect();
433                vector_text(&inner, *coord)
434            }
435        }
436    }
437}
438
439/// One component accessor of a point (`p.x`, `p.longitude`, `p.crs`, …) —
440/// the one point-accessor vocabulary, the data-model sibling of the
441/// temporal accessor ([`crate::temporal::Temporal::component`]): a key no
442/// component names is the same typed rejection the temporal reader answers,
443/// never a silently null read. The coordinate aliases (`x` is `longitude`)
444/// are the shared axis vocabulary beside [`PointValue`].
445///
446/// Which axis spellings a point exposes is live Neo4j 2026.10.1's rule
447/// (probed 2026-11-11): a cartesian point has only the cartesian
448/// spellings (`x`/`y`/`z`), a geographic point accepts both (`x` and
449/// `longitude`, …), and the third axis exists only on a 3D point. An
450/// unavailable spelling is `ArgumentError` "Field: <key> is not
451/// available", not a null read.
452pub fn point_component(p: &PointValue, key: &str) -> Result<Value, Error> {
453    let name = key.to_ascii_lowercase();
454    Ok(match name.as_str() {
455        "srid" => Value::Int(i64::from(p.srid)),
456        // The canonical CRS spelling; a decoder-supplied srid/dimensionality
457        // pair outside the four canonical codes keeps the srid table's
458        // spelling rather than claiming no CRS.
459        "crs" => Value::String(
460            p.crs_name()
461                .unwrap_or_else(|| relate_model::wire::crs_name(p.srid))
462                .into(),
463        ),
464        _ => {
465            let Some(axis) = relate_model::point::point_axis(&name) else {
466                // 22G03 invalid argument, not a runtime TypeError.
467                return Err(Error::argument_error(format!(
468                    "no such component '{key}' on a point value"
469                )));
470            };
471            // A cartesian point has no geographic spelling; any point has
472            // the third axis only when it is 3D (`p.z` is its presence).
473            let cartesian = !relate_model::point::is_geographic(p.srid);
474            let unavailable =
475                (cartesian && axis.key(true) == name) || (axis.index == 2 && p.z.is_none());
476            if unavailable {
477                return Err(Error::argument_error(format!(
478                    "Field: {key} is not available on a point value"
479                )));
480            }
481            match axis.index {
482                0 => Value::Float(p.x),
483                1 => Value::Float(p.y),
484                _ => Value::Float(p.z.expect("the 3D check admitted only a present z")),
485            }
486        }
487    })
488}
489
490/// The Neo4j text form of a point (the CIP-271 display policy `toString()`
491/// and string concatenation use): `point({x: 1.0, y: 2.0, crs:
492/// 'cartesian'})`. Coordinates render through the float-literal policy (so
493/// an integral coordinate keeps its `.0`), a 3D point adds `z`, and the CRS
494/// name comes from [`PointValue::crs_name`]. A srid/dimensionality pair
495/// outside the four `point()` codes — only reachable from a decoder, never
496/// from `point()` — renders the srid spelling rather than claiming a CRS
497/// the value does not have.
498fn point_display(p: &PointValue) -> String {
499    let coord = |value: f64| Value::Float(value).to_cypher_literal();
500    match (p.crs_name(), p.z) {
501        (Some(crs), Some(z)) => format!(
502            "point({{x: {}, y: {}, z: {}, crs: '{crs}'}})",
503            coord(p.x),
504            coord(p.y),
505            coord(z)
506        ),
507        (Some(crs), None) => format!(
508            "point({{x: {}, y: {}, crs: '{crs}'}})",
509            coord(p.x),
510            coord(p.y)
511        ),
512        (None, Some(z)) => format!(
513            "point({{srid: {}, x: {}, y: {}, z: {}}})",
514            p.srid,
515            coord(p.x),
516            coord(p.y),
517            coord(z)
518        ),
519        (None, None) => format!(
520            "point({{srid: {}, x: {}, y: {}}})",
521            p.srid,
522            coord(p.x),
523            coord(p.y)
524        ),
525    }
526}
527
528/// The `vector([…], N, COORD)` text shape shared by the literal and
529/// display renderers; `elements` are the already-rendered coordinates.
530/// The round-trippable value-constructor form (CIP-271): a vector VALUE
531/// renders as `vector([1, 2], 2, INTEGER8)` — the coordinate type is the
532/// third argument, not a `NOT NULL`-suffixed type expression (that is the
533/// TYPE rendering's own path, e.g. `valueType()`).
534fn vector_text(elements: &[String], coord: VectorCoordKind) -> String {
535    format!(
536        "vector([{}], {}, {})",
537        elements.join(", "),
538        elements.len(),
539        coord.canonical_name()
540    )
541}
542
543impl Node {
544    pub fn to_cypher_literal(&self) -> String {
545        self.to_cypher_literal_at(0)
546    }
547
548    /// [`Node::to_cypher_literal`] with the ADR-0462 `depth` (the number of
549    /// containers enclosing this node).
550    fn to_cypher_literal_at(&self, depth: u32) -> String {
551        let Some(next) = next_depth(depth) else {
552            return DEPTH_LIMIT_MARKER.into();
553        };
554        let labels: String = self.labels.iter().map(|l| format!(":{l}")).collect();
555        let props = props_suffix(&self.properties, next);
556        format!("({labels}{props})")
557    }
558}
559
560impl Relationship {
561    pub fn to_cypher_literal(&self) -> String {
562        self.to_cypher_literal_at(0)
563    }
564
565    /// [`Relationship::to_cypher_literal`] with the ADR-0462 `depth`.
566    fn to_cypher_literal_at(&self, depth: u32) -> String {
567        let Some(next) = next_depth(depth) else {
568            return DEPTH_LIMIT_MARKER.into();
569        };
570        let props = props_suffix(&self.properties, next);
571        format!("[:{}{}]", self.rel_type, props)
572    }
573}
574
575impl Path {
576    pub fn to_cypher_literal(&self) -> String {
577        self.to_cypher_literal_at(0)
578    }
579
580    /// [`Path::to_cypher_literal`] with the ADR-0462 `depth`.
581    fn to_cypher_literal_at(&self, depth: u32) -> String {
582        // The path itself is the container (`depth + 1`); its embedded
583        // entities are not an extra level, so they get `depth`.
584        if next_depth(depth).is_none() {
585            return DEPTH_LIMIT_MARKER.into();
586        }
587        format!(
588            "<{}>",
589            self.walk(
590                |n| n.to_cypher_literal_at(depth),
591                |r| r.to_cypher_literal_at(depth)
592            )
593        )
594    }
595
596    /// The CIP-271 `toString()` form of a path: no enclosing `<…>` and no
597    /// properties — the same label-only / type-only element rendering a
598    /// standalone node or relationship gets (Neo4j 2026.10.1 renders
599    /// `toString(path)` as `(:A)-[:FIRST]->(:B)<-[:SECOND]-(:C)`). The
600    /// display walk renders no properties, so nothing recurses and no
601    /// depth budget applies — the literal twin's guard bounds its own
602    /// property-rendering recursion, not this walk.
603    fn display_string(&self) -> String {
604        self.walk(node_display, relationship_display)
605    }
606
607    /// The path's element chain — one node then, if the path continues past
608    /// it, the relationship traversed from it, with the arrows of the
609    /// direction actually stored. `node`/`rel` render one element, so the
610    /// literal and display walks share the direction policy.
611    fn walk(
612        &self,
613        node: impl Fn(&Node) -> String,
614        rel: impl Fn(&Relationship) -> String,
615    ) -> String {
616        let mut s = String::new();
617        for (i, n) in self.nodes.iter().enumerate() {
618            s.push_str(&node(n));
619            if let Some(r) = self.rels.get(i) {
620                // `rels[i]` connects `nodes[i]` and `nodes[i+1]`, so the
621                // arrow is the one bit that is always defined: which
622                // endpoint is the current node. A self-loop is outgoing.
623                let (left, right) = if r.start == n.id {
624                    ("-", "->")
625                } else {
626                    ("<-", "-")
627                };
628                s.push_str(&format!("{left}{}{right}", rel(r)));
629            }
630        }
631        s
632    }
633}
634
635/// Labels only, no properties, alphabetically (CIP-271): Neo4j 2026.09.0
636/// renders `toString(node-with-props)` as `(:X)` and a multi-label node as
637/// `(:A:B:C)` whatever the creation order.
638fn node_display(n: &Node) -> String {
639    let mut labels: Vec<&str> = n.labels.iter().map(String::as_str).collect();
640    labels.sort_unstable();
641    let labels: String = labels
642        .iter()
643        .map(|l| format!(":{}", quote_identifier_shaped(l)))
644        .collect();
645    format!("({labels})")
646}
647
648/// Type only, no properties (CIP-271), the relationship half of
649/// [`node_display`].
650fn relationship_display(r: &Relationship) -> String {
651    format!("[:{}]", quote_identifier_shaped(&r.rel_type))
652}
653
654impl fmt::Display for Value {
655    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
656        write!(f, "{}", self.to_cypher_literal())
657    }
658}
659
660/// Cypher has no byte-array literal: a [`Value::Bytes`] renders as the list
661/// of its byte values 0-255 (`[0, 1, 255]`), the same shape it crosses the
662/// `value_to_cypher` bridge in (ADR-0327).
663fn bytes_as_int_list(bytes: &[u8]) -> String {
664    let inner: Vec<_> = bytes.iter().map(u8::to_string).collect();
665    format!("[{}]", inner.join(", "))
666}
667
668fn escape_cypher_string(s: &str) -> String {
669    s.replace('\\', "\\\\").replace('\'', "\\'")
670}
671
672/// The ` {…}` property suffix shared by the node and relationship literal
673/// renderers (one owner for the policy and the ADR-0462 depth hand-off);
674/// empty when the entity has no properties. `depth` is the property values'
675/// enclosing-container count.
676fn props_suffix(props: &PropertyMap, depth: u32) -> String {
677    if props.is_empty() {
678        String::new()
679    } else {
680        format!(" {}", map_to_cypher_literal(props.iter(), depth))
681    }
682}
683
684fn map_to_cypher_literal<'a>(
685    m: impl IntoIterator<Item = (&'a String, &'a Value)>,
686    depth: u32,
687) -> String {
688    let inner: Vec<_> = m
689        .into_iter()
690        .map(|(k, v)| format!("{}: {}", k, v.to_cypher_literal_at(depth)))
691        .collect();
692    format!("{{{}}}", inner.join(", "))
693}
694
695/// Render a 128-bit UUID value as the canonical lowercase hyphenated
696/// string (8-4-4-4-12, CIP-246 / RFC 4122).
697pub fn uuid_hyphenated(u: u128) -> String {
698    let hex = format!("{u:032x}");
699    format!(
700        "{}-{}-{}-{}-{}",
701        &hex[0..8],
702        &hex[8..12],
703        &hex[12..16],
704        &hex[16..20],
705        &hex[20..32]
706    )
707}
708
709/// Parse an RFC-4122-shaped UUID string (case-insensitive, hyphens
710/// required, 8-4-4-4-12 groups) into its 128-bit value. `None` on any
711/// non-conforming input, mirroring Java's `UUID.fromString` strictness
712/// (CIP-246).
713pub fn uuid_parse(s: &str) -> Option<u128> {
714    // Allocation-free single pass over the original string: `to_digit(16)`
715    // accepts both hex cases, so no lowercasing or concatenation is needed.
716    // Strictness is unchanged -- exactly five groups of 8-4-4-4-12 hex digits
717    // separated by four hyphens, with nothing before or after.
718    const GROUP_LEN: [usize; 5] = [8, 4, 4, 4, 12];
719    let mut chars = s.chars();
720    let mut u: u128 = 0;
721    for (i, &len) in GROUP_LEN.iter().enumerate() {
722        if i > 0 && chars.next()? != '-' {
723            return None;
724        }
725        for _ in 0..len {
726            u = (u << 4) | chars.next()?.to_digit(16)? as u128;
727        }
728    }
729    if chars.next().is_some() {
730        return None;
731    }
732    Some(u)
733}
734
735#[cfg(test)]
736mod depth_tests;
737#[cfg(test)]
738mod point_tests;
739#[cfg(test)]
740mod tests;