Skip to main content

relate_core/value/
pretty.rs

1//! Neo4j's `AnyValue.prettyPrint()`: the value rendering live Neo4j embeds
2//! in error text that echoes a call's inputs. Extracted from
3//! `value/mod.rs` for the file-size rule (the `depth.rs`/`ordering.rs`
4//! precedent); the method stays inherent, so no caller changes.
5//!
6//! Every shape below was probed 2026-11-27 on neo4j:2026.10.1-enterprise
7//! through `duration_between(<value>, 'abc')`, whose rejection renders the
8//! whole input list: scalars wrap as `Type(literal)` — `String("abc")`
9//! (raw, unescaped), `Long(123)`, `Double(1.500000e+00)`,
10//! `Boolean('true')` — containers wrap as `List{…}` / `Map{k -> v, …}`
11//! (sorted keys), entities print their bare ids — `(<id>)`, `-[<id>]-`,
12//! `Path{(0)-[<id>]-(1)}` — a byte array prints `ByteArray[120, 121]`, a
13//! UUID wraps its bare hyphenated form, and temporals and points print
14//! their display forms (`2021-01-01`, `point({x: 1.0, y: 2.0, crs:
15//! 'cartesian'})`), the same rendering [`Value::to_display_string`]
16//! carries.
17
18use super::{Coord, Node, Relationship, Value};
19
20impl Value {
21    /// Live Neo4j's `AnyValue.prettyPrint()`, the rendering its error
22    /// messages embed when they echo a call's input values (the
23    /// `Invalid call signature for …: Provided input was […]` family).
24    /// The rendering is probed live, not derived — see the module docs.
25    pub fn pretty_print(&self) -> String {
26        self.pretty_print_at(0)
27    }
28
29    /// [`Value::pretty_print`] with the ADR-0462 `depth` guard: a container
30    /// nested past [`super::MAX_VALUE_DEPTH`] renders the depth marker
31    /// instead of recursing — the same safety valve every other render
32    /// walk carries, through the one shared [`super::guarded_container`].
33    fn pretty_print_at(&self, depth: u32) -> String {
34        match self {
35            // Null never reaches an operand-echoing message (null
36            // propagation answers first); Neo4j's pretty print of NO_VALUE
37            // is `NULL`, kept for totality.
38            Value::Null => "NULL".into(),
39            Value::Bool(b) => format!("Boolean('{b}')"),
40            Value::Int(i) => format!("Long({i})"),
41            Value::Float(f) => format!("Double({})", double_scientific(*f)),
42            // Live does not escape the payload (probed: `String("a"b'c")`).
43            Value::String(s) => format!("String(\"{s}\")"),
44            Value::List(xs) => super::guarded_container(
45                depth,
46                |joined| format!("List{{{joined}}}"),
47                |d| xs.iter().map(|v| v.pretty_print_at(d)).collect(),
48            ),
49            // A `BTreeMap`, so the iteration order is already the sorted
50            // one live prints (probed: `{b:2,a:1}` renders `Map{a -> …, b
51            // -> …}`); keys print raw, like live's.
52            Value::Map(m) => super::guarded_container(
53                depth,
54                |joined| format!("Map{{{joined}}}"),
55                |d| {
56                    m.iter()
57                        .map(|(k, v)| format!("{k} -> {}", v.pretty_print_at(d)))
58                        .collect()
59                },
60            ),
61            Value::Node(n) => pretty_node(n),
62            Value::Relationship(r) => pretty_rel(r),
63            Value::Path(p) => pretty_path(p),
64            // The display form is live's own pretty print for temporals
65            // (probed: `2021-01-01T00:00:00+01:00[Europe/Stockholm]`,
66            // `12:30:00Z`, `PT1M30S`).
67            Value::Temporal(t) => t.full_seconds_string(),
68            // Same for points: `point({x: 1.0, y: 2.0, crs: 'cartesian'})`.
69            Value::Point(pt) => super::point_display(pt),
70            Value::Uuid(u) => format!("UUID({})", super::uuid_hyphenated(*u)),
71            Value::Bytes(b) => format!("ByteArray[{}]", super::bytes_int_list(b)),
72            // Engine-only scalar (live 2026.10.1 has no vector values —
73            // `vec` is an unknown function there, probed): the container
74            // family's wrapped form, coordinates pretty-printed like any
75            // other element.
76            // The packed coordinates (ADR-0706) pretty-print as the
77            // scalars they are — the same Long/Double forms the walk
78            // above gives them — with the container family's wrapped
79            // form. No child Values, so the guard cannot stop a
80            // recursion; the family render is direct.
81            Value::Vector { coords, .. } => {
82                // The scalars' own pretty forms (the Int/Float arms
83                // above), one spelling through the shared helper.
84                let joined = coords
85                    .iter()
86                    .map(coord_pretty)
87                    .collect::<Vec<_>>()
88                    .join(", ");
89                format!("Vector{{{joined}}}")
90            }
91        }
92    }
93}
94
95/// `(<id>)` — the bare node id, no labels or properties (probed).
96fn pretty_node(n: &Node) -> String {
97    format!("({})", n.id)
98}
99
100/// `-[<id>]-` — the bare relationship id, no type (probed).
101fn pretty_rel(r: &Relationship) -> String {
102    format!("-[{}]-", r.id)
103}
104
105/// `Path{(0)-[<id>]-(1)}` — the shared chain walk ([`super::Path::walk`])
106/// with the bare-id element renderings. Live's pretty print carries no
107/// direction arrows, and the pretty rel form (`-[<id>]-`) brings its own
108/// dashes — the display/literal walks compose [`super::direction_arrows`]
109/// around their dash-less `[:TYPE]` — so this walk's rel seam ignores the
110/// current node id.
111fn pretty_path(p: &super::Path) -> String {
112    format!("Path{{{}}}", p.walk(pretty_node, |r, _| pretty_rel(r)))
113}
114
115/// The `Double(…)` payload: Java's `%e` — one integer digit, six
116/// fractional digits, a signed exponent zero-padded to two places
117/// (`Double(1.500000e+00)`, `Double(1.000000e-07)`,
118/// `Double(1.000000e+300)`; `NaN`/`Infinity`/`-Infinity` verbatim — all
119/// probed).
120///
121/// The rounding basis is the f64's **shortest round-trip digits**, not its
122/// exact binary expansion: live prints `Double(1.007813e+00)` for
123/// 1.0078125 — Java's formatter rounds the decimal string half-up, so
124/// 129/128 rounds up where a round-half-even of the same digits would
125/// keep 1.007812 (probed). Rust's `{:e}` produces the same shortest
126/// digits for every probed shape, so the digits are taken from it and the
127/// half-up rounding is done here, on the string.
128///
129/// One known boundary divergence, documented rather than ported: live's
130/// formatter is OpenJDK's legacy `FloatingDecimal`, whose digit weeding
131/// sometimes emits more digits than the shortest that round-trips — the
132/// smallest subnormal (exact 4.9406564584124654e-324) prints
133/// `Double(4.900000e-324)` on live while this rendering prints its
134/// shortest correctly-rounded form `Double(5.000000e-324)`. Every
135/// probed non-boundary float agrees.
136fn double_scientific(f: f64) -> String {
137    // The non-finite spellings are the one float policy's own —
138    // `float_text` prints NaN/Infinity/-Infinity, the same strings live's
139    // formatter does (probed).
140    if !f.is_finite() {
141        return relate_model::value::float_text(f);
142    }
143    // Shortest scientific digits: `1.5e0`, `-2.25e0`, `1e20`, `4.9e-324`.
144    let rendered = format!("{f:e}");
145    let (mantissa, exponent) = rendered
146        .split_once('e')
147        .expect("LowerExp always carries an exponent");
148    let exponent: i64 = exponent.parse().expect("a LowerExp exponent is an integer");
149    let (mantissa, exponent) = round_half_up_at_six(mantissa, exponent);
150    format!("{mantissa}e{exponent:+03}")
151}
152
153/// A packed coordinate's pretty form — the `Value::Int`/`Value::Float`
154/// arms' renders, spelled once for the vector arm (ADR-0706).
155fn coord_pretty(c: Coord) -> String {
156    match c {
157        Coord::I(i) => format!("Long({i})"),
158        Coord::F(f) => format!("Double({})", double_scientific(f)),
159    }
160}
161
162/// Round a `{:e}` mantissa string (`"1.0078125"`, `"-1.5"`, `"9"`) half-up
163/// at six fractional digits, returning the padded mantissa and, when the
164/// rounding carried out of the integer digit (`9.999999…5` → `10.000000`),
165/// the exponent shifted up one with the mantissa renormalized to
166/// `1.000000`. A `{:e}` mantissa carries exactly one integer digit, so the
167/// arithmetic stays a single-digit add; the exponent crosses as the
168/// integer it is.
169fn round_half_up_at_six(mantissa: &str, exponent: i64) -> (String, i64) {
170    let negative = mantissa.starts_with('-');
171    let unsigned = mantissa.strip_prefix('-').unwrap_or(mantissa);
172    // One integer digit, a dot, and at least seven fractional digits (the
173    // seventh is the first discarded one — the half-up decider). Only
174    // zeros are appended, so the dot's index does not move.
175    let mut digits = unsigned.to_string();
176    if !digits.contains('.') {
177        digits.push('.');
178    }
179    let dot = digits.find('.').expect("the dot was just ensured");
180    let frac_len = digits.len() - dot - 1;
181    digits.push_str(&"0".repeat(7 - frac_len.min(7)));
182    // The integer digit and the six kept fraction digits are one seven-digit
183    // significand, so the half-up carry is one add and one boundary check.
184    let mut significand: u64 = format!("{}{}", &digits[..dot], &digits[dot + 1..dot + 7])
185        .parse()
186        .expect("one integer digit and six fractional digits are a number");
187    // Half-up: the discarded tail alone decides, never the kept digit's
188    // parity (probed: 1.0078125 rounds to 1.007813).
189    if digits.as_bytes()[dot + 7] >= b'5' {
190        significand += 1;
191    }
192    // The one shape that leaves the single-digit range — 9.999999…5 —
193    // renormalizes to 1.000000 with the exponent bumped.
194    let mut exponent_shift = 0i64;
195    if significand == 10_000_000 {
196        significand = 1_000_000;
197        exponent_shift = 1;
198    }
199    let mantissa = format!("{}.{:06}", significand / 1_000_000, significand % 1_000_000);
200    (
201        if negative {
202            format!("-{mantissa}")
203        } else {
204            mantissa
205        },
206        exponent + exponent_shift,
207    )
208}