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/// Decodes and validates one payload from JSON text, strictly: what a test, a fixture or a
387/// replayed log line needs, without a transport handler around it.
388///
389/// ```
390/// use ocpp_kit::{decode, v2_1};
391///
392/// let alarm: v2_1::NotifyDERAlarmRequest = decode::from_str(
393///     r#"{"controlType":"VoltWatt","timestamp":"2026-11-20T17:05:00Z"}"#,
394/// )?;
395/// assert_eq!(alarm.control_type, v2_1::DERControl::VoltWatt);
396///
397/// // Validated, not just parsed: a missing member is the error a CSMS would answer with.
398/// let error = decode::from_str::<v2_1::NotifyDERAlarmRequest>(r#"{"controlType":"VoltWatt"}"#)
399///     .unwrap_err();
400/// assert_eq!(error.kind, decode::DecodeErrorKind::Occurrence);
401/// # Ok::<(), decode::DecodeError>(())
402/// ```
403///
404/// # Errors
405///
406/// [`DecodeError`] exactly as [`decode_payload`] with [`DecodeOptions::strict`] reports it.
407pub 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
415/// [`decode_payload`], also returning every [`Repair`] the lenient options applied.
416pub 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    // Part 4 §4.2.1: the payload of a CALL / CALLRESULT is a JSON object.
434    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
483/// Decodes a payload and serializes the typed value straight back.
484///
485/// Used by [`v2_1::transcode_request`](crate::v2_1::transcode_request) and friends: what comes
486/// out is what the Rust types actually model, so comparing it with the input reveals any
487/// member the types drop.
488pub 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
505/// Maps a `serde` failure onto the OCPP error taxonomy.
506///
507/// `serde`'s messages are the only structured signal available for derived impls, so the
508/// mapping is pinned by tests (see the module's unit tests) — a `serde` change that altered
509/// the wording would fail CI rather than silently downgrade every error to `FormatViolation`.
510fn 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            // A missing member and a wrong array length are both occurrence constraints.
521            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                // `invalid value: …` and every custom error our own impls raise
531                // (undefined enum value, bad RFC 3339 timestamp).
532                DecodeErrorKind::Property
533            }
534        }
535    };
536    // The trailing " at line L column C" is noise once a path is available.
537    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
544/// `serde_path_to_error` renders paths as `a.b.0.c`; OCPP error details use JSON pointers.
545fn 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
557// ---------------------------------------------------------------------------
558// Leniency repairs
559// ---------------------------------------------------------------------------
560
561/// Re-parses `text` after rewriting the member the strict parse tripped over, repeating for
562/// as long as progress is made and `options.max_repairs` allows.
563fn 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
595/// Rewrites the single member `error` points at, and says what kind of repair it was.
596/// Returns `None` when no repair applies.
597fn 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    // `20000.0` where a draft-04 schema says `integer`.
605    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    // A number that arrived as a string.
619    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    // A timestamp without an offset, or with a space instead of `T`.
627    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/// `Some(n)` when `v` is a finite whole number that fits an `i64` exactly.
646#[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
655/// Resolves an RFC 6901 pointer to a mutable slot.
656fn 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
675// ---------------------------------------------------------------------------
676// Strict unknown-field detection
677// ---------------------------------------------------------------------------
678
679/// Finds the first member present on the wire but absent from the decoded value.
680///
681/// Implemented by re-serializing the decoded payload and diffing, which needs no schema
682/// descriptors and cannot drift from the types. It runs only when
683/// [`UnknownFields::Reject`] is configured.
684fn 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; // an explicit null is indistinguishable from an absent member
706                }
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}