Skip to main content

ocpp_kit/
decode.rs

1//! Payload decoding with spec-exact failure classification.
2//!
3//! OCPP does not have one "bad payload" error. It has five, and answering with the wrong one
4//! is a conformance failure that most implementations make because they collapse every
5//! `serde` error into a single code. This module keeps them apart:
6//!
7//! | What went wrong | [`DecodeErrorKind`] |
8//! |---|---|
9//! | The payload is not a JSON object, or the JSON is malformed | [`Format`](DecodeErrorKind::Format) |
10//! | A required member is missing, or an array is too short/long | [`Occurrence`](DecodeErrorKind::Occurrence) |
11//! | A member has the wrong JSON type | [`Type`](DecodeErrorKind::Type) |
12//! | A value is too long, out of range, or an undefined enum value | [`Property`](DecodeErrorKind::Property) |
13//! | A member the schema does not define was present (strict mode) | [`UnknownField`](DecodeErrorKind::UnknownField) |
14//! | Cross-field rules broken | [`Protocol`](DecodeErrorKind::Protocol) |
15//!
16//! [`DecodeOptions`] additionally carries the leniency knobs that make it possible to talk to
17//! the substantial share of field devices that do not follow the schemas. Leniency is
18//! implemented as a bounded *repair loop*: the strict parse runs first, and only when it
19//! fails is the offending member — identified by path — rewritten and the parse retried. A
20//! conforming payload therefore costs exactly one strict parse.
21
22use 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/// How to treat enumeration values the schema does not define.
34#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
35pub enum UnknownEnumValues {
36    /// Fail with [`DecodeErrorKind::Property`].
37    #[default]
38    Reject,
39    /// Keep them in the enum's open `UnknownValue` variant.
40    Preserve,
41}
42
43/// How to treat members the schema does not define.
44///
45/// The 2.x schemas say `additionalProperties: false`, but rejecting is not the safe default
46/// in the field: stations routinely add vendor members outside `customData`.
47#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
48pub enum UnknownFields {
49    /// Fail with [`DecodeErrorKind::UnknownField`].
50    Reject,
51    /// Drop them.
52    #[default]
53    Ignore,
54}
55
56/// How much to forgive in `dateTime` members.
57#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
58pub enum DateTimeLeniency {
59    /// RFC 3339 with a mandatory offset, as the schemas require.
60    #[default]
61    Strict,
62    /// Also accept a missing offset, interpreted as UTC.
63    AllowNaive,
64    /// Also accept a space instead of `T`, and a missing offset.
65    AllowSpace,
66}
67
68/// How to treat numbers sent as JSON strings (`"42"`).
69#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
70pub enum NumericStrings {
71    /// Fail with [`DecodeErrorKind::Type`].
72    #[default]
73    Reject,
74    /// Convert them, when the string is a valid number.
75    Coerce,
76}
77
78/// How to treat a whole number written with a fraction (`20000.0`) where the schema says
79/// `integer` *and* the schema's own draft does not count it as one.
80///
81/// Only the OCPP 1.6 core schemas are affected: they are JSON Schema draft-04, where an
82/// integer is "a JSON number without a fraction or exponent part". From draft-06 on —
83/// every OCPP 2.0.1 and 2.1 schema, and the 1.6 security extensions — `20000.0` *is* an
84/// integer, and the generated types accept it in every mode.
85#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
86pub enum WholeFloats {
87    /// Fail with [`DecodeErrorKind::Type`], as draft-04 requires.
88    #[default]
89    Reject,
90    /// Rewrite them as integers. A real fraction (`20000.5`) is never rewritten.
91    Coerce,
92}
93
94/// Decoding policy. The strict default is exactly what the specification requires.
95#[derive(Clone, Debug, PartialEq, Eq)]
96#[non_exhaustive]
97pub struct DecodeOptions {
98    /// Enumeration values the schema does not define.
99    pub unknown_enum_values: UnknownEnumValues,
100    /// Members the schema does not define.
101    pub unknown_fields: UnknownFields,
102    /// `dateTime` spellings.
103    pub datetime: DateTimeLeniency,
104    /// Numbers sent as strings.
105    pub numeric_strings: NumericStrings,
106    /// Whole numbers written as `20000.0` where a draft-04 schema says `integer`.
107    pub whole_floats: WholeFloats,
108    /// Upper bound on one *payload*, in bytes — the fourth element of a `CALL`, not the
109    /// whole frame.
110    ///
111    /// The frame is bounded earlier and elsewhere, at the socket, by
112    /// [`Csms::max_message_size_bytes`](crate::transport::CsmsBuilder::max_message_size_bytes);
113    /// this is the second line, and it is what a handler that decodes a payload of its own
114    /// gets for free. OCPP sets no limit of its own, and `NotifyReport` and
115    /// `GetCompositeSchedule` payloads can be large, so the default is generous.
116    pub max_payload_size: usize,
117    /// Upper bound on the number of leniency repairs applied to one payload.
118    pub max_repairs: usize,
119}
120
121impl Default for DecodeOptions {
122    fn default() -> Self {
123        Self::strict()
124    }
125}
126
127impl DecodeOptions {
128    /// Exactly what the specification requires. The default.
129    #[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    /// Everything the schemas require, plus rejection of undefined members.
143    ///
144    /// Useful in tests and for a CSMS that wants to hold its fleet to the letter of
145    /// `additionalProperties: false`.
146    #[must_use]
147    pub const fn pedantic() -> Self {
148        Self {
149            unknown_fields: UnknownFields::Reject,
150            ..Self::strict()
151        }
152    }
153
154    /// The knobs field devices actually need: undefined enum values and members are kept,
155    /// offset-less and space-separated timestamps are accepted, numeric strings are coerced,
156    /// and `20000.0` is accepted for a 1.6 `integer`.
157    #[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    /// Sets the maximum accepted payload size.
171    #[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    /// Sets how undefined enumeration values are treated.
178    #[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    /// Sets how undefined members are treated.
185    #[must_use]
186    pub const fn with_unknown_fields(mut self, policy: UnknownFields) -> Self {
187        self.unknown_fields = policy;
188        self
189    }
190
191    /// Sets which `dateTime` spellings are accepted.
192    #[must_use]
193    pub const fn with_datetime(mut self, policy: DateTimeLeniency) -> Self {
194        self.datetime = policy;
195        self
196    }
197
198    /// Sets how numbers sent as strings are treated.
199    #[must_use]
200    pub const fn with_numeric_strings(mut self, policy: NumericStrings) -> Self {
201        self.numeric_strings = policy;
202        self
203    }
204
205    /// Sets how `20000.0` is treated where a draft-04 schema says `integer`.
206    #[must_use]
207    pub const fn with_whole_floats(mut self, policy: WholeFloats) -> Self {
208        self.whole_floats = policy;
209        self
210    }
211
212    /// Sets the maximum number of leniency repairs applied to one payload.
213    #[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/// The category of a decoding failure, which decides the OCPP error code.
227#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
228#[non_exhaustive]
229pub enum DecodeErrorKind {
230    /// Malformed JSON, or a payload that is not a JSON object.
231    Format,
232    /// A required member is absent, or an array's cardinality is wrong.
233    Occurrence,
234    /// A member has the wrong JSON type.
235    Type,
236    /// A value violates a `maxLength`, range, or enumeration constraint.
237    Property,
238    /// A member the schema does not define was present.
239    UnknownField,
240    /// Individually valid members that break a cross-field rule.
241    Protocol,
242    /// The action is not defined for this direction or version.
243    UnsupportedAction,
244}
245
246/// A decoding failure, carrying enough detail to fill an OCPP `CALLERROR`.
247#[derive(Clone, Debug, PartialEq, Eq)]
248pub struct DecodeError {
249    /// Which OCPP error code this maps to.
250    pub kind: DecodeErrorKind,
251    /// RFC 6901 pointer to the offending member, empty for whole-payload failures.
252    pub path: String,
253    /// Human-readable reason, suitable for `errorDescription`.
254    pub reason: String,
255}
256
257impl DecodeError {
258    /// Builds a decoding failure.
259    #[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    /// The action is not valid for this direction or version.
269    #[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/// One thing a lenient decode forgave, and where.
305///
306/// The repair loop knows exactly which member it rewrote; this is that knowledge, kept. A
307/// counter per [`RepairKind`] and station is what turns "this fleet is tolerated" into "this
308/// fleet sends timestamps without an offset, 40 000 times a day" — the sentence an operator
309/// takes back to the vendor.
310#[derive(Clone, Debug, PartialEq, Eq)]
311pub struct Repair {
312    /// RFC 6901 pointer to the member, e.g. `/meterValue/0/timestamp`.
313    pub pointer: String,
314    /// What was wrong with it.
315    pub kind: RepairKind,
316}
317
318/// The kinds of non-conformance leniency forgives.
319#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
320#[non_exhaustive]
321pub enum RepairKind {
322    /// A number sent as a JSON string (`"42"`), coerced ([`NumericStrings::Coerce`]).
323    NumericString,
324    /// A `dateTime` without a UTC offset, read as UTC ([`DateTimeLeniency::AllowNaive`]).
325    DateTimeWithoutOffset,
326    /// A `dateTime` with a space instead of `T` ([`DateTimeLeniency::AllowSpace`]).
327    DateTimeWithSpace,
328    /// `20000.0` where a draft-04 schema says `integer` ([`WholeFloats::Coerce`]).
329    WholeFloat,
330    /// An enumeration value the schema does not define, kept in `UnknownValue`
331    /// ([`UnknownEnumValues::Preserve`]).
332    UnknownEnumValue,
333}
334
335impl RepairKind {
336    /// A stable, lower-case name, suitable as a metric label.
337    #[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/// A decoded payload, and what had to be forgiven to decode it.
356#[derive(Clone, Debug, PartialEq)]
357pub struct Decoded<T> {
358    /// The payload.
359    pub value: T,
360    /// Empty for a conforming payload — which costs one strict parse and no allocation.
361    pub repairs: Vec<Repair>,
362}
363
364impl<T> Decoded<T> {
365    /// Maps the value, keeping the repairs.
366    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
374/// Decodes and validates one payload according to `options`.
375///
376/// Used by the generated `CsRequest::decode` / `CsmsRequest::decode` dispatchers, and usable
377/// directly when the action is known statically. [`decode_payload_reporting`] is the same, and
378/// also says what leniency forgave.
379pub 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
386/// [`decode_payload`], also returning every [`Repair`] the lenient options applied.
387pub 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    // Part 4 §4.2.1: the payload of a CALL / CALLRESULT is a JSON object.
405    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
454/// Decodes a payload and serializes the typed value straight back.
455///
456/// Used by [`v2_1::transcode_request`](crate::v2_1::transcode_request) and friends: what comes
457/// out is what the Rust types actually model, so comparing it with the input reveals any
458/// member the types drop.
459pub 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
476/// Maps a `serde` failure onto the OCPP error taxonomy.
477///
478/// `serde`'s messages are the only structured signal available for derived impls, so the
479/// mapping is pinned by tests (see the module's unit tests) — a `serde` change that altered
480/// the wording would fail CI rather than silently downgrade every error to `FormatViolation`.
481fn 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            // A missing member and a wrong array length are both occurrence constraints.
492            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                // `invalid value: …` and every custom error our own impls raise
502                // (undefined enum value, bad RFC 3339 timestamp).
503                DecodeErrorKind::Property
504            }
505        }
506    };
507    // The trailing " at line L column C" is noise once a path is available.
508    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
515/// `serde_path_to_error` renders paths as `a.b.0.c`; OCPP error details use JSON pointers.
516fn 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
528// ---------------------------------------------------------------------------
529// Leniency repairs
530// ---------------------------------------------------------------------------
531
532/// Re-parses `text` after rewriting the member the strict parse tripped over, repeating for
533/// as long as progress is made and `options.max_repairs` allows.
534fn 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
566/// Rewrites the single member `error` points at, and says what kind of repair it was.
567/// Returns `None` when no repair applies.
568fn 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    // `20000.0` where a draft-04 schema says `integer`.
576    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    // A number that arrived as a string.
590    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    // A timestamp without an offset, or with a space instead of `T`.
598    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/// `Some(n)` when `v` is a finite whole number that fits an `i64` exactly.
617#[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
626/// Resolves an RFC 6901 pointer to a mutable slot.
627fn 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
646// ---------------------------------------------------------------------------
647// Strict unknown-field detection
648// ---------------------------------------------------------------------------
649
650/// Finds the first member present on the wire but absent from the decoded value.
651///
652/// Implemented by re-serializing the decoded payload and diffing, which needs no schema
653/// descriptors and cannot drift from the types. It runs only when
654/// [`UnknownFields::Reject`] is configured.
655fn 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; // an explicit null is indistinguishable from an absent member
677                }
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}