Skip to main content

relate_model/
serde_value.rs

1//! Serialization/deserialization support for CypherValue.
2//!
3//! Converts CypherValue to/from serde_json::Value for JSON persistence.
4//! Designed for Go JSON format compatibility.
5
6use chrono::{DateTime, Duration, FixedOffset, NaiveDate, NaiveDateTime, NaiveTime};
7use indexmap::IndexMap;
8use serde_json::{Map as JsonMap, Value as JsonValue};
9
10use crate::value::{Coord2D, CypherValue, GeometryValue, IsoDuration, PointValue, VectorCoordKind};
11
12/// Invalid persistence value, with a JSON path to the offending member.
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub struct EncodeError {
15    pub path: String,
16    pub message: String,
17}
18
19impl std::fmt::Display for EncodeError {
20    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
21        write!(f, "{}: {}", self.path, self.message)
22    }
23}
24
25impl std::error::Error for EncodeError {}
26
27fn encode_error(path: &str, message: impl Into<String>) -> EncodeError {
28    EncodeError {
29        path: path.into(),
30        message: message.into(),
31    }
32}
33
34/// A finite f64 is exactly representable as f32 only if its signed bits survive.
35pub fn float32_exact(f: f64) -> bool {
36    VectorCoordKind::Float32.is_exact(f)
37}
38
39fn finite_number(f: f64, path: &str) -> Result<JsonValue, EncodeError> {
40    serde_json::Number::from_f64(f)
41        .map(JsonValue::Number)
42        .ok_or_else(|| encode_error(path, "expected finite number"))
43}
44
45fn require_minute_offset(offset: &FixedOffset, path: &str) -> Result<(), EncodeError> {
46    if offset.local_minus_utc() % 60 != 0 {
47        return Err(encode_error(
48            path,
49            "offset must be a whole number of minutes",
50        ));
51    }
52    Ok(())
53}
54
55/// Encode a persistence value as v2 JSON, rejecting values that cannot round-trip.
56/// Temporal, spatial, duration and vector values use `__type` tags, while user
57/// maps containing `__type` use the versioned `map` escape.
58/// A `DateTime` also requires a minute-aligned fixed offset whose UTC instant
59/// plus offset fits chrono's local `NaiveDateTime` range. Otherwise this returns
60/// an [`EncodeError`] with the nested value path before RFC3339 formatting;
61/// `serde::Serialize` reports the same error.
62///
63/// ```
64/// use relate_model::{CypherValue, serde_value::{
65///     cypher_value_to_json, props_to_json, try_json_to_cypher_value_v2,
66/// }};
67/// use relate_model::value::PointValue;
68/// use indexmap::IndexMap;
69///
70/// let point = CypherValue::Point(PointValue::cartesian_3d(1.5, -2.25, 3.0));
71/// let value = CypherValue::Map(IndexMap::from([
72///     ("__type".into(), CypherValue::Str("user data".into())),
73///     ("place".into(), point),
74/// ]));
75/// let json = cypher_value_to_json(&value)?;
76/// assert_eq!(json["__type"], "map");
77/// assert_eq!(json["value"]["place"]["__type"], "point");
78/// assert_eq!(try_json_to_cypher_value_v2(&json)?, value);
79///
80/// let invalid = CypherValue::Point(PointValue::cartesian_3d(1.5, f64::INFINITY, 3.0));
81/// assert_eq!(cypher_value_to_json(&invalid).unwrap_err().path, "$.y");
82/// let props = IndexMap::from([("place".into(), invalid)]);
83/// assert_eq!(props_to_json(&props).unwrap_err().path, "$.place.y");
84/// # Ok::<(), Box<dyn std::error::Error>>(())
85/// ```
86///
87/// A fixed offset can be valid even when its local time lies outside chrono's
88/// range. Canonical expanded-year values *inside* the range still round-trip:
89///
90/// ```
91/// use chrono::{Duration, FixedOffset, NaiveDateTime, TimeZone};
92/// use relate_model::{CypherValue, serde_value::{
93///     cypher_value_to_json, props_to_json, try_json_to_cypher_value_v2,
94/// }};
95/// use indexmap::IndexMap;
96///
97/// let plus_one = FixedOffset::east_opt(3600).unwrap();
98/// let invalid = CypherValue::DateTime(plus_one.from_utc_datetime(&NaiveDateTime::MAX), None);
99/// let error = cypher_value_to_json(&invalid).unwrap_err();
100/// assert_eq!(error.path, "$");
101/// assert_eq!(error.message, "DateTime local time out of range");
102/// let nested = CypherValue::Map(IndexMap::from([("items".into(), CypherValue::List(vec![invalid]))]));
103/// let props = IndexMap::from([("payload".into(), nested)]);
104/// assert_eq!(props_to_json(&props).unwrap_err().path, "$.payload.items[0]");
105/// assert!(serde_json::to_value(&CypherValue::Map(props)).unwrap_err()
106///     .to_string().contains("$.payload.items[0]"));
107///
108/// for (utc, offset, expected) in [
109///     (NaiveDateTime::MAX - Duration::hours(1), 3600,
110///      "+262142-12-31T23:59:59.999999999+01:00"),
111///     (NaiveDateTime::MIN + Duration::hours(1), -3600,
112///      "-262143-01-01T00:00:00-01:00"),
113/// ] {
114///     let fixed = FixedOffset::east_opt(offset).unwrap();
115///     let value = CypherValue::DateTime(fixed.from_utc_datetime(&utc), None);
116///     let json = cypher_value_to_json(&value)?;
117///     assert_eq!(json["value"], expected);
118///     assert_eq!(try_json_to_cypher_value_v2(&json)?, value);
119///     assert_eq!(serde_json::from_value::<CypherValue>(serde_json::to_value(&value)?)?, value);
120/// }
121/// # Ok::<(), Box<dyn std::error::Error>>(())
122/// ```
123pub fn cypher_value_to_json(val: &CypherValue) -> Result<JsonValue, EncodeError> {
124    encode(val, "$")
125}
126
127fn encode(val: &CypherValue, path: &str) -> Result<JsonValue, EncodeError> {
128    Ok(match val {
129        CypherValue::Null => JsonValue::Null,
130        CypherValue::Bool(b) => JsonValue::Bool(*b),
131        CypherValue::Int(i) => JsonValue::Number((*i).into()),
132        CypherValue::Float(f) => finite_number(*f, path)?,
133        CypherValue::Str(s) => JsonValue::String(s.clone()),
134        CypherValue::List(items) => JsonValue::Array(
135            items
136                .iter()
137                .enumerate()
138                .map(|(i, item)| encode(item, &format!("{path}[{i}]")))
139                .collect::<Result<_, _>>()?,
140        ),
141        CypherValue::Map(map) => {
142            let obj = encode_map(map, path)?;
143            if map.contains_key("__type") {
144                serde_json::json!({"__type": "map", "value": obj})
145            } else {
146                JsonValue::Object(obj)
147            }
148        }
149        CypherValue::Date(d) => serde_json::json!({"__type": "date", "value": d.to_string()}),
150        CypherValue::Time(t, tz) => {
151            let mut obj = serde_json::json!({
152                "__type": "time", "value": t.format("%H:%M:%S%.f").to_string(),
153            });
154            if let Some(offset) = tz {
155                require_minute_offset(offset, path)?;
156                let secs = offset.local_minus_utc();
157                let h = secs.abs() / 3600;
158                let m = (secs.abs() % 3600) / 60;
159                obj["offset"] =
160                    JsonValue::String(format!("{}{h:02}:{m:02}", if secs < 0 { '-' } else { '+' }));
161            }
162            obj
163        }
164        CypherValue::DateTime(dt, tz_name) => {
165            require_minute_offset(dt.offset(), path)?;
166            if dt
167                .naive_utc()
168                .checked_add_signed(Duration::seconds(i64::from(dt.offset().local_minus_utc())))
169                .is_none()
170            {
171                return Err(encode_error(path, "DateTime local time out of range"));
172            }
173            let mut obj = serde_json::json!({"__type": "datetime", "value": dt.to_rfc3339()});
174            if let Some(name) = tz_name {
175                obj["timezone"] = JsonValue::String(name.clone());
176            }
177            obj
178        }
179        CypherValue::LocalDateTime(ldt) => serde_json::json!({
180            "__type": "localdatetime", "value": ldt.format("%Y-%m-%dT%H:%M:%S%.f").to_string(),
181        }),
182        CypherValue::Duration(d) => serde_json::json!({
183            "__type": "duration", "months": d.months, "days": d.days,
184            "seconds": d.seconds, "nanoseconds": d.nanoseconds,
185        }),
186        CypherValue::Point(p) => {
187            let mut obj = serde_json::json!({"__type": "point", "srid": p.srid});
188            obj["x"] = finite_number(p.x, &format!("{path}.x"))?;
189            obj["y"] = finite_number(p.y, &format!("{path}.y"))?;
190            if let Some(z) = p.z {
191                obj["z"] = finite_number(z, &format!("{path}.z"))?;
192            }
193            obj
194        }
195        CypherValue::Geometry(g) => encode_geometry(g, path)?,
196        CypherValue::Vector { coord, dim, values } => {
197            if *dim != values.len() {
198                return Err(encode_error(
199                    &format!("{path}.dim"),
200                    "dimension does not match values length",
201                ));
202            }
203            let mut encoded = Vec::with_capacity(values.len());
204            for (i, value) in values.iter().enumerate() {
205                let at = format!("{path}.values[{i}]");
206                let item = match (coord, value) {
207                    (_, CypherValue::Int(n)) if coord.holds_int(*n) => {
208                        JsonValue::Number((*n).into())
209                    }
210                    (
211                        VectorCoordKind::Float16
212                        | VectorCoordKind::BFloat16
213                        | VectorCoordKind::Float32,
214                        CypherValue::Float(f),
215                    ) if coord.is_exact(*f) => finite_number(*f, &at)?,
216                    (VectorCoordKind::Float64, CypherValue::Float(f)) => finite_number(*f, &at)?,
217                    _ => {
218                        return Err(encode_error(
219                            &at,
220                            format!(
221                                "invalid {} coordinate type or range",
222                                coord.canonical_name()
223                            ),
224                        ))
225                    }
226                };
227                encoded.push(item);
228            }
229            serde_json::json!({"__type": "vector", "coord": coord.canonical_name(), "dim": dim, "values": encoded})
230        }
231        CypherValue::Node { .. } | CypherValue::Relationship { .. } | CypherValue::Path { .. } => {
232            return Err(encode_error(
233                path,
234                "graph entity is not a persistence property",
235            ));
236        }
237    })
238}
239
240fn encode_map(
241    map: &IndexMap<String, CypherValue>,
242    path: &str,
243) -> Result<JsonMap<String, JsonValue>, EncodeError> {
244    map.iter()
245        .map(|(key, value)| Ok((key.clone(), encode(value, &format!("{path}.{key}"))?)))
246        .collect()
247}
248
249fn encode_coords(coords: &[Coord2D], path: &str) -> Result<JsonValue, EncodeError> {
250    Ok(JsonValue::Array(
251        coords
252            .iter()
253            .enumerate()
254            .map(|(i, c)| {
255                Ok(JsonValue::Array(vec![
256                    finite_number(c[0], &format!("{path}[{i}][0]"))?,
257                    finite_number(c[1], &format!("{path}[{i}][1]"))?,
258                ]))
259            })
260            .collect::<Result<_, EncodeError>>()?,
261    ))
262}
263
264fn encode_nested_coords(groups: &[Vec<Coord2D>], path: &str) -> Result<JsonValue, EncodeError> {
265    Ok(JsonValue::Array(
266        groups
267            .iter()
268            .enumerate()
269            .map(|(i, coords)| encode_coords(coords, &format!("{path}[{i}]")))
270            .collect::<Result<_, _>>()?,
271    ))
272}
273
274fn encode_geometry(g: &GeometryValue, path: &str) -> Result<JsonValue, EncodeError> {
275    let mut obj = serde_json::json!({
276        "__type": "geometry", "geometry_type": g.type_name(), "srid": g.srid(),
277    });
278    let at = format!("{path}.coordinates");
279    match g {
280        GeometryValue::LineString { coordinates, .. } => {
281            obj["coordinates"] = encode_coords(coordinates, &at)?
282        }
283        GeometryValue::Polygon { rings, .. } => {
284            obj["coordinates"] = encode_nested_coords(rings, &at)?
285        }
286        GeometryValue::MultiPoint { points, .. } => {
287            obj["coordinates"] = encode_coords(points, &at)?
288        }
289        GeometryValue::MultiLineString { lines, .. } => {
290            obj["coordinates"] = encode_nested_coords(lines, &at)?
291        }
292        GeometryValue::MultiPolygon { polygons, .. } => {
293            obj["coordinates"] = JsonValue::Array(
294                polygons
295                    .iter()
296                    .enumerate()
297                    .map(|(i, polygon)| encode_nested_coords(polygon, &format!("{at}[{i}]")))
298                    .collect::<Result<_, _>>()?,
299            );
300        }
301        GeometryValue::GeometryCollection { geometries, .. } => {
302            obj["geometries"] = JsonValue::Array(
303                geometries
304                    .iter()
305                    .enumerate()
306                    .map(|(i, geometry)| {
307                        encode_geometry(geometry, &format!("{path}.geometries[{i}]"))
308                    })
309                    .collect::<Result<_, _>>()?,
310            );
311        }
312    }
313    Ok(obj)
314}
315
316/// An invalid persistence value, with a JSON path to the offending field.
317#[derive(Debug, Clone, PartialEq, Eq)]
318pub struct DecodeError {
319    pub path: String,
320    pub message: String,
321}
322
323impl std::fmt::Display for DecodeError {
324    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
325        write!(f, "{}: {}", self.path, self.message)
326    }
327}
328
329impl std::error::Error for DecodeError {}
330
331fn invalid(path: &str, message: impl Into<String>) -> DecodeError {
332    DecodeError {
333        path: path.into(),
334        message: message.into(),
335    }
336}
337
338fn field<'a>(
339    obj: &'a JsonMap<String, JsonValue>,
340    name: &str,
341    path: &str,
342) -> Result<&'a JsonValue, DecodeError> {
343    obj.get(name)
344        .ok_or_else(|| invalid(&format!("{path}.{name}"), "missing required field"))
345}
346
347fn string<'a>(val: &'a JsonValue, path: &str) -> Result<&'a str, DecodeError> {
348    val.as_str().ok_or_else(|| invalid(path, "expected string"))
349}
350
351fn integer(val: &JsonValue, path: &str) -> Result<i64, DecodeError> {
352    val.as_i64()
353        .ok_or_else(|| invalid(path, "expected signed 64-bit integer"))
354}
355
356fn number(val: &JsonValue, path: &str) -> Result<f64, DecodeError> {
357    val.as_f64()
358        .filter(|n| n.is_finite())
359        .ok_or_else(|| invalid(path, "expected finite number"))
360}
361
362fn array<'a>(val: &'a JsonValue, path: &str) -> Result<&'a [JsonValue], DecodeError> {
363    val.as_array()
364        .map(Vec::as_slice)
365        .ok_or_else(|| invalid(path, "expected array"))
366}
367
368fn keys(obj: &JsonMap<String, JsonValue>, allowed: &[&str], path: &str) -> Result<(), DecodeError> {
369    if let Some(key) = obj.keys().find(|key| !allowed.contains(&key.as_str())) {
370        return Err(invalid(&format!("{path}.{key}"), "unrecognized field"));
371    }
372    Ok(())
373}
374
375/// Decode standalone persistence JSON (which follows version-2 tag rules).
376pub fn try_json_to_cypher_value(val: &JsonValue) -> Result<CypherValue, DecodeError> {
377    try_json_to_cypher_value_v2(val)
378}
379
380/// Decode version-2 snapshot values. Known tags are strict; the exact
381/// `{"__type":"map","value":{...}}` form escapes ordinary maps.
382///
383/// ```
384/// use relate_model::{CypherValue, serde_value::{
385///     cypher_value_to_json, try_json_to_cypher_value_v2,
386///     try_json_to_cypher_value_legacy, try_json_to_param_value,
387/// }};
388/// use serde_json::json;
389///
390/// let point = json!({"__type":"point", "srid":4326, "x":1.5, "y":-2.25});
391/// assert!(matches!(try_json_to_cypher_value_v2(&point)?, CypherValue::Point(_)));
392/// // A v2 escaped map cannot be mistaken for a point.
393/// let escaped = json!({"__type":"map", "value":{"__type":"point", "x":1}});
394/// let map = try_json_to_cypher_value_v2(&escaped)?;
395/// assert!(matches!(map, CypherValue::Map(_)));
396/// assert_eq!(cypher_value_to_json(&map)?, escaped);
397/// // In v1, __type=map is ordinary data; its nested values still use v1 rules.
398/// let legacy_map = json!({"__type":"map", "value":{"x":1}});
399/// let legacy = try_json_to_cypher_value_legacy(&legacy_map)?;
400/// assert!(matches!(&legacy, CypherValue::Map(m) if m.contains_key("value")));
401/// assert!(try_json_to_cypher_value_legacy(&escaped).is_err());
402/// // User parameters never infer typed values from __type.
403/// assert!(matches!(try_json_to_param_value(&point)?, CypherValue::Map(_)));
404///
405/// let invalid = json!({"__type":"point", "srid":4326, "x":1.5});
406/// assert_eq!(try_json_to_cypher_value_v2(&invalid).unwrap_err().path, "$.y");
407/// assert!(serde_json::from_value::<CypherValue>(invalid).is_err());
408/// # Ok::<(), Box<dyn std::error::Error>>(())
409/// ```
410pub fn try_json_to_cypher_value_v2(val: &JsonValue) -> Result<CypherValue, DecodeError> {
411    decode(val, "$", DecodeMode::V2)
412}
413
414/// Decode version-1 snapshots. `__type=map` is ordinary map data in v1;
415/// valid historical typed tags still have their original interpretation.
416pub fn try_json_to_cypher_value_legacy(val: &JsonValue) -> Result<CypherValue, DecodeError> {
417    decode(val, "$", DecodeMode::Legacy)
418}
419
420/// Decode user-supplied JSON parameters. Objects are always ordinary maps,
421/// including those with `__type`; typed values require explicit query constructors.
422pub fn try_json_to_param_value(val: &JsonValue) -> Result<CypherValue, DecodeError> {
423    decode(val, "$", DecodeMode::Parameter)
424}
425
426/// Selects whether `__type` is interpreted as a persistence tag and whether
427/// the v2 map envelope is recognized. Parameters treat every object as a map.
428#[derive(Clone, Copy, PartialEq, Eq)]
429enum DecodeMode {
430    Legacy,
431    V2,
432    Parameter,
433}
434
435fn decode_map(
436    obj: &JsonMap<String, JsonValue>,
437    path: &str,
438    mode: DecodeMode,
439) -> Result<CypherValue, DecodeError> {
440    let mut result = IndexMap::new();
441    for (key, value) in obj {
442        let child = format!("{path}.{key}");
443        result.insert(key.clone(), decode(value, &child, mode)?);
444    }
445    Ok(CypherValue::Map(result))
446}
447
448fn decode(val: &JsonValue, path: &str, mode: DecodeMode) -> Result<CypherValue, DecodeError> {
449    match val {
450        JsonValue::Null => Ok(CypherValue::Null),
451        JsonValue::Bool(b) => Ok(CypherValue::Bool(*b)),
452        JsonValue::Number(n) => {
453            if let Some(i) = n.as_i64() {
454                Ok(CypherValue::Int(i))
455            } else if n.is_u64() {
456                Err(invalid(path, "integer exceeds i64 range"))
457            } else {
458                Ok(CypherValue::Float(number(val, path)?))
459            }
460        }
461        JsonValue::String(s) => Ok(CypherValue::Str(s.clone())),
462        JsonValue::Array(items) => items
463            .iter()
464            .enumerate()
465            .map(|(i, item)| decode(item, &format!("{path}[{i}]"), mode))
466            .collect::<Result<Vec<_>, _>>()
467            .map(CypherValue::List),
468        JsonValue::Object(obj) => {
469            if mode == DecodeMode::Parameter {
470                return decode_map(obj, path, mode);
471            }
472            let Some(tag) = obj.get("__type").and_then(JsonValue::as_str) else {
473                return decode_map(obj, path, mode);
474            };
475            if tag == "map" && mode == DecodeMode::V2 {
476                keys(obj, &["__type", "value"], path)?;
477                let contents = field(obj, "value", path)?
478                    .as_object()
479                    .ok_or_else(|| invalid(&format!("{path}.value"), "expected object"))?;
480                return decode_map(contents, path, mode);
481            }
482            let value = match tag {
483                "date" => {
484                    keys(obj, &["__type", "value"], path)?;
485                    let s = string(field(obj, "value", path)?, &format!("{path}.value"))?;
486                    CypherValue::Date(
487                        s.parse::<NaiveDate>()
488                            .map_err(|e| invalid(&format!("{path}.value"), e.to_string()))?,
489                    )
490                }
491                "time" => {
492                    keys(obj, &["__type", "value", "offset"], path)?;
493                    let s = string(field(obj, "value", path)?, &format!("{path}.value"))?;
494                    let t = NaiveTime::parse_from_str(s, "%H:%M:%S%.f")
495                        .map_err(|e| invalid(&format!("{path}.value"), e.to_string()))?;
496                    let offset =
497                        obj.get("offset")
498                            .map(|o| {
499                                parse_numeric_offset(string(o, &format!("{path}.offset"))?)
500                                    .ok_or_else(|| {
501                                        invalid(
502                                            &format!("{path}.offset"),
503                                            "expected ASCII ±HH:MM offset within 24 hours",
504                                        )
505                                    })
506                            })
507                            .transpose()?;
508                    CypherValue::Time(t, offset)
509                }
510                "datetime" => {
511                    keys(obj, &["__type", "value", "timezone"], path)?;
512                    let s = string(field(obj, "value", path)?, &format!("{path}.value"))?;
513                    let dt = parse_persistence_datetime(s)
514                        .map_err(|e| invalid(&format!("{path}.value"), e.to_string()))?;
515                    let tz = obj
516                        .get("timezone")
517                        .map(|v| string(v, &format!("{path}.timezone")).map(str::to_owned))
518                        .transpose()?;
519                    CypherValue::DateTime(dt, tz)
520                }
521                "localdatetime" => {
522                    keys(obj, &["__type", "value"], path)?;
523                    let s = string(field(obj, "value", path)?, &format!("{path}.value"))?;
524                    CypherValue::LocalDateTime(
525                        NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S%.f")
526                            .map_err(|e| invalid(&format!("{path}.value"), e.to_string()))?,
527                    )
528                }
529                "duration" => {
530                    keys(
531                        obj,
532                        &["__type", "months", "days", "seconds", "nanoseconds"],
533                        path,
534                    )?;
535                    let component =
536                        |name: &str| integer(field(obj, name, path)?, &format!("{path}.{name}"));
537                    CypherValue::Duration(IsoDuration::new(
538                        component("months")?,
539                        component("days")?,
540                        component("seconds")?,
541                        component("nanoseconds")?,
542                    ))
543                }
544                "point" => {
545                    keys(obj, &["__type", "srid", "x", "y", "z"], path)?;
546                    let srid =
547                        i32::try_from(integer(field(obj, "srid", path)?, &format!("{path}.srid"))?)
548                            .map_err(|_| {
549                                invalid(&format!("{path}.srid"), "SRID exceeds i32 range")
550                            })?;
551                    let coordinate =
552                        |name: &str| number(field(obj, name, path)?, &format!("{path}.{name}"));
553                    let z = obj
554                        .get("z")
555                        .map(|v| number(v, &format!("{path}.z")))
556                        .transpose()?;
557                    CypherValue::Point(PointValue {
558                        srid,
559                        x: coordinate("x")?,
560                        y: coordinate("y")?,
561                        z,
562                    })
563                }
564                "geometry" => CypherValue::Geometry(decode_geometry(obj, path, mode)?),
565                "vector" => decode_vector(obj, path)?,
566                _ => return decode_map(obj, path, mode),
567            };
568            Ok(value)
569        }
570    }
571}
572
573fn decode_vector(obj: &JsonMap<String, JsonValue>, path: &str) -> Result<CypherValue, DecodeError> {
574    keys(obj, &["__type", "coord", "dim", "values"], path)?;
575    let coord_path = format!("{path}.coord");
576    let coord =
577        VectorCoordKind::from_canonical_name(string(field(obj, "coord", path)?, &coord_path)?)
578            .ok_or_else(|| invalid(&coord_path, "unknown vector coordinate type"))?;
579    let dim_path = format!("{path}.dim");
580    let dim = usize::try_from(
581        field(obj, "dim", path)?
582            .as_u64()
583            .ok_or_else(|| invalid(&dim_path, "expected nonnegative integer dimension"))?,
584    )
585    .map_err(|_| invalid(&dim_path, "dimension exceeds usize range"))?;
586    let values_path = format!("{path}.values");
587    let items = array(field(obj, "values", path)?, &values_path)?;
588    if dim != items.len() {
589        return Err(invalid(&dim_path, "dimension does not match values length"));
590    }
591    let mut values = Vec::with_capacity(items.len());
592    for (i, item) in items.iter().enumerate() {
593        let at = format!("{values_path}[{i}]");
594        let value = match coord {
595            VectorCoordKind::Int8
596            | VectorCoordKind::Int16
597            | VectorCoordKind::Int32
598            | VectorCoordKind::Int64 => {
599                let n = integer(item, &at)?;
600                if !coord.holds_int(n) {
601                    return Err(invalid(
602                        &at,
603                        format!("{} out of range", coord.canonical_name()),
604                    ));
605                }
606                CypherValue::Int(n)
607            }
608            VectorCoordKind::Float16 | VectorCoordKind::BFloat16 | VectorCoordKind::Float32 => {
609                let f = float_number(item, &at)?;
610                if !coord.is_exact(f) {
611                    return Err(invalid(
612                        &at,
613                        format!("{} out of range or loses precision", coord.canonical_name()),
614                    ));
615                }
616                CypherValue::Float(f)
617            }
618            VectorCoordKind::Float64 => CypherValue::Float(float_number(item, &at)?),
619        };
620        values.push(value);
621    }
622    Ok(CypherValue::Vector { coord, dim, values })
623}
624
625fn float_number(val: &JsonValue, path: &str) -> Result<f64, DecodeError> {
626    if !val.is_f64() {
627        return Err(invalid(path, "expected floating-point number"));
628    }
629    number(val, path)
630}
631
632fn decode_geometry(
633    obj: &JsonMap<String, JsonValue>,
634    path: &str,
635    mode: DecodeMode,
636) -> Result<GeometryValue, DecodeError> {
637    let srid = i32::try_from(integer(field(obj, "srid", path)?, &format!("{path}.srid"))?)
638        .map_err(|_| invalid(&format!("{path}.srid"), "SRID exceeds i32 range"))?;
639    let kind = string(
640        field(obj, "geometry_type", path)?,
641        &format!("{path}.geometry_type"),
642    )?;
643    let coords_path = format!("{path}.coordinates");
644    let geometry = match kind {
645        "LineString" | "MultiPoint" => {
646            keys(
647                obj,
648                &["__type", "geometry_type", "srid", "coordinates"],
649                path,
650            )?;
651            let coords = decode_coords(field(obj, "coordinates", path)?, &coords_path)?;
652            if kind == "LineString" {
653                GeometryValue::LineString {
654                    coordinates: coords,
655                    srid,
656                }
657            } else {
658                GeometryValue::MultiPoint {
659                    points: coords,
660                    srid,
661                }
662            }
663        }
664        "Polygon" | "MultiLineString" => {
665            keys(
666                obj,
667                &["__type", "geometry_type", "srid", "coordinates"],
668                path,
669            )?;
670            let rings = decode_nested_coords(field(obj, "coordinates", path)?, &coords_path)?;
671            if kind == "Polygon" {
672                GeometryValue::Polygon { rings, srid }
673            } else {
674                GeometryValue::MultiLineString { lines: rings, srid }
675            }
676        }
677        "MultiPolygon" => {
678            keys(
679                obj,
680                &["__type", "geometry_type", "srid", "coordinates"],
681                path,
682            )?;
683            let polygons = array(field(obj, "coordinates", path)?, &coords_path)?
684                .iter()
685                .enumerate()
686                .map(|(i, v)| decode_nested_coords(v, &format!("{coords_path}[{i}]")))
687                .collect::<Result<_, _>>()?;
688            GeometryValue::MultiPolygon { polygons, srid }
689        }
690        "GeometryCollection" => {
691            keys(
692                obj,
693                &["__type", "geometry_type", "srid", "geometries"],
694                path,
695            )?;
696            let geometries = array(
697                field(obj, "geometries", path)?,
698                &format!("{path}.geometries"),
699            )?
700            .iter()
701            .enumerate()
702            .map(|(i, item)| {
703                let at = format!("{path}.geometries[{i}]");
704                match decode(item, &at, mode)? {
705                    CypherValue::Geometry(g) => Ok(g),
706                    _ => Err(invalid(&at, "expected tagged geometry")),
707                }
708            })
709            .collect::<Result<_, _>>()?;
710            GeometryValue::GeometryCollection { geometries, srid }
711        }
712        _ => {
713            return Err(invalid(
714                &format!("{path}.geometry_type"),
715                "unknown geometry type",
716            ))
717        }
718    };
719    Ok(geometry)
720}
721
722fn decode_nested_coords(val: &JsonValue, path: &str) -> Result<Vec<Vec<Coord2D>>, DecodeError> {
723    array(val, path)?
724        .iter()
725        .enumerate()
726        .map(|(i, v)| decode_coords(v, &format!("{path}[{i}]")))
727        .collect()
728}
729
730fn decode_coords(val: &JsonValue, path: &str) -> Result<Vec<Coord2D>, DecodeError> {
731    array(val, path)?
732        .iter()
733        .enumerate()
734        .map(|(i, v)| {
735            let at = format!("{path}[{i}]");
736            let pair = array(v, &at)?;
737            if pair.len() != 2 {
738                return Err(invalid(&at, "expected exactly two coordinates"));
739            }
740            Ok([
741                number(&pair[0], &format!("{at}[0]"))?,
742                number(&pair[1], &format!("{at}[1]"))?,
743            ])
744        })
745        .collect()
746}
747
748/// Convert a CypherValue property map to a serde_json::Map, retaining key paths.
749pub fn props_to_json(
750    props: &IndexMap<String, CypherValue>,
751) -> Result<JsonMap<String, JsonValue>, EncodeError> {
752    encode_map(props, "$")
753}
754
755/// Decode standalone property values following version-2 tag rules.
756pub fn try_json_to_props(
757    obj: &JsonMap<String, JsonValue>,
758) -> Result<IndexMap<String, CypherValue>, DecodeError> {
759    try_json_to_props_v2(obj)
760}
761
762/// Decode version-2 snapshot properties, retaining property-key error paths.
763pub fn try_json_to_props_v2(
764    obj: &JsonMap<String, JsonValue>,
765) -> Result<IndexMap<String, CypherValue>, DecodeError> {
766    decode_props(obj, DecodeMode::V2)
767}
768
769/// Decode version-1 snapshot properties (where `__type=map` was ordinary data).
770pub fn try_json_to_props_legacy(
771    obj: &JsonMap<String, JsonValue>,
772) -> Result<IndexMap<String, CypherValue>, DecodeError> {
773    decode_props(obj, DecodeMode::Legacy)
774}
775
776fn decode_props(
777    obj: &JsonMap<String, JsonValue>,
778    mode: DecodeMode,
779) -> Result<IndexMap<String, CypherValue>, DecodeError> {
780    obj.iter()
781        .map(|(key, value)| Ok((key.clone(), decode(value, &format!("$.{key}"), mode)?)))
782        .collect()
783}
784
785// ---- serde::Serialize / Deserialize impls for CypherValue ----
786
787impl serde::Serialize for CypherValue {
788    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
789    where
790        S: serde::Serializer,
791    {
792        let json = cypher_value_to_json(self).map_err(serde::ser::Error::custom)?;
793        json.serialize(serializer)
794    }
795}
796
797impl<'de> serde::Deserialize<'de> for CypherValue {
798    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
799    where
800        D: serde::Deserializer<'de>,
801    {
802        let json = JsonValue::deserialize(deserializer)?;
803        try_json_to_cypher_value(&json).map_err(serde::de::Error::custom)
804    }
805}
806
807// chrono's RFC 3339 parser rejects expanded years (e.g. +262142) that its
808// to_rfc3339 writer emits. Accept only that exact canonical writer form.
809fn parse_persistence_datetime(s: &str) -> Result<DateTime<FixedOffset>, chrono::ParseError> {
810    match DateTime::parse_from_rfc3339(s) {
811        Ok(dt) => Ok(dt),
812        Err(original) => {
813            let bytes = s.as_bytes();
814            let year_end = 1 + bytes
815                .iter()
816                .skip(1)
817                .take_while(|b| b.is_ascii_digit())
818                .count();
819            if !matches!(bytes.first(), Some(b'+' | b'-'))
820                || year_end < 6
821                || bytes.get(year_end) != Some(&b'-')
822            {
823                return Err(original);
824            }
825            let dt = DateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S%.f%:z")?;
826            if dt
827                .naive_utc()
828                .checked_add_signed(Duration::seconds(i64::from(dt.offset().local_minus_utc())))
829                .is_some()
830                && dt.to_rfc3339() == s
831            {
832                Ok(dt)
833            } else {
834                Err(original)
835            }
836        }
837    }
838}
839
840/// Parse exactly six ASCII bytes in signed `±HH:MM` form into a fixed offset.
841///
842/// The sign, two hour digits, colon, and two minute digits are required. Minutes
843/// must be at most 59, and the resulting offset must fit chrono's `FixedOffset`
844/// range. Returns `None` for malformed or out-of-range input, including
845/// non-ASCII text, without panicking.
846///
847/// ```
848/// use relate_model::serde_value::parse_numeric_offset;
849///
850/// assert_eq!(parse_numeric_offset("+02:30").unwrap().local_minus_utc(), 9_000);
851/// assert_eq!(parse_numeric_offset("-05:45").unwrap().local_minus_utc(), -20_700);
852/// assert!(parse_numeric_offset("+00:60").is_none());
853/// assert!(parse_numeric_offset("é+02:30").is_none());
854/// ```
855pub fn parse_numeric_offset(s: &str) -> Option<FixedOffset> {
856    let bytes = s.as_bytes();
857    if bytes.len() != 6 || !bytes.is_ascii() || bytes[3] != b':' {
858        return None;
859    }
860    let sign: i32 = match bytes[0] {
861        b'+' => 1,
862        b'-' => -1,
863        _ => return None,
864    };
865    let digit = |b: u8| -> Option<i32> { b.is_ascii_digit().then(|| i32::from(b - b'0')) };
866    let h = digit(bytes[1])?
867        .checked_mul(10)?
868        .checked_add(digit(bytes[2])?)?;
869    let m = digit(bytes[4])?
870        .checked_mul(10)?
871        .checked_add(digit(bytes[5])?)?;
872    if m > 59 {
873        return None;
874    }
875    let seconds = h
876        .checked_mul(3600)?
877        .checked_add(m.checked_mul(60)?)?
878        .checked_mul(sign)?;
879    FixedOffset::east_opt(seconds)
880}
881
882#[cfg(test)]
883mod tests;