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, Debug, PartialEq, Eq)]
80#[non_exhaustive]
81pub struct DecodeOptions {
82 pub unknown_enum_values: UnknownEnumValues,
84 pub unknown_fields: UnknownFields,
86 pub datetime: DateTimeLeniency,
88 pub numeric_strings: NumericStrings,
90 pub max_payload_size: usize,
99 pub max_repairs: usize,
101}
102
103impl Default for DecodeOptions {
104 fn default() -> Self {
105 Self::strict()
106 }
107}
108
109impl DecodeOptions {
110 #[must_use]
112 pub const fn strict() -> Self {
113 Self {
114 unknown_enum_values: UnknownEnumValues::Reject,
115 unknown_fields: UnknownFields::Ignore,
116 datetime: DateTimeLeniency::Strict,
117 numeric_strings: NumericStrings::Reject,
118 max_payload_size: 1024 * 1024,
119 max_repairs: 32,
120 }
121 }
122
123 #[must_use]
128 pub const fn pedantic() -> Self {
129 Self {
130 unknown_fields: UnknownFields::Reject,
131 ..Self::strict()
132 }
133 }
134
135 #[must_use]
139 pub const fn lenient() -> Self {
140 Self {
141 unknown_enum_values: UnknownEnumValues::Preserve,
142 unknown_fields: UnknownFields::Ignore,
143 datetime: DateTimeLeniency::AllowSpace,
144 numeric_strings: NumericStrings::Coerce,
145 max_payload_size: 1024 * 1024,
146 max_repairs: 32,
147 }
148 }
149
150 #[must_use]
152 pub const fn with_max_payload_size(mut self, bytes: usize) -> Self {
153 self.max_payload_size = bytes;
154 self
155 }
156
157 fn repairs_enabled(&self) -> bool {
158 self.datetime != DateTimeLeniency::Strict || self.numeric_strings == NumericStrings::Coerce
159 }
160}
161
162#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
164#[non_exhaustive]
165pub enum DecodeErrorKind {
166 Format,
168 Occurrence,
170 Type,
172 Property,
174 UnknownField,
176 Protocol,
178 UnsupportedAction,
180}
181
182#[derive(Clone, Debug, PartialEq, Eq)]
184pub struct DecodeError {
185 pub kind: DecodeErrorKind,
187 pub path: String,
189 pub reason: String,
191}
192
193impl DecodeError {
194 #[must_use]
196 pub fn new(kind: DecodeErrorKind, path: impl Into<String>, reason: impl Into<String>) -> Self {
197 Self {
198 kind,
199 path: path.into(),
200 reason: reason.into(),
201 }
202 }
203
204 #[must_use]
206 pub fn unsupported_action(action: &str) -> Self {
207 Self::new(
208 DecodeErrorKind::UnsupportedAction,
209 "",
210 format!("action {action:?} is not valid in this direction"),
211 )
212 }
213
214 #[must_use]
215 fn from_violation(violation: &crate::validate::Violation) -> Self {
216 let kind = match violation.kind {
217 ViolationKind::Occurrence => DecodeErrorKind::Occurrence,
218 ViolationKind::Type => DecodeErrorKind::Type,
219 ViolationKind::Property | ViolationKind::UnknownEnumValue => DecodeErrorKind::Property,
220 ViolationKind::UnknownField => DecodeErrorKind::UnknownField,
221 ViolationKind::Protocol => DecodeErrorKind::Protocol,
222 };
223 Self::new(kind, violation.path.clone(), violation.reason.clone())
224 }
225}
226
227impl fmt::Display for DecodeError {
228 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
229 if self.path.is_empty() {
230 write!(f, "{}", self.reason)
231 } else {
232 write!(f, "{}: {}", self.path, self.reason)
233 }
234 }
235}
236
237#[cfg(feature = "std")]
238impl std::error::Error for DecodeError {}
239
240pub fn decode_payload<T: DeserializeOwned + serde::Serialize + Validate>(
245 payload: &RawValue,
246 options: &DecodeOptions,
247) -> Result<T, DecodeError> {
248 let text = payload.get();
249 if text.len() > options.max_payload_size {
250 return Err(DecodeError::new(
251 DecodeErrorKind::Format,
252 "",
253 format!(
254 "payload is {} bytes, limit is {}",
255 text.len(),
256 options.max_payload_size
257 ),
258 ));
259 }
260 if !text.trim_start().starts_with('{') {
262 return Err(DecodeError::new(
263 DecodeErrorKind::Format,
264 "",
265 "payload is not a JSON object",
266 ));
267 }
268
269 let value: T = match parse(text) {
270 Ok(value) => value,
271 Err(error) if options.repairs_enabled() => repair_and_parse(text, options, &error)?,
272 Err(error) => return Err(error),
273 };
274
275 if options.unknown_fields == UnknownFields::Reject {
276 if let Some(path) = first_unknown_field(text, &value)? {
277 return Err(DecodeError::new(
278 DecodeErrorKind::UnknownField,
279 path,
280 "member is not defined by the schema",
281 ));
282 }
283 }
284
285 let mut violations = match value.validate() {
286 Ok(()) => return Ok(value),
287 Err(violations) => violations,
288 };
289 if options.unknown_enum_values == UnknownEnumValues::Preserve {
290 violations.retain_kinds(|kind| kind != ViolationKind::UnknownEnumValue);
291 }
292 match violations.first() {
293 Some(violation) => Err(DecodeError::from_violation(violation)),
294 None => Ok(value),
295 }
296}
297
298pub fn transcode<T: DeserializeOwned + serde::Serialize + Validate>(
304 payload: &RawValue,
305 options: &DecodeOptions,
306) -> Result<alloc::boxed::Box<RawValue>, DecodeError> {
307 let value = decode_payload::<T>(payload, options)?;
308 serde_json::value::to_raw_value(&value)
309 .map_err(|error| DecodeError::new(DecodeErrorKind::Format, "", error.to_string()))
310}
311
312fn parse<T: DeserializeOwned>(text: &str) -> Result<T, DecodeError> {
313 let mut deserializer = serde_json::Deserializer::from_str(text);
314 match serde_path_to_error::deserialize(&mut deserializer) {
315 Ok(value) => Ok(value),
316 Err(error) => Err(classify(&error)),
317 }
318}
319
320fn classify(error: &serde_path_to_error::Error<serde_json::Error>) -> DecodeError {
326 let path = pointer_from(&error.path().to_string());
327 let inner = error.inner();
328 let message = inner.to_string();
329 let kind = match inner.classify() {
330 serde_json::error::Category::Syntax | serde_json::error::Category::Eof => {
331 DecodeErrorKind::Format
332 }
333 serde_json::error::Category::Io => DecodeErrorKind::Format,
334 serde_json::error::Category::Data => {
335 if message.starts_with("missing field") || message.starts_with("invalid length") {
337 DecodeErrorKind::Occurrence
338 } else if message.starts_with("invalid type") {
339 DecodeErrorKind::Type
340 } else if message.starts_with("unknown field") {
341 DecodeErrorKind::UnknownField
342 } else if message.starts_with("duplicate field") {
343 DecodeErrorKind::Format
344 } else {
345 DecodeErrorKind::Property
348 }
349 }
350 };
351 let reason = match message.rfind(" at line ") {
353 Some(cut) => message[..cut].to_owned(),
354 None => message,
355 };
356 DecodeError::new(kind, path, reason)
357}
358
359fn pointer_from(path: &str) -> String {
361 if path.is_empty() || path == "." {
362 return String::new();
363 }
364 let mut out = String::with_capacity(path.len() + 1);
365 for segment in path.split('.') {
366 out.push('/');
367 out.push_str(&segment.replace('~', "~0").replace('/', "~1"));
368 }
369 out
370}
371
372fn repair_and_parse<T: DeserializeOwned>(
379 text: &str,
380 options: &DecodeOptions,
381 first: &DecodeError,
382) -> Result<T, DecodeError> {
383 let mut json: serde_json::Value = serde_json::from_str(text)
384 .map_err(|error| DecodeError::new(DecodeErrorKind::Format, "", error.to_string()))?;
385
386 let mut error = first.clone();
387 for _ in 0..options.max_repairs {
388 if !apply_repair(&mut json, &error, options) {
389 return Err(error);
390 }
391 match serde_path_to_error::deserialize::<_, T>(&json) {
392 Ok(value) => return Ok(value),
393 Err(next) => {
394 let next = classify(&next);
395 if next == error {
396 return Err(next);
397 }
398 error = next;
399 }
400 }
401 }
402 Err(error)
403}
404
405fn apply_repair(
407 json: &mut serde_json::Value,
408 error: &DecodeError,
409 options: &DecodeOptions,
410) -> bool {
411 let Some(slot) = pointer_mut(json, &error.path) else {
412 return false;
413 };
414 let Some(text) = slot.as_str().map(ToOwned::to_owned) else {
415 return false;
416 };
417
418 if options.numeric_strings == NumericStrings::Coerce && error.kind == DecodeErrorKind::Type {
420 if let Ok(number) = text.parse::<serde_json::Number>() {
421 *slot = serde_json::Value::Number(number);
422 return true;
423 }
424 }
425
426 if options.datetime != DateTimeLeniency::Strict && error.kind == DecodeErrorKind::Property {
428 let allow_space = options.datetime == DateTimeLeniency::AllowSpace;
429 if !allow_space && text.contains(' ') {
430 return false;
431 }
432 let normalized = crate::types::normalize_datetime(&text);
433 if normalized != text && crate::types::DateTime::parse(&normalized).is_ok() {
434 *slot = serde_json::Value::String(normalized);
435 return true;
436 }
437 }
438 false
439}
440
441fn pointer_mut<'a>(
443 value: &'a mut serde_json::Value,
444 pointer: &str,
445) -> Option<&'a mut serde_json::Value> {
446 if pointer.is_empty() {
447 return Some(value);
448 }
449 let mut current = value;
450 for raw in pointer.trim_start_matches('/').split('/') {
451 let key = raw.replace("~1", "/").replace("~0", "~");
452 current = match current {
453 serde_json::Value::Object(map) => map.get_mut(&key)?,
454 serde_json::Value::Array(items) => items.get_mut(key.parse::<usize>().ok()?)?,
455 _ => return None,
456 };
457 }
458 Some(current)
459}
460
461fn first_unknown_field<T: serde::Serialize>(
471 text: &str,
472 value: &T,
473) -> Result<Option<String>, DecodeError> {
474 let wire: serde_json::Value = serde_json::from_str(text)
475 .map_err(|error| DecodeError::new(DecodeErrorKind::Format, "", error.to_string()))?;
476 let ours = serde_json::to_value(value)
477 .map_err(|error| DecodeError::new(DecodeErrorKind::Format, "", error.to_string()))?;
478 let mut path = Vec::new();
479 Ok(diff(&wire, &ours, &mut path))
480}
481
482fn diff(
483 wire: &serde_json::Value,
484 ours: &serde_json::Value,
485 path: &mut Vec<String>,
486) -> Option<String> {
487 match (wire, ours) {
488 (serde_json::Value::Object(w), serde_json::Value::Object(o)) => {
489 for (key, value) in w {
490 if value.is_null() {
491 continue; }
493 path.push(key.replace('~', "~0").replace('/', "~1"));
494 let found = match o.get(key) {
495 None => Some(render(path)),
496 Some(mine) => diff(value, mine, path),
497 };
498 path.pop();
499 if found.is_some() {
500 return found;
501 }
502 }
503 None
504 }
505 (serde_json::Value::Array(w), serde_json::Value::Array(o)) => {
506 for (index, (value, mine)) in w.iter().zip(o).enumerate() {
507 path.push(index.to_string());
508 let found = diff(value, mine, path);
509 path.pop();
510 if found.is_some() {
511 return found;
512 }
513 }
514 None
515 }
516 _ => None,
517 }
518}
519
520fn render(path: &[String]) -> String {
521 let mut out = String::new();
522 for segment in path {
523 out.push('/');
524 out.push_str(segment);
525 }
526 out
527}