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 from_str<T: DeserializeOwned + serde::Serialize + Validate>(
408 text: &str,
409) -> Result<T, DecodeError> {
410 let payload = RawValue::from_string(text.to_owned())
411 .map_err(|error| DecodeError::new(DecodeErrorKind::Format, "", error.to_string()))?;
412 decode_payload(&payload, &DecodeOptions::strict())
413}
414
415pub fn decode_payload_reporting<T: DeserializeOwned + serde::Serialize + Validate>(
417 payload: &RawValue,
418 options: &DecodeOptions,
419) -> Result<Decoded<T>, DecodeError> {
420 let mut repairs = Vec::new();
421 let text = payload.get();
422 if text.len() > options.max_payload_size {
423 return Err(DecodeError::new(
424 DecodeErrorKind::Format,
425 "",
426 format!(
427 "payload is {} bytes, limit is {}",
428 text.len(),
429 options.max_payload_size
430 ),
431 ));
432 }
433 if !text.trim_start().starts_with('{') {
435 return Err(DecodeError::new(
436 DecodeErrorKind::Format,
437 "",
438 "payload is not a JSON object",
439 ));
440 }
441
442 let value: T = match parse(text) {
443 Ok(value) => value,
444 Err(error) if options.repairs_enabled() => {
445 repair_and_parse(text, options, &error, &mut repairs)?
446 }
447 Err(error) => return Err(error),
448 };
449
450 if options.unknown_fields == UnknownFields::Reject {
451 if let Some(path) = first_unknown_field(text, &value)? {
452 return Err(DecodeError::new(
453 DecodeErrorKind::UnknownField,
454 path,
455 "member is not defined by the schema",
456 ));
457 }
458 }
459
460 let mut violations = match value.validate() {
461 Ok(()) => return Ok(Decoded { value, repairs }),
462 Err(violations) => violations,
463 };
464 if options.unknown_enum_values == UnknownEnumValues::Preserve {
465 repairs.extend(
466 violations
467 .as_slice()
468 .iter()
469 .filter(|v| v.kind == ViolationKind::UnknownEnumValue)
470 .map(|v| Repair {
471 pointer: v.path.clone(),
472 kind: RepairKind::UnknownEnumValue,
473 }),
474 );
475 violations.retain_kinds(|kind| kind != ViolationKind::UnknownEnumValue);
476 }
477 match violations.first() {
478 Some(violation) => Err(DecodeError::from_violation(violation)),
479 None => Ok(Decoded { value, repairs }),
480 }
481}
482
483pub fn transcode<T: DeserializeOwned + serde::Serialize + Validate>(
489 payload: &RawValue,
490 options: &DecodeOptions,
491) -> Result<alloc::boxed::Box<RawValue>, DecodeError> {
492 let value = decode_payload::<T>(payload, options)?;
493 serde_json::value::to_raw_value(&value)
494 .map_err(|error| DecodeError::new(DecodeErrorKind::Format, "", error.to_string()))
495}
496
497fn parse<T: DeserializeOwned>(text: &str) -> Result<T, DecodeError> {
498 let mut deserializer = serde_json::Deserializer::from_str(text);
499 match serde_path_to_error::deserialize(&mut deserializer) {
500 Ok(value) => Ok(value),
501 Err(error) => Err(classify(&error)),
502 }
503}
504
505fn classify(error: &serde_path_to_error::Error<serde_json::Error>) -> DecodeError {
511 let path = pointer_from(&error.path().to_string());
512 let inner = error.inner();
513 let message = inner.to_string();
514 let kind = match inner.classify() {
515 serde_json::error::Category::Syntax | serde_json::error::Category::Eof => {
516 DecodeErrorKind::Format
517 }
518 serde_json::error::Category::Io => DecodeErrorKind::Format,
519 serde_json::error::Category::Data => {
520 if message.starts_with("missing field") || message.starts_with("invalid length") {
522 DecodeErrorKind::Occurrence
523 } else if message.starts_with("invalid type") {
524 DecodeErrorKind::Type
525 } else if message.starts_with("unknown field") {
526 DecodeErrorKind::UnknownField
527 } else if message.starts_with("duplicate field") {
528 DecodeErrorKind::Format
529 } else {
530 DecodeErrorKind::Property
533 }
534 }
535 };
536 let reason = match message.rfind(" at line ") {
538 Some(cut) => message[..cut].to_owned(),
539 None => message,
540 };
541 DecodeError::new(kind, path, reason)
542}
543
544fn pointer_from(path: &str) -> String {
546 if path.is_empty() || path == "." {
547 return String::new();
548 }
549 let mut out = String::with_capacity(path.len() + 1);
550 for segment in path.split('.') {
551 out.push('/');
552 out.push_str(&segment.replace('~', "~0").replace('/', "~1"));
553 }
554 out
555}
556
557fn repair_and_parse<T: DeserializeOwned>(
564 text: &str,
565 options: &DecodeOptions,
566 first: &DecodeError,
567 repairs: &mut Vec<Repair>,
568) -> Result<T, DecodeError> {
569 let mut json: serde_json::Value = serde_json::from_str(text)
570 .map_err(|error| DecodeError::new(DecodeErrorKind::Format, "", error.to_string()))?;
571
572 let mut error = first.clone();
573 for _ in 0..options.max_repairs {
574 let Some(kind) = apply_repair(&mut json, &error, options) else {
575 return Err(error);
576 };
577 repairs.push(Repair {
578 pointer: error.path.clone(),
579 kind,
580 });
581 match serde_path_to_error::deserialize::<_, T>(&json) {
582 Ok(value) => return Ok(value),
583 Err(next) => {
584 let next = classify(&next);
585 if next == error {
586 return Err(next);
587 }
588 error = next;
589 }
590 }
591 }
592 Err(error)
593}
594
595fn apply_repair(
598 json: &mut serde_json::Value,
599 error: &DecodeError,
600 options: &DecodeOptions,
601) -> Option<RepairKind> {
602 let slot = pointer_mut(json, &error.path)?;
603
604 if options.whole_floats == WholeFloats::Coerce && error.kind == DecodeErrorKind::Type {
606 if let Some(whole) = slot
607 .as_f64()
608 .filter(|_| slot.is_f64())
609 .and_then(whole_number)
610 {
611 *slot = serde_json::Value::from(whole);
612 return Some(RepairKind::WholeFloat);
613 }
614 }
615
616 let text = slot.as_str().map(ToOwned::to_owned)?;
617
618 if options.numeric_strings == NumericStrings::Coerce && error.kind == DecodeErrorKind::Type {
620 if let Ok(number) = text.parse::<serde_json::Number>() {
621 *slot = serde_json::Value::Number(number);
622 return Some(RepairKind::NumericString);
623 }
624 }
625
626 if options.datetime != DateTimeLeniency::Strict && error.kind == DecodeErrorKind::Property {
628 let allow_space = options.datetime == DateTimeLeniency::AllowSpace;
629 if !allow_space && text.contains(' ') {
630 return None;
631 }
632 let normalized = crate::types::normalize_datetime(&text);
633 if normalized != text && crate::types::DateTime::parse(&normalized).is_ok() {
634 *slot = serde_json::Value::String(normalized);
635 return Some(if text.contains(' ') {
636 RepairKind::DateTimeWithSpace
637 } else {
638 RepairKind::DateTimeWithoutOffset
639 });
640 }
641 }
642 None
643}
644
645#[allow(
647 clippy::cast_possible_truncation,
648 clippy::float_cmp,
649 clippy::cast_precision_loss
650)]
651fn whole_number(v: f64) -> Option<i64> {
652 (v.is_finite() && v.abs() < 9.0e15 && (v as i64) as f64 == v).then_some(v as i64)
653}
654
655fn pointer_mut<'a>(
657 value: &'a mut serde_json::Value,
658 pointer: &str,
659) -> Option<&'a mut serde_json::Value> {
660 if pointer.is_empty() {
661 return Some(value);
662 }
663 let mut current = value;
664 for raw in pointer.trim_start_matches('/').split('/') {
665 let key = raw.replace("~1", "/").replace("~0", "~");
666 current = match current {
667 serde_json::Value::Object(map) => map.get_mut(&key)?,
668 serde_json::Value::Array(items) => items.get_mut(key.parse::<usize>().ok()?)?,
669 _ => return None,
670 };
671 }
672 Some(current)
673}
674
675fn first_unknown_field<T: serde::Serialize>(
685 text: &str,
686 value: &T,
687) -> Result<Option<String>, DecodeError> {
688 let wire: serde_json::Value = serde_json::from_str(text)
689 .map_err(|error| DecodeError::new(DecodeErrorKind::Format, "", error.to_string()))?;
690 let ours = serde_json::to_value(value)
691 .map_err(|error| DecodeError::new(DecodeErrorKind::Format, "", error.to_string()))?;
692 let mut path = Vec::new();
693 Ok(diff(&wire, &ours, &mut path))
694}
695
696fn diff(
697 wire: &serde_json::Value,
698 ours: &serde_json::Value,
699 path: &mut Vec<String>,
700) -> Option<String> {
701 match (wire, ours) {
702 (serde_json::Value::Object(w), serde_json::Value::Object(o)) => {
703 for (key, value) in w {
704 if value.is_null() {
705 continue; }
707 path.push(key.replace('~', "~0").replace('/', "~1"));
708 let found = match o.get(key) {
709 None => Some(render(path)),
710 Some(mine) => diff(value, mine, path),
711 };
712 path.pop();
713 if found.is_some() {
714 return found;
715 }
716 }
717 None
718 }
719 (serde_json::Value::Array(w), serde_json::Value::Array(o)) => {
720 for (index, (value, mine)) in w.iter().zip(o).enumerate() {
721 path.push(index.to_string());
722 let found = diff(value, mine, path);
723 path.pop();
724 if found.is_some() {
725 return found;
726 }
727 }
728 None
729 }
730 _ => None,
731 }
732}
733
734fn render(path: &[String]) -> String {
735 let mut out = String::new();
736 for segment in path {
737 out.push('/');
738 out.push_str(segment);
739 }
740 out
741}