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