1use 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};
11use crate::vector::coords::{Coord, VectorCoords};
12
13#[derive(Debug, Clone, PartialEq, Eq)]
15pub struct EncodeError {
16 pub path: String,
17 pub message: String,
18}
19
20impl std::fmt::Display for EncodeError {
21 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
22 write!(f, "{}: {}", self.path, self.message)
23 }
24}
25
26impl std::error::Error for EncodeError {}
27
28fn encode_error(path: &str, message: impl Into<String>) -> EncodeError {
29 EncodeError {
30 path: path.into(),
31 message: message.into(),
32 }
33}
34
35pub fn float32_exact(f: f64) -> bool {
37 VectorCoordKind::Float32.is_exact(f)
38}
39
40fn finite_number(f: f64, path: &str) -> Result<JsonValue, EncodeError> {
41 serde_json::Number::from_f64(f)
42 .map(JsonValue::Number)
43 .ok_or_else(|| encode_error(path, "expected finite number"))
44}
45
46fn require_minute_offset(offset: &FixedOffset, path: &str) -> Result<(), EncodeError> {
47 if offset.local_minus_utc() % 60 != 0 {
48 return Err(encode_error(
49 path,
50 "offset must be a whole number of minutes",
51 ));
52 }
53 Ok(())
54}
55
56pub fn cypher_value_to_json(val: &CypherValue) -> Result<JsonValue, EncodeError> {
125 encode(val, "$")
126}
127
128fn encode(val: &CypherValue, path: &str) -> Result<JsonValue, EncodeError> {
129 Ok(match val {
130 CypherValue::Null => JsonValue::Null,
131 CypherValue::Bool(b) => JsonValue::Bool(*b),
132 CypherValue::Int(i) => JsonValue::Number((*i).into()),
133 CypherValue::Float(f) => finite_number(*f, path)?,
134 CypherValue::Str(s) => JsonValue::String(s.clone()),
135 CypherValue::List(items) => JsonValue::Array(
136 items
137 .iter()
138 .enumerate()
139 .map(|(i, item)| encode(item, &format!("{path}[{i}]")))
140 .collect::<Result<_, _>>()?,
141 ),
142 CypherValue::Map(map) => {
143 let obj = encode_map(map, path)?;
144 if map.contains_key("__type") {
145 serde_json::json!({"__type": "map", "value": obj})
146 } else {
147 JsonValue::Object(obj)
148 }
149 }
150 CypherValue::Date(d) => serde_json::json!({"__type": "date", "value": d.to_string()}),
151 CypherValue::Time(t, tz) => {
152 let mut obj = serde_json::json!({
153 "__type": "time", "value": t.format("%H:%M:%S%.f").to_string(),
154 });
155 if let Some(offset) = tz {
156 require_minute_offset(offset, path)?;
157 let secs = offset.local_minus_utc();
158 let h = secs.abs() / 3600;
159 let m = (secs.abs() % 3600) / 60;
160 obj["offset"] =
161 JsonValue::String(format!("{}{h:02}:{m:02}", if secs < 0 { '-' } else { '+' }));
162 }
163 obj
164 }
165 CypherValue::DateTime(dt, tz_name) => {
166 require_minute_offset(dt.offset(), path)?;
167 if dt
168 .naive_utc()
169 .checked_add_signed(Duration::seconds(i64::from(dt.offset().local_minus_utc())))
170 .is_none()
171 {
172 return Err(encode_error(path, "DateTime local time out of range"));
173 }
174 let mut obj = serde_json::json!({"__type": "datetime", "value": dt.to_rfc3339()});
175 if let Some(name) = tz_name {
176 obj["timezone"] = JsonValue::String(name.clone());
177 }
178 obj
179 }
180 CypherValue::LocalDateTime(ldt) => serde_json::json!({
181 "__type": "localdatetime", "value": ldt.format("%Y-%m-%dT%H:%M:%S%.f").to_string(),
182 }),
183 CypherValue::Duration(d) => serde_json::json!({
184 "__type": "duration", "months": d.months, "days": d.days,
185 "seconds": d.seconds, "nanoseconds": d.nanoseconds,
186 }),
187 CypherValue::Point(p) => {
188 let mut obj = serde_json::json!({"__type": "point", "srid": p.srid});
189 obj["x"] = finite_number(p.x, &format!("{path}.x"))?;
190 obj["y"] = finite_number(p.y, &format!("{path}.y"))?;
191 if let Some(z) = p.z {
192 obj["z"] = finite_number(z, &format!("{path}.z"))?;
193 }
194 obj
195 }
196 CypherValue::Geometry(g) => encode_geometry(g, path)?,
197 CypherValue::Vector { coord, coords } => {
198 let values_path = format!("{path}.values");
208 let encoded = coords
209 .iter()
210 .map(|c| match c {
211 Coord::I(n) => Ok(JsonValue::Number(n.into())),
212 Coord::F(f) => finite_number(f, &values_path),
213 })
214 .collect::<Result<Vec<_>, _>>()?;
215 serde_json::json!({"__type": "vector", "coord": coord.canonical_name(), "dim": coords.len(), "values": encoded})
216 }
217 CypherValue::Node { .. } | CypherValue::Relationship { .. } | CypherValue::Path { .. } => {
218 return Err(encode_error(
219 path,
220 "graph entity is not a persistence property",
221 ));
222 }
223 })
224}
225
226fn encode_map(
227 map: &IndexMap<String, CypherValue>,
228 path: &str,
229) -> Result<JsonMap<String, JsonValue>, EncodeError> {
230 map.iter()
231 .map(|(key, value)| Ok((key.clone(), encode(value, &format!("{path}.{key}"))?)))
232 .collect()
233}
234
235fn encode_coords(coords: &[Coord2D], path: &str) -> Result<JsonValue, EncodeError> {
236 Ok(JsonValue::Array(
237 coords
238 .iter()
239 .enumerate()
240 .map(|(i, c)| {
241 Ok(JsonValue::Array(vec![
242 finite_number(c[0], &format!("{path}[{i}][0]"))?,
243 finite_number(c[1], &format!("{path}[{i}][1]"))?,
244 ]))
245 })
246 .collect::<Result<_, EncodeError>>()?,
247 ))
248}
249
250fn encode_nested_coords(groups: &[Vec<Coord2D>], path: &str) -> Result<JsonValue, EncodeError> {
251 Ok(JsonValue::Array(
252 groups
253 .iter()
254 .enumerate()
255 .map(|(i, coords)| encode_coords(coords, &format!("{path}[{i}]")))
256 .collect::<Result<_, _>>()?,
257 ))
258}
259
260fn encode_geometry(g: &GeometryValue, path: &str) -> Result<JsonValue, EncodeError> {
261 let mut obj = serde_json::json!({
262 "__type": "geometry", "geometry_type": g.type_name(), "srid": g.srid(),
263 });
264 let at = format!("{path}.coordinates");
265 match g {
266 GeometryValue::LineString { coordinates, .. } => {
267 obj["coordinates"] = encode_coords(coordinates, &at)?
268 }
269 GeometryValue::Polygon { rings, .. } => {
270 obj["coordinates"] = encode_nested_coords(rings, &at)?
271 }
272 GeometryValue::MultiPoint { points, .. } => {
273 obj["coordinates"] = encode_coords(points, &at)?
274 }
275 GeometryValue::MultiLineString { lines, .. } => {
276 obj["coordinates"] = encode_nested_coords(lines, &at)?
277 }
278 GeometryValue::MultiPolygon { polygons, .. } => {
279 obj["coordinates"] = JsonValue::Array(
280 polygons
281 .iter()
282 .enumerate()
283 .map(|(i, polygon)| encode_nested_coords(polygon, &format!("{at}[{i}]")))
284 .collect::<Result<_, _>>()?,
285 );
286 }
287 GeometryValue::GeometryCollection { geometries, .. } => {
288 obj["geometries"] = JsonValue::Array(
289 geometries
290 .iter()
291 .enumerate()
292 .map(|(i, geometry)| {
293 encode_geometry(geometry, &format!("{path}.geometries[{i}]"))
294 })
295 .collect::<Result<_, _>>()?,
296 );
297 }
298 }
299 Ok(obj)
300}
301
302#[derive(Debug, Clone, PartialEq, Eq)]
304pub struct DecodeError {
305 pub path: String,
306 pub message: String,
307}
308
309impl std::fmt::Display for DecodeError {
310 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
311 write!(f, "{}: {}", self.path, self.message)
312 }
313}
314
315impl std::error::Error for DecodeError {}
316
317fn invalid(path: &str, message: impl Into<String>) -> DecodeError {
318 DecodeError {
319 path: path.into(),
320 message: message.into(),
321 }
322}
323
324fn field<'a>(
325 obj: &'a JsonMap<String, JsonValue>,
326 name: &str,
327 path: &str,
328) -> Result<&'a JsonValue, DecodeError> {
329 obj.get(name)
330 .ok_or_else(|| invalid(&format!("{path}.{name}"), "missing required field"))
331}
332
333fn string<'a>(val: &'a JsonValue, path: &str) -> Result<&'a str, DecodeError> {
334 val.as_str().ok_or_else(|| invalid(path, "expected string"))
335}
336
337fn integer(val: &JsonValue, path: &str) -> Result<i64, DecodeError> {
338 val.as_i64()
339 .ok_or_else(|| invalid(path, "expected signed 64-bit integer"))
340}
341
342fn number(val: &JsonValue, path: &str) -> Result<f64, DecodeError> {
343 val.as_f64()
344 .filter(|n| n.is_finite())
345 .ok_or_else(|| invalid(path, "expected finite number"))
346}
347
348fn array<'a>(val: &'a JsonValue, path: &str) -> Result<&'a [JsonValue], DecodeError> {
349 val.as_array()
350 .map(Vec::as_slice)
351 .ok_or_else(|| invalid(path, "expected array"))
352}
353
354fn keys(obj: &JsonMap<String, JsonValue>, allowed: &[&str], path: &str) -> Result<(), DecodeError> {
355 if let Some(key) = obj.keys().find(|key| !allowed.contains(&key.as_str())) {
356 return Err(invalid(&format!("{path}.{key}"), "unrecognized field"));
357 }
358 Ok(())
359}
360
361pub fn try_json_to_cypher_value(val: &JsonValue) -> Result<CypherValue, DecodeError> {
363 try_json_to_cypher_value_v2(val)
364}
365
366pub fn try_json_to_cypher_value_v2(val: &JsonValue) -> Result<CypherValue, DecodeError> {
397 decode(val, "$", DecodeMode::V2)
398}
399
400pub fn try_json_to_cypher_value_legacy(val: &JsonValue) -> Result<CypherValue, DecodeError> {
403 decode(val, "$", DecodeMode::Legacy)
404}
405
406pub fn try_json_to_param_value(val: &JsonValue) -> Result<CypherValue, DecodeError> {
409 decode(val, "$", DecodeMode::Parameter)
410}
411
412#[derive(Clone, Copy, PartialEq, Eq)]
415enum DecodeMode {
416 Legacy,
417 V2,
418 Parameter,
419}
420
421fn decode_map(
422 obj: &JsonMap<String, JsonValue>,
423 path: &str,
424 mode: DecodeMode,
425) -> Result<CypherValue, DecodeError> {
426 let mut result = IndexMap::new();
427 for (key, value) in obj {
428 let child = format!("{path}.{key}");
429 result.insert(key.clone(), decode(value, &child, mode)?);
430 }
431 Ok(CypherValue::Map(result))
432}
433
434fn decode(val: &JsonValue, path: &str, mode: DecodeMode) -> Result<CypherValue, DecodeError> {
435 match val {
436 JsonValue::Null => Ok(CypherValue::Null),
437 JsonValue::Bool(b) => Ok(CypherValue::Bool(*b)),
438 JsonValue::Number(n) => {
439 if let Some(i) = n.as_i64() {
440 Ok(CypherValue::Int(i))
441 } else if n.is_u64() {
442 Err(invalid(path, "integer exceeds i64 range"))
443 } else {
444 Ok(CypherValue::Float(number(val, path)?))
445 }
446 }
447 JsonValue::String(s) => Ok(CypherValue::Str(s.clone())),
448 JsonValue::Array(items) => items
449 .iter()
450 .enumerate()
451 .map(|(i, item)| decode(item, &format!("{path}[{i}]"), mode))
452 .collect::<Result<Vec<_>, _>>()
453 .map(CypherValue::List),
454 JsonValue::Object(obj) => {
455 if mode == DecodeMode::Parameter {
456 return decode_map(obj, path, mode);
457 }
458 let Some(tag) = obj.get("__type").and_then(JsonValue::as_str) else {
459 return decode_map(obj, path, mode);
460 };
461 if tag == "map" && mode == DecodeMode::V2 {
462 keys(obj, &["__type", "value"], path)?;
463 let contents = field(obj, "value", path)?
464 .as_object()
465 .ok_or_else(|| invalid(&format!("{path}.value"), "expected object"))?;
466 return decode_map(contents, path, mode);
467 }
468 let value = match tag {
469 "date" => {
470 keys(obj, &["__type", "value"], path)?;
471 let s = string(field(obj, "value", path)?, &format!("{path}.value"))?;
472 CypherValue::Date(
473 s.parse::<NaiveDate>()
474 .map_err(|e| invalid(&format!("{path}.value"), e.to_string()))?,
475 )
476 }
477 "time" => {
478 keys(obj, &["__type", "value", "offset"], path)?;
479 let s = string(field(obj, "value", path)?, &format!("{path}.value"))?;
480 let t = NaiveTime::parse_from_str(s, "%H:%M:%S%.f")
481 .map_err(|e| invalid(&format!("{path}.value"), e.to_string()))?;
482 let offset =
483 obj.get("offset")
484 .map(|o| {
485 parse_numeric_offset(string(o, &format!("{path}.offset"))?)
486 .ok_or_else(|| {
487 invalid(
488 &format!("{path}.offset"),
489 "expected ASCII ±HH:MM offset within 24 hours",
490 )
491 })
492 })
493 .transpose()?;
494 CypherValue::Time(t, offset)
495 }
496 "datetime" => {
497 keys(obj, &["__type", "value", "timezone"], path)?;
498 let s = string(field(obj, "value", path)?, &format!("{path}.value"))?;
499 let dt = parse_persistence_datetime(s)
500 .map_err(|e| invalid(&format!("{path}.value"), e.to_string()))?;
501 let tz = obj
502 .get("timezone")
503 .map(|v| string(v, &format!("{path}.timezone")).map(str::to_owned))
504 .transpose()?;
505 CypherValue::DateTime(dt, tz)
506 }
507 "localdatetime" => {
508 keys(obj, &["__type", "value"], path)?;
509 let s = string(field(obj, "value", path)?, &format!("{path}.value"))?;
510 CypherValue::LocalDateTime(
511 NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S%.f")
512 .map_err(|e| invalid(&format!("{path}.value"), e.to_string()))?,
513 )
514 }
515 "duration" => {
516 keys(
517 obj,
518 &["__type", "months", "days", "seconds", "nanoseconds"],
519 path,
520 )?;
521 let component =
522 |name: &str| integer(field(obj, name, path)?, &format!("{path}.{name}"));
523 CypherValue::Duration(IsoDuration::new(
524 component("months")?,
525 component("days")?,
526 component("seconds")?,
527 component("nanoseconds")?,
528 ))
529 }
530 "point" => {
531 keys(obj, &["__type", "srid", "x", "y", "z"], path)?;
532 let srid =
533 i32::try_from(integer(field(obj, "srid", path)?, &format!("{path}.srid"))?)
534 .map_err(|_| {
535 invalid(&format!("{path}.srid"), "SRID exceeds i32 range")
536 })?;
537 let coordinate =
538 |name: &str| number(field(obj, name, path)?, &format!("{path}.{name}"));
539 let z = obj
540 .get("z")
541 .map(|v| number(v, &format!("{path}.z")))
542 .transpose()?;
543 CypherValue::Point(PointValue {
544 srid,
545 x: coordinate("x")?,
546 y: coordinate("y")?,
547 z,
548 })
549 }
550 "geometry" => CypherValue::Geometry(decode_geometry(obj, path, mode)?),
551 "vector" => decode_vector(obj, path)?,
552 _ => return decode_map(obj, path, mode),
553 };
554 Ok(value)
555 }
556 }
557}
558
559fn decode_vector(obj: &JsonMap<String, JsonValue>, path: &str) -> Result<CypherValue, DecodeError> {
560 keys(obj, &["__type", "coord", "dim", "values"], path)?;
561 let coord_path = format!("{path}.coord");
562 let coord =
563 VectorCoordKind::from_canonical_name(string(field(obj, "coord", path)?, &coord_path)?)
564 .ok_or_else(|| invalid(&coord_path, "unknown vector coordinate type"))?;
565 let dim_path = format!("{path}.dim");
566 let dim = usize::try_from(
567 field(obj, "dim", path)?
568 .as_u64()
569 .ok_or_else(|| invalid(&dim_path, "expected nonnegative integer dimension"))?,
570 )
571 .map_err(|_| invalid(&dim_path, "dimension exceeds usize range"))?;
572 let values_path = format!("{path}.values");
573 let items = array(field(obj, "values", path)?, &values_path)?;
574 if dim != items.len() {
575 return Err(invalid(&dim_path, "dimension does not match values length"));
576 }
577 let mut tokens = Vec::with_capacity(items.len());
584 if coord.is_integer() {
585 for (i, item) in items.iter().enumerate() {
586 let at = format!("{values_path}[{i}]");
587 let n = integer(item, &at)?;
588 if !coord.holds_int(n) {
589 return Err(invalid(
590 &at,
591 format!("{} out of range", coord.canonical_name()),
592 ));
593 }
594 tokens.push(Coord::I(n));
595 }
596 } else {
597 for (i, item) in items.iter().enumerate() {
598 let at = format!("{values_path}[{i}]");
599 match item {
600 JsonValue::Number(n) if n.is_i64() || n.is_u64() => {
601 tokens.push(Coord::I(integer(item, &at)?));
602 }
603 _ => {
604 let f = float_number(item, &at)?;
605 if !coord.is_exact(f) {
606 return Err(invalid(
607 &at,
608 format!("{} out of range or loses precision", coord.canonical_name()),
609 ));
610 }
611 tokens.push(Coord::F(f));
612 }
613 }
614 }
615 }
616 let coords = VectorCoords::from_coords(coord, tokens.into_iter())
617 .ok_or_else(|| invalid(&values_path, "coordinates mix integer and float families"))?;
618 Ok(CypherValue::vector(coord, coords))
619}
620
621fn float_number(val: &JsonValue, path: &str) -> Result<f64, DecodeError> {
622 if !val.is_f64() {
623 return Err(invalid(path, "expected floating-point number"));
624 }
625 number(val, path)
626}
627
628fn decode_geometry(
629 obj: &JsonMap<String, JsonValue>,
630 path: &str,
631 mode: DecodeMode,
632) -> Result<GeometryValue, DecodeError> {
633 let srid = i32::try_from(integer(field(obj, "srid", path)?, &format!("{path}.srid"))?)
634 .map_err(|_| invalid(&format!("{path}.srid"), "SRID exceeds i32 range"))?;
635 let kind = string(
636 field(obj, "geometry_type", path)?,
637 &format!("{path}.geometry_type"),
638 )?;
639 let coords_path = format!("{path}.coordinates");
640 let geometry = match kind {
641 "LineString" | "MultiPoint" => {
642 keys(
643 obj,
644 &["__type", "geometry_type", "srid", "coordinates"],
645 path,
646 )?;
647 let coords = decode_coords(field(obj, "coordinates", path)?, &coords_path)?;
648 if kind == "LineString" {
649 GeometryValue::LineString {
650 coordinates: coords,
651 srid,
652 }
653 } else {
654 GeometryValue::MultiPoint {
655 points: coords,
656 srid,
657 }
658 }
659 }
660 "Polygon" | "MultiLineString" => {
661 keys(
662 obj,
663 &["__type", "geometry_type", "srid", "coordinates"],
664 path,
665 )?;
666 let rings = decode_nested_coords(field(obj, "coordinates", path)?, &coords_path)?;
667 if kind == "Polygon" {
668 GeometryValue::Polygon { rings, srid }
669 } else {
670 GeometryValue::MultiLineString { lines: rings, srid }
671 }
672 }
673 "MultiPolygon" => {
674 keys(
675 obj,
676 &["__type", "geometry_type", "srid", "coordinates"],
677 path,
678 )?;
679 let polygons = array(field(obj, "coordinates", path)?, &coords_path)?
680 .iter()
681 .enumerate()
682 .map(|(i, v)| decode_nested_coords(v, &format!("{coords_path}[{i}]")))
683 .collect::<Result<_, _>>()?;
684 GeometryValue::MultiPolygon { polygons, srid }
685 }
686 "GeometryCollection" => {
687 keys(
688 obj,
689 &["__type", "geometry_type", "srid", "geometries"],
690 path,
691 )?;
692 let geometries = array(
693 field(obj, "geometries", path)?,
694 &format!("{path}.geometries"),
695 )?
696 .iter()
697 .enumerate()
698 .map(|(i, item)| {
699 let at = format!("{path}.geometries[{i}]");
700 match decode(item, &at, mode)? {
701 CypherValue::Geometry(g) => Ok(g),
702 _ => Err(invalid(&at, "expected tagged geometry")),
703 }
704 })
705 .collect::<Result<_, _>>()?;
706 GeometryValue::GeometryCollection { geometries, srid }
707 }
708 _ => {
709 return Err(invalid(
710 &format!("{path}.geometry_type"),
711 "unknown geometry type",
712 ))
713 }
714 };
715 Ok(geometry)
716}
717
718fn decode_nested_coords(val: &JsonValue, path: &str) -> Result<Vec<Vec<Coord2D>>, DecodeError> {
719 array(val, path)?
720 .iter()
721 .enumerate()
722 .map(|(i, v)| decode_coords(v, &format!("{path}[{i}]")))
723 .collect()
724}
725
726fn decode_coords(val: &JsonValue, path: &str) -> Result<Vec<Coord2D>, DecodeError> {
727 array(val, path)?
728 .iter()
729 .enumerate()
730 .map(|(i, v)| {
731 let at = format!("{path}[{i}]");
732 let pair = array(v, &at)?;
733 if pair.len() != 2 {
734 return Err(invalid(&at, "expected exactly two coordinates"));
735 }
736 Ok([
737 number(&pair[0], &format!("{at}[0]"))?,
738 number(&pair[1], &format!("{at}[1]"))?,
739 ])
740 })
741 .collect()
742}
743
744pub fn props_to_json(
746 props: &IndexMap<String, CypherValue>,
747) -> Result<JsonMap<String, JsonValue>, EncodeError> {
748 encode_map(props, "$")
749}
750
751pub fn try_json_to_props(
753 obj: &JsonMap<String, JsonValue>,
754) -> Result<IndexMap<String, CypherValue>, DecodeError> {
755 try_json_to_props_v2(obj)
756}
757
758pub fn try_json_to_props_v2(
760 obj: &JsonMap<String, JsonValue>,
761) -> Result<IndexMap<String, CypherValue>, DecodeError> {
762 decode_props(obj, DecodeMode::V2)
763}
764
765pub fn try_json_to_props_legacy(
767 obj: &JsonMap<String, JsonValue>,
768) -> Result<IndexMap<String, CypherValue>, DecodeError> {
769 decode_props(obj, DecodeMode::Legacy)
770}
771
772pub fn try_json_entries_to_props_v2<'a>(
775 entries: impl IntoIterator<Item = (&'a String, &'a JsonValue)>,
776) -> Result<IndexMap<String, CypherValue>, DecodeError> {
777 decode_props(entries, DecodeMode::V2)
778}
779
780pub fn try_json_entries_to_props_legacy<'a>(
782 entries: impl IntoIterator<Item = (&'a String, &'a JsonValue)>,
783) -> Result<IndexMap<String, CypherValue>, DecodeError> {
784 decode_props(entries, DecodeMode::Legacy)
785}
786
787fn decode_props<'a>(
788 entries: impl IntoIterator<Item = (&'a String, &'a JsonValue)>,
789 mode: DecodeMode,
790) -> Result<IndexMap<String, CypherValue>, DecodeError> {
791 entries
792 .into_iter()
793 .map(|(key, value)| Ok((key.clone(), decode(value, &format!("$.{key}"), mode)?)))
794 .collect()
795}
796
797impl serde::Serialize for CypherValue {
800 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
801 where
802 S: serde::Serializer,
803 {
804 let json = cypher_value_to_json(self).map_err(serde::ser::Error::custom)?;
805 json.serialize(serializer)
806 }
807}
808
809impl<'de> serde::Deserialize<'de> for CypherValue {
810 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
811 where
812 D: serde::Deserializer<'de>,
813 {
814 let json = JsonValue::deserialize(deserializer)?;
815 try_json_to_cypher_value(&json).map_err(serde::de::Error::custom)
816 }
817}
818
819fn parse_persistence_datetime(s: &str) -> Result<DateTime<FixedOffset>, chrono::ParseError> {
822 match DateTime::parse_from_rfc3339(s) {
823 Ok(dt) => Ok(dt),
824 Err(original) => {
825 let bytes = s.as_bytes();
826 let year_end = 1 + bytes
827 .iter()
828 .skip(1)
829 .take_while(|b| b.is_ascii_digit())
830 .count();
831 if !matches!(bytes.first(), Some(b'+' | b'-'))
832 || year_end < 6
833 || bytes.get(year_end) != Some(&b'-')
834 {
835 return Err(original);
836 }
837 let dt = DateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S%.f%:z")?;
838 if dt
839 .naive_utc()
840 .checked_add_signed(Duration::seconds(i64::from(dt.offset().local_minus_utc())))
841 .is_some()
842 && dt.to_rfc3339() == s
843 {
844 Ok(dt)
845 } else {
846 Err(original)
847 }
848 }
849 }
850}
851
852pub fn parse_numeric_offset(s: &str) -> Option<FixedOffset> {
868 let bytes = s.as_bytes();
869 if bytes.len() != 6 || !bytes.is_ascii() || bytes[3] != b':' {
870 return None;
871 }
872 let sign: i32 = match bytes[0] {
873 b'+' => 1,
874 b'-' => -1,
875 _ => return None,
876 };
877 let digit = |b: u8| -> Option<i32> { b.is_ascii_digit().then(|| i32::from(b - b'0')) };
878 let h = digit(bytes[1])?
879 .checked_mul(10)?
880 .checked_add(digit(bytes[2])?)?;
881 let m = digit(bytes[4])?
882 .checked_mul(10)?
883 .checked_add(digit(bytes[5])?)?;
884 if m > 59 {
885 return None;
886 }
887 let seconds = h
888 .checked_mul(3600)?
889 .checked_add(m.checked_mul(60)?)?
890 .checked_mul(sign)?;
891 FixedOffset::east_opt(seconds)
892}
893
894#[cfg(test)]
895mod tests;