1use alloc::borrow::ToOwned;
23use alloc::format;
24use alloc::string::{String, ToString};
25use alloc::vec::Vec;
26use core::fmt;
27
28use serde::de::DeserializeOwned;
29use serde_json::value::RawValue;
30
31use crate::validate::{Validate, ViolationKind};
32
33#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
35pub enum UnknownEnumValues {
36 #[default]
38 Reject,
39 Preserve,
41}
42
43#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
48pub enum UnknownFields {
49 Reject,
51 #[default]
53 Ignore,
54}
55
56#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
58pub enum DateTimeLeniency {
59 #[default]
61 Strict,
62 AllowNaive,
64 AllowSpace,
66}
67
68#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
70pub enum NumericStrings {
71 #[default]
73 Reject,
74 Coerce,
76}
77
78#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
86pub enum WholeFloats {
87 #[default]
89 Reject,
90 Coerce,
92}
93
94#[derive(Clone, Debug, PartialEq, Eq)]
96#[non_exhaustive]
97pub struct DecodeOptions {
98 pub unknown_enum_values: UnknownEnumValues,
100 pub unknown_fields: UnknownFields,
102 pub datetime: DateTimeLeniency,
104 pub numeric_strings: NumericStrings,
106 pub whole_floats: WholeFloats,
108 pub max_payload_size: usize,
117 pub max_repairs: usize,
119}
120
121impl Default for DecodeOptions {
122 fn default() -> Self {
123 Self::strict()
124 }
125}
126
127impl DecodeOptions {
128 #[must_use]
130 pub const fn strict() -> Self {
131 Self {
132 unknown_enum_values: UnknownEnumValues::Reject,
133 unknown_fields: UnknownFields::Ignore,
134 datetime: DateTimeLeniency::Strict,
135 numeric_strings: NumericStrings::Reject,
136 whole_floats: WholeFloats::Reject,
137 max_payload_size: 1024 * 1024,
138 max_repairs: 32,
139 }
140 }
141
142 #[must_use]
147 pub const fn pedantic() -> Self {
148 Self {
149 unknown_fields: UnknownFields::Reject,
150 ..Self::strict()
151 }
152 }
153
154 #[must_use]
158 pub const fn lenient() -> Self {
159 Self {
160 unknown_enum_values: UnknownEnumValues::Preserve,
161 unknown_fields: UnknownFields::Ignore,
162 datetime: DateTimeLeniency::AllowSpace,
163 numeric_strings: NumericStrings::Coerce,
164 whole_floats: WholeFloats::Coerce,
165 max_payload_size: 1024 * 1024,
166 max_repairs: 32,
167 }
168 }
169
170 #[must_use]
172 pub const fn with_max_payload_size(mut self, bytes: usize) -> Self {
173 self.max_payload_size = bytes;
174 self
175 }
176
177 #[must_use]
179 pub const fn with_unknown_enum_values(mut self, policy: UnknownEnumValues) -> Self {
180 self.unknown_enum_values = policy;
181 self
182 }
183
184 #[must_use]
186 pub const fn with_unknown_fields(mut self, policy: UnknownFields) -> Self {
187 self.unknown_fields = policy;
188 self
189 }
190
191 #[must_use]
193 pub const fn with_datetime(mut self, policy: DateTimeLeniency) -> Self {
194 self.datetime = policy;
195 self
196 }
197
198 #[must_use]
200 pub const fn with_numeric_strings(mut self, policy: NumericStrings) -> Self {
201 self.numeric_strings = policy;
202 self
203 }
204
205 #[must_use]
207 pub const fn with_whole_floats(mut self, policy: WholeFloats) -> Self {
208 self.whole_floats = policy;
209 self
210 }
211
212 #[must_use]
214 pub const fn with_max_repairs(mut self, repairs: usize) -> Self {
215 self.max_repairs = repairs;
216 self
217 }
218
219 fn repairs_enabled(&self) -> bool {
220 self.datetime != DateTimeLeniency::Strict
221 || self.numeric_strings == NumericStrings::Coerce
222 || self.whole_floats == WholeFloats::Coerce
223 }
224}
225
226#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
228#[non_exhaustive]
229pub enum DecodeErrorKind {
230 Format,
232 Occurrence,
234 Type,
236 Property,
238 UnknownField,
240 Protocol,
242 UnsupportedAction,
244}
245
246#[derive(Clone, Debug, PartialEq, Eq)]
248pub struct DecodeError {
249 pub kind: DecodeErrorKind,
251 pub path: String,
253 pub reason: String,
255}
256
257impl DecodeError {
258 #[must_use]
260 pub fn new(kind: DecodeErrorKind, path: impl Into<String>, reason: impl Into<String>) -> Self {
261 Self {
262 kind,
263 path: path.into(),
264 reason: reason.into(),
265 }
266 }
267
268 #[must_use]
270 pub fn unsupported_action(action: &str) -> Self {
271 Self::new(
272 DecodeErrorKind::UnsupportedAction,
273 "",
274 format!("action {action:?} is not valid in this direction"),
275 )
276 }
277
278 #[must_use]
279 fn from_violation(violation: &crate::validate::Violation) -> Self {
280 let kind = match violation.kind {
281 ViolationKind::Occurrence => DecodeErrorKind::Occurrence,
282 ViolationKind::Type => DecodeErrorKind::Type,
283 ViolationKind::Property | ViolationKind::UnknownEnumValue => DecodeErrorKind::Property,
284 ViolationKind::UnknownField => DecodeErrorKind::UnknownField,
285 ViolationKind::Protocol => DecodeErrorKind::Protocol,
286 };
287 Self::new(kind, violation.path.clone(), violation.reason.clone())
288 }
289}
290
291impl fmt::Display for DecodeError {
292 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
293 if self.path.is_empty() {
294 write!(f, "{}", self.reason)
295 } else {
296 write!(f, "{}: {}", self.path, self.reason)
297 }
298 }
299}
300
301#[cfg(feature = "std")]
302impl std::error::Error for DecodeError {}
303
304#[derive(Clone, Debug, PartialEq, Eq)]
311pub struct Repair {
312 pub pointer: String,
314 pub kind: RepairKind,
316}
317
318#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
320#[non_exhaustive]
321pub enum RepairKind {
322 NumericString,
324 DateTimeWithoutOffset,
326 DateTimeWithSpace,
328 WholeFloat,
330 UnknownEnumValue,
333}
334
335impl RepairKind {
336 #[must_use]
338 pub const fn as_str(self) -> &'static str {
339 match self {
340 RepairKind::NumericString => "numeric_string",
341 RepairKind::DateTimeWithoutOffset => "datetime_without_offset",
342 RepairKind::DateTimeWithSpace => "datetime_with_space",
343 RepairKind::WholeFloat => "whole_float",
344 RepairKind::UnknownEnumValue => "unknown_enum_value",
345 }
346 }
347}
348
349impl fmt::Display for RepairKind {
350 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
351 f.write_str(self.as_str())
352 }
353}
354
355#[derive(Clone, Debug, PartialEq)]
357pub struct Decoded<T> {
358 pub value: T,
360 pub repairs: Vec<Repair>,
362}
363
364impl<T> Decoded<T> {
365 pub fn map<U>(self, f: impl FnOnce(T) -> U) -> Decoded<U> {
367 Decoded {
368 value: f(self.value),
369 repairs: self.repairs,
370 }
371 }
372}
373
374pub fn decode_payload<T: DeserializeOwned + serde::Serialize + Validate>(
380 payload: &RawValue,
381 options: &DecodeOptions,
382) -> Result<T, DecodeError> {
383 decode_payload_reporting(payload, options).map(|decoded| decoded.value)
384}
385
386pub fn decode_payload_reporting<T: DeserializeOwned + serde::Serialize + Validate>(
388 payload: &RawValue,
389 options: &DecodeOptions,
390) -> Result<Decoded<T>, DecodeError> {
391 let mut repairs = Vec::new();
392 let text = payload.get();
393 if text.len() > options.max_payload_size {
394 return Err(DecodeError::new(
395 DecodeErrorKind::Format,
396 "",
397 format!(
398 "payload is {} bytes, limit is {}",
399 text.len(),
400 options.max_payload_size
401 ),
402 ));
403 }
404 if !text.trim_start().starts_with('{') {
406 return Err(DecodeError::new(
407 DecodeErrorKind::Format,
408 "",
409 "payload is not a JSON object",
410 ));
411 }
412
413 let value: T = match parse(text) {
414 Ok(value) => value,
415 Err(error) if options.repairs_enabled() => {
416 repair_and_parse(text, options, &error, &mut repairs)?
417 }
418 Err(error) => return Err(error),
419 };
420
421 if options.unknown_fields == UnknownFields::Reject {
422 if let Some(path) = first_unknown_field(text, &value)? {
423 return Err(DecodeError::new(
424 DecodeErrorKind::UnknownField,
425 path,
426 "member is not defined by the schema",
427 ));
428 }
429 }
430
431 let mut violations = match value.validate() {
432 Ok(()) => return Ok(Decoded { value, repairs }),
433 Err(violations) => violations,
434 };
435 if options.unknown_enum_values == UnknownEnumValues::Preserve {
436 repairs.extend(
437 violations
438 .as_slice()
439 .iter()
440 .filter(|v| v.kind == ViolationKind::UnknownEnumValue)
441 .map(|v| Repair {
442 pointer: v.path.clone(),
443 kind: RepairKind::UnknownEnumValue,
444 }),
445 );
446 violations.retain_kinds(|kind| kind != ViolationKind::UnknownEnumValue);
447 }
448 match violations.first() {
449 Some(violation) => Err(DecodeError::from_violation(violation)),
450 None => Ok(Decoded { value, repairs }),
451 }
452}
453
454pub fn transcode<T: DeserializeOwned + serde::Serialize + Validate>(
460 payload: &RawValue,
461 options: &DecodeOptions,
462) -> Result<alloc::boxed::Box<RawValue>, DecodeError> {
463 let value = decode_payload::<T>(payload, options)?;
464 serde_json::value::to_raw_value(&value)
465 .map_err(|error| DecodeError::new(DecodeErrorKind::Format, "", error.to_string()))
466}
467
468fn parse<T: DeserializeOwned>(text: &str) -> Result<T, DecodeError> {
469 let mut deserializer = serde_json::Deserializer::from_str(text);
470 match serde_path_to_error::deserialize(&mut deserializer) {
471 Ok(value) => Ok(value),
472 Err(error) => Err(classify(&error)),
473 }
474}
475
476fn classify(error: &serde_path_to_error::Error<serde_json::Error>) -> DecodeError {
482 let path = pointer_from(&error.path().to_string());
483 let inner = error.inner();
484 let message = inner.to_string();
485 let kind = match inner.classify() {
486 serde_json::error::Category::Syntax | serde_json::error::Category::Eof => {
487 DecodeErrorKind::Format
488 }
489 serde_json::error::Category::Io => DecodeErrorKind::Format,
490 serde_json::error::Category::Data => {
491 if message.starts_with("missing field") || message.starts_with("invalid length") {
493 DecodeErrorKind::Occurrence
494 } else if message.starts_with("invalid type") {
495 DecodeErrorKind::Type
496 } else if message.starts_with("unknown field") {
497 DecodeErrorKind::UnknownField
498 } else if message.starts_with("duplicate field") {
499 DecodeErrorKind::Format
500 } else {
501 DecodeErrorKind::Property
504 }
505 }
506 };
507 let reason = match message.rfind(" at line ") {
509 Some(cut) => message[..cut].to_owned(),
510 None => message,
511 };
512 DecodeError::new(kind, path, reason)
513}
514
515fn pointer_from(path: &str) -> String {
517 if path.is_empty() || path == "." {
518 return String::new();
519 }
520 let mut out = String::with_capacity(path.len() + 1);
521 for segment in path.split('.') {
522 out.push('/');
523 out.push_str(&segment.replace('~', "~0").replace('/', "~1"));
524 }
525 out
526}
527
528fn repair_and_parse<T: DeserializeOwned>(
535 text: &str,
536 options: &DecodeOptions,
537 first: &DecodeError,
538 repairs: &mut Vec<Repair>,
539) -> Result<T, DecodeError> {
540 let mut json: serde_json::Value = serde_json::from_str(text)
541 .map_err(|error| DecodeError::new(DecodeErrorKind::Format, "", error.to_string()))?;
542
543 let mut error = first.clone();
544 for _ in 0..options.max_repairs {
545 let Some(kind) = apply_repair(&mut json, &error, options) else {
546 return Err(error);
547 };
548 repairs.push(Repair {
549 pointer: error.path.clone(),
550 kind,
551 });
552 match serde_path_to_error::deserialize::<_, T>(&json) {
553 Ok(value) => return Ok(value),
554 Err(next) => {
555 let next = classify(&next);
556 if next == error {
557 return Err(next);
558 }
559 error = next;
560 }
561 }
562 }
563 Err(error)
564}
565
566fn apply_repair(
569 json: &mut serde_json::Value,
570 error: &DecodeError,
571 options: &DecodeOptions,
572) -> Option<RepairKind> {
573 let slot = pointer_mut(json, &error.path)?;
574
575 if options.whole_floats == WholeFloats::Coerce && error.kind == DecodeErrorKind::Type {
577 if let Some(whole) = slot
578 .as_f64()
579 .filter(|_| slot.is_f64())
580 .and_then(whole_number)
581 {
582 *slot = serde_json::Value::from(whole);
583 return Some(RepairKind::WholeFloat);
584 }
585 }
586
587 let text = slot.as_str().map(ToOwned::to_owned)?;
588
589 if options.numeric_strings == NumericStrings::Coerce && error.kind == DecodeErrorKind::Type {
591 if let Ok(number) = text.parse::<serde_json::Number>() {
592 *slot = serde_json::Value::Number(number);
593 return Some(RepairKind::NumericString);
594 }
595 }
596
597 if options.datetime != DateTimeLeniency::Strict && error.kind == DecodeErrorKind::Property {
599 let allow_space = options.datetime == DateTimeLeniency::AllowSpace;
600 if !allow_space && text.contains(' ') {
601 return None;
602 }
603 let normalized = crate::types::normalize_datetime(&text);
604 if normalized != text && crate::types::DateTime::parse(&normalized).is_ok() {
605 *slot = serde_json::Value::String(normalized);
606 return Some(if text.contains(' ') {
607 RepairKind::DateTimeWithSpace
608 } else {
609 RepairKind::DateTimeWithoutOffset
610 });
611 }
612 }
613 None
614}
615
616#[allow(
618 clippy::cast_possible_truncation,
619 clippy::float_cmp,
620 clippy::cast_precision_loss
621)]
622fn whole_number(v: f64) -> Option<i64> {
623 (v.is_finite() && v.abs() < 9.0e15 && (v as i64) as f64 == v).then_some(v as i64)
624}
625
626fn pointer_mut<'a>(
628 value: &'a mut serde_json::Value,
629 pointer: &str,
630) -> Option<&'a mut serde_json::Value> {
631 if pointer.is_empty() {
632 return Some(value);
633 }
634 let mut current = value;
635 for raw in pointer.trim_start_matches('/').split('/') {
636 let key = raw.replace("~1", "/").replace("~0", "~");
637 current = match current {
638 serde_json::Value::Object(map) => map.get_mut(&key)?,
639 serde_json::Value::Array(items) => items.get_mut(key.parse::<usize>().ok()?)?,
640 _ => return None,
641 };
642 }
643 Some(current)
644}
645
646fn first_unknown_field<T: serde::Serialize>(
656 text: &str,
657 value: &T,
658) -> Result<Option<String>, DecodeError> {
659 let wire: serde_json::Value = serde_json::from_str(text)
660 .map_err(|error| DecodeError::new(DecodeErrorKind::Format, "", error.to_string()))?;
661 let ours = serde_json::to_value(value)
662 .map_err(|error| DecodeError::new(DecodeErrorKind::Format, "", error.to_string()))?;
663 let mut path = Vec::new();
664 Ok(diff(&wire, &ours, &mut path))
665}
666
667fn diff(
668 wire: &serde_json::Value,
669 ours: &serde_json::Value,
670 path: &mut Vec<String>,
671) -> Option<String> {
672 match (wire, ours) {
673 (serde_json::Value::Object(w), serde_json::Value::Object(o)) => {
674 for (key, value) in w {
675 if value.is_null() {
676 continue; }
678 path.push(key.replace('~', "~0").replace('/', "~1"));
679 let found = match o.get(key) {
680 None => Some(render(path)),
681 Some(mine) => diff(value, mine, path),
682 };
683 path.pop();
684 if found.is_some() {
685 return found;
686 }
687 }
688 None
689 }
690 (serde_json::Value::Array(w), serde_json::Value::Array(o)) => {
691 for (index, (value, mine)) in w.iter().zip(o).enumerate() {
692 path.push(index.to_string());
693 let found = diff(value, mine, path);
694 path.pop();
695 if found.is_some() {
696 return found;
697 }
698 }
699 None
700 }
701 _ => None,
702 }
703}
704
705fn render(path: &[String]) -> String {
706 let mut out = String::new();
707 for segment in path {
708 out.push('/');
709 out.push_str(segment);
710 }
711 out
712}