Skip to main content

buffa/
json_helpers.rs

1// Modified by ReallyMe Technologies Limited.
2//! Proto3 JSON encoding helpers for use with serde.
3//!
4//! The protobuf JSON mapping (proto3 JSON) has several types whose wire
5//! representation differs from their JSON representation:
6//!
7//! | Proto type          | JSON representation                          |
8//! |---------------------|----------------------------------------------|
9//! | `int64` / `sint64`  | Decimal string (e.g. `"9007199254740993"`)   |
10//! | `uint64` / `fixed64`| Decimal string (e.g. `"18446744073709551615"`)|
11//! | `float`             | Number, or `"NaN"` / `"Infinity"` / `"-Infinity"` |
12//! | `double`            | Number, or `"NaN"` / `"Infinity"` / `"-Infinity"` |
13//! | `bytes`             | Base64-encoded string (RFC 4648 standard)    |
14//!
15//! Most submodules provide `serialize` / `deserialize` functions compatible
16//! with serde's `#[serde(with = "...")]` attribute.
17//!
18//! A [`skip_if`] submodule provides `skip_serializing_if` predicates for
19//! omitting default-valued fields from JSON output.
20//!
21//! The [`wkt`] submodule provides the shared formatting and parsing
22//! primitives for the well-known types' JSON forms (`Timestamp` RFC 3339,
23//! `Duration` decimal seconds, `FieldMask` camelCase). Both `buffa-types`'s
24//! typed serde impls and `buffa-descriptor`'s reflective JSON codec call
25//! into it, so the two paths can't drift on edge cases the conformance
26//! suite exercises. It's `#[doc(hidden)]` because the supported entry
27//! points are the typed serde impls and `DynamicMessage`'s JSON codec —
28//! these helpers operate on raw scalars and have no semver contract.
29//!
30//! The [`buffered`] submodule deserializes a `serde_json::Value` with every
31//! object key read as data. Use it wherever a `Deserialize` impl, hand-written
32//! or derived, keeps untrusted JSON as a `serde_json::Value`. It provides
33//! types, and functions for `#[serde(deserialize_with = "...")]`.
34
35pub mod buffered;
36mod ignored_key;
37mod map_key;
38mod policy;
39pub mod proto_list;
40#[doc(hidden)]
41pub use ignored_key::IgnoredObjectKey;
42#[doc(hidden)]
43pub mod wkt;
44
45#[doc(hidden)]
46pub use policy::{
47    bytes_policy, list_bytes_policy, list_string_policy, map_bytes_policy,
48    map_bytes_policy_bytes_key, map_bytes_policy_policy_key, map_bytes_policy_serde_key,
49    map_string_policy, map_string_policy_bytes_key, map_string_policy_policy_key,
50    map_string_policy_serde_key, opt_bytes_policy, opt_string_policy, policy_str_key_map,
51    repeated_bytes_policy, repeated_string_policy, string_policy, BytesPolicyJson, BytesPolicySeed,
52    BytesPolicySeqJson, StringPolicyJson, StringPolicySeed, StringPolicySeqJson,
53    ViewJsonErrorReason,
54};
55pub use policy::{ProtoBytesJson, ProtoStringJson};
56
57use buffered::BufferedValue;
58
59/// Ignore a carrier's tag and decode its payload with the same JSON-kind
60/// visitor. Typed string/map/sequence entry points historically ignored YAML
61/// tags; switching to `deserialize_any` must not reject those valid payloads.
62/// The tag itself is discarded without retaining its text.
63///
64/// # Errors
65///
66/// Propagates tag traversal errors and the visitor's payload errors.
67#[doc(hidden)]
68pub fn deserialize_tagged<'de, V, A>(visitor: V, tagged: A) -> Result<V::Value, A::Error>
69where
70    V: serde::de::Visitor<'de>,
71    A: serde::de::EnumAccess<'de>,
72{
73    struct Seed<V>(V);
74    impl<'de, V: serde::de::Visitor<'de>> serde::de::DeserializeSeed<'de> for Seed<V> {
75        type Value = V::Value;
76        fn deserialize<D: serde::Deserializer<'de>>(self, d: D) -> Result<V::Value, D::Error> {
77            d.deserialize_any(self.0)
78        }
79    }
80    let (_, variant) = tagged.variant::<serde::de::IgnoredAny>()?;
81    serde::de::VariantAccess::newtype_variant_seed(variant, Seed(visitor))
82}
83
84/// Fixed diagnostics shared by the runtime and its well-known type codecs.
85///
86/// Never include the token or a parser's original error in these reasons.
87#[doc(hidden)]
88#[derive(Clone, Copy, Debug, thiserror::Error)]
89#[non_exhaustive]
90pub enum JsonValueError {
91    #[error("invalid protobuf map key")]
92    MapKey,
93    #[error("invalid i32 value")]
94    Int32,
95    #[error("invalid u32 value")]
96    Uint32,
97    #[error("invalid i64 value")]
98    Int64,
99    #[error("invalid u64 value")]
100    Uint64,
101    #[error("invalid float value, expected a finite f32 or a protobuf special value")]
102    Float,
103    #[error("invalid double value, expected a finite f64 or a protobuf special value")]
104    Double,
105    #[error("invalid base64 string")]
106    Base64,
107    #[error("invalid Duration string")]
108    Duration,
109    #[error("invalid RFC 3339 timestamp")]
110    Timestamp,
111    #[error("invalid FieldMask path, expected comma-separated lowerCamelCase paths")]
112    FieldMask,
113    #[error("invalid FieldMask path, it has no proto3 JSON representation")]
114    FieldMaskEncode,
115    #[error("invalid JSON payload for a registered Any message")]
116    AnyMessage,
117    #[error("invalid JSON value for a registered Any well-known type")]
118    AnyWellKnownType,
119    #[error("@type is not a valid type URL: it names no type")]
120    AnyEmptyType,
121    #[error("@type must contain a '/' (e.g. type.googleapis.com/pkg.Type)")]
122    AnyBareType,
123    #[error("Any with a well-known type requires a \"value\" key")]
124    AnyMissingValue,
125    #[error("Any with a well-known type has an unexpected field")]
126    AnyUnexpectedField,
127    #[error("Any type is not registered in the descriptor pool")]
128    AnyUnregisteredType,
129    #[error("Any: no type registry is installed to resolve a bare @type; install one with `set_type_registry`, or send a type URL")]
130    AnyBareTypeWithoutRegistry,
131    #[error("Any: bare @type has no JSON entry in the type registry; register the message or send a type URL")]
132    AnyBareTypeWithoutEntry,
133    #[error("Any: no type registry is installed; send the message encoded as a base64 string under \"value\", or install a registry with `set_type_registry`")]
134    AnyOpaqueWithoutRegistry,
135    #[error("Any: type has no JSON entry in the type registry; send the message encoded as a base64 string under \"value\", or register the message with `register_types`")]
136    AnyOpaqueWithoutEntry,
137    #[error("Any opaque payload field cannot be parsed")]
138    AnyOpaqueField,
139}
140
141/// Implement the `serde::de::Visitor` methods for the input kinds a protobuf
142/// JSON visitor does not accept, without echoing the rejected value.
143///
144/// serde's default `visit_*` methods describe a rejected token by its value
145/// (``invalid type: integer `123` ``), which can carry a would-be secret into
146/// error text. Each listed kind instead returns
147/// `invalid_type(Unexpected::Other("<kind>"), &self)`, which names only the
148/// JSON kind. Rejected owned text and bytes are wiped first when buffa's
149/// `zeroize` feature is enabled. List only kinds the visitor does not accept.
150///
151/// Kinds: `bool`, `i64`, `u64`, `i128`, `u128`, `f64`, `str`, `string`,
152/// `bytes`, `byte_buf`, `unit`, `seq` and `map`. serde forwards the narrower
153/// integer and float methods to `i64`, `u64` and `f64`, `char` and borrowed
154/// strings to `str`, and borrowed bytes to `bytes`. `seq` and `map` require the
155/// surrounding impl to name the visitor lifetime `'de`.
156///
157/// The `i128` and `u128` arms forward values that fit in 64 bits to the
158/// corresponding integer visitor. A deserializer may use these visits even
159/// for narrow values; rejecting them unconditionally would change acceptance.
160/// Values outside that range are rejected without formatting their contents.
161///
162/// A visitor only sees these calls through `deserialize_any`: a typed request
163/// such as serde_json's `deserialize_str` reports a mismatched token itself,
164/// including its value.
165///
166/// ```ignore
167/// impl<'de> serde::de::Visitor<'de> for Text {
168///     // ...expecting, visit_str and visit_string...
169///     buffa::json_helpers::reject_other_json_kinds!(
170///         bool, i64, u64, i128, u128, f64, bytes, byte_buf, unit, seq, map
171///     );
172/// }
173/// ```
174#[doc(hidden)]
175#[macro_export]
176macro_rules! __buffa_reject_other_json_kinds {
177    ($($kind:ident),* $(,)?) => {
178        $($crate::__buffa_reject_other_json_kinds!(@kind $kind);)*
179    };
180    (@kind bool) => {
181        fn visit_bool<__E: ::serde::de::Error>(
182            self,
183            _: ::core::primitive::bool,
184        ) -> ::core::result::Result<Self::Value, __E> {
185            ::core::result::Result::Err(__E::invalid_type(
186                ::serde::de::Unexpected::Other("boolean"),
187                &self,
188            ))
189        }
190    };
191    (@kind i64) => {
192        fn visit_i64<__E: ::serde::de::Error>(
193            self,
194            _: ::core::primitive::i64,
195        ) -> ::core::result::Result<Self::Value, __E> {
196            ::core::result::Result::Err(__E::invalid_type(
197                ::serde::de::Unexpected::Other("integer"),
198                &self,
199            ))
200        }
201    };
202    (@kind u64) => {
203        fn visit_u64<__E: ::serde::de::Error>(
204            self,
205            _: ::core::primitive::u64,
206        ) -> ::core::result::Result<Self::Value, __E> {
207            ::core::result::Result::Err(__E::invalid_type(
208                ::serde::de::Unexpected::Other("integer"),
209                &self,
210            ))
211        }
212    };
213    (@kind i128) => {
214        fn visit_i128<__E: ::serde::de::Error>(
215            self,
216            value: ::core::primitive::i128,
217        ) -> ::core::result::Result<Self::Value, __E> {
218            if let ::core::result::Result::Ok(value) = <::core::primitive::i64 as ::core::convert::TryFrom<::core::primitive::i128>>::try_from(value) {
219                return ::serde::de::Visitor::visit_i64(self, value);
220            }
221            if let ::core::result::Result::Ok(value) = <::core::primitive::u64 as ::core::convert::TryFrom<::core::primitive::i128>>::try_from(value) {
222                return ::serde::de::Visitor::visit_u64(self, value);
223            }
224            ::core::result::Result::Err(__E::invalid_type(
225                ::serde::de::Unexpected::Other("integer"),
226                &self,
227            ))
228        }
229    };
230    (@kind u128) => {
231        fn visit_u128<__E: ::serde::de::Error>(
232            self,
233            value: ::core::primitive::u128,
234        ) -> ::core::result::Result<Self::Value, __E> {
235            if let ::core::result::Result::Ok(value) = <::core::primitive::u64 as ::core::convert::TryFrom<::core::primitive::u128>>::try_from(value) {
236                return ::serde::de::Visitor::visit_u64(self, value);
237            }
238            ::core::result::Result::Err(__E::invalid_type(
239                ::serde::de::Unexpected::Other("integer"),
240                &self,
241            ))
242        }
243    };
244    (@kind f64) => {
245        fn visit_f64<__E: ::serde::de::Error>(
246            self,
247            _: ::core::primitive::f64,
248        ) -> ::core::result::Result<Self::Value, __E> {
249            ::core::result::Result::Err(__E::invalid_type(
250                ::serde::de::Unexpected::Other("floating-point number"),
251                &self,
252            ))
253        }
254    };
255    (@kind str) => {
256        fn visit_str<__E: ::serde::de::Error>(
257            self,
258            _: &::core::primitive::str,
259        ) -> ::core::result::Result<Self::Value, __E> {
260            ::core::result::Result::Err(__E::invalid_type(
261                ::serde::de::Unexpected::Other("string"),
262                &self,
263            ))
264        }
265    };
266    (@kind string) => {
267        fn visit_string<__E: ::serde::de::Error>(
268            self,
269            value: $crate::alloc::string::String,
270        ) -> ::core::result::Result<Self::Value, __E> {
271            $crate::json_helpers::discard_rejected_text(value);
272            ::core::result::Result::Err(__E::invalid_type(
273                ::serde::de::Unexpected::Other("string"),
274                &self,
275            ))
276        }
277    };
278    (@kind bytes) => {
279        fn visit_bytes<__E: ::serde::de::Error>(
280            self,
281            _: &[::core::primitive::u8],
282        ) -> ::core::result::Result<Self::Value, __E> {
283            ::core::result::Result::Err(__E::invalid_type(
284                ::serde::de::Unexpected::Other("bytes"),
285                &self,
286            ))
287        }
288    };
289    (@kind byte_buf) => {
290        fn visit_byte_buf<__E: ::serde::de::Error>(
291            self,
292            value: $crate::alloc::vec::Vec<::core::primitive::u8>,
293        ) -> ::core::result::Result<Self::Value, __E> {
294            $crate::json_helpers::discard_rejected_bytes(value);
295            ::core::result::Result::Err(__E::invalid_type(
296                ::serde::de::Unexpected::Other("bytes"),
297                &self,
298            ))
299        }
300    };
301    (@kind unit) => {
302        fn visit_unit<__E: ::serde::de::Error>(self) -> ::core::result::Result<Self::Value, __E> {
303            ::core::result::Result::Err(__E::invalid_type(
304                ::serde::de::Unexpected::Other("null"),
305                &self,
306            ))
307        }
308    };
309    (@kind seq) => {
310        fn visit_seq<__A: ::serde::de::SeqAccess<'de>>(
311            self,
312            _: __A,
313        ) -> ::core::result::Result<Self::Value, __A::Error> {
314            ::core::result::Result::Err(<__A::Error as ::serde::de::Error>::invalid_type(
315                ::serde::de::Unexpected::Other("array"),
316                &self,
317            ))
318        }
319    };
320    (@kind map) => {
321        fn visit_map<__A: ::serde::de::MapAccess<'de>>(
322            self,
323            _: __A,
324        ) -> ::core::result::Result<Self::Value, __A::Error> {
325            ::core::result::Result::Err(<__A::Error as ::serde::de::Error>::invalid_type(
326                ::serde::de::Unexpected::Other("object"),
327                &self,
328            ))
329        }
330    };
331}
332#[doc(hidden)]
333pub use crate::__buffa_reject_other_json_kinds as reject_other_json_kinds;
334
335/// Release rejected owned text, wiping it first under the `zeroize` feature.
336#[doc(hidden)]
337pub fn discard_rejected_text(text: alloc::string::String) {
338    discard_rejected_bytes(text.into_bytes());
339}
340
341/// Release rejected owned bytes, wiping them first under the `zeroize` feature.
342#[doc(hidden)]
343pub fn discard_rejected_bytes(bytes: alloc::vec::Vec<u8>) {
344    #[cfg(feature = "zeroize")]
345    {
346        let mut bytes = bytes;
347        zeroize::Zeroize::zeroize(&mut bytes);
348    }
349    #[cfg(not(feature = "zeroize"))]
350    drop(bytes);
351}
352
353/// The object key under which `serde_json`'s `arbitrary_precision` feature
354/// hands a number to `visit_map`.
355///
356/// A message visitor driven by `deserialize_any` rejects this key as a
357/// number, as `deserialize_map` would. An explicit schema `json_name` can
358/// legally use this spelling; those messages retain typed map deserialization
359/// to distinguish genuine objects from synthetic number objects.
360#[doc(hidden)]
361pub const SERDE_JSON_NUMBER_KEY: &str = "$serde_json::private::Number";
362
363/// `visit_i128` / `visit_u128` for a numeric helper: a value that fits in 64
364/// bits goes to the visitor's `visit_i64` / `visit_u64`, and a wider one is
365/// rejected with the helper's fixed reason.
366macro_rules! visit_wide_ints {
367    ($reason:expr) => {
368        fn visit_i128<E: serde::de::Error>(self, v: i128) -> Result<Self::Value, E> {
369            if let Ok(v) = i64::try_from(v) {
370                return serde::de::Visitor::visit_i64(self, v);
371            }
372            match u64::try_from(v) {
373                Ok(v) => serde::de::Visitor::visit_u64(self, v),
374                Err(_) => Err(E::custom($reason)),
375            }
376        }
377        fn visit_u128<E: serde::de::Error>(self, v: u128) -> Result<Self::Value, E> {
378            match u64::try_from(v) {
379                Ok(v) => serde::de::Visitor::visit_u64(self, v),
380                Err(_) => Err(E::custom($reason)),
381            }
382        }
383    };
384}
385
386// ── Lenient base64 engines ──────────────────────────────────────────────────
387//
388// The pre-built `general_purpose` engines reject non-zero trailing bits.
389// The protobuf JSON spec requires accepting any valid standard or URL-safe
390// base64, so we configure lenient engines that tolerate trailing bits and
391// optional padding.
392
393use base64::alphabet;
394use base64::engine::{
395    general_purpose::STANDARD, DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig,
396};
397
398const LENIENT_CFG: GeneralPurposeConfig = GeneralPurposeConfig::new()
399    .with_decode_allow_trailing_bits(true)
400    .with_decode_padding_mode(DecodePaddingMode::Indifferent);
401
402static STANDARD_LENIENT: GeneralPurpose = GeneralPurpose::new(&alphabet::STANDARD, LENIENT_CFG);
403static URL_SAFE_LENIENT: GeneralPurpose = GeneralPurpose::new(&alphabet::URL_SAFE, LENIENT_CFG);
404
405/// Maximum elements to pre-allocate from a deserializer's `size_hint`.
406///
407/// `size_hint` comes from untrusted input in the general case (any
408/// `Deserializer<'de>`, not just `serde_json`). A hostile implementation
409/// could return `Some(usize::MAX)`, causing `Vec::with_capacity` to abort.
410/// Capping the hint bounds worst-case preallocation while still avoiding
411/// reallocs for small-to-medium collections.
412const MAX_PREALLOC_HINT: usize = 4096;
413
414/// Clamp a deserializer size hint to [`MAX_PREALLOC_HINT`].
415#[inline]
416fn clamp_size_hint(hint: Option<usize>) -> usize {
417    hint.unwrap_or(0).min(MAX_PREALLOC_HINT)
418}
419
420// ── ProtoElemJson: per-element proto3-JSON dispatch trait ───────────────────
421//
422// Proto3 JSON has per-type encoding rules (int64 → quoted string, float NaN
423// → "NaN", bytes → base64). For singular/optional fields these are handled
424// by the int64/float/bytes/etc. modules below. For CONTAINERS (repeated, map
425// values) we need to apply the same per-element encoding, but serde's `with =`
426// attribute doesn't compose. This trait provides the dispatch point.
427//
428// proto_seq, proto_map, proto_str_key_map and bytes_key_map are the container
429// modules — they are generic over T: ProtoElemJson. Codegen emits ProtoElemJson
430// impls for each generated message and enum type.
431//
432// Named `Json` (not `Serde`) because these are JSON-specific encoding rules.
433// A future YAML encoder would have different per-element rules (YAML has native
434// int64, no quoting needed) and would get its own trait.
435
436/// Per-element proto3-JSON encoding.
437///
438/// Implemented in this crate for primitives (i64 → quoted, f64 → NaN/Inf
439/// strings, `Vec<u8>` → base64, etc.). Codegen generates impls for message
440/// and enum types. Used by [`proto_seq`] (repeated fields), [`proto_map`],
441/// [`proto_str_key_map`] and [`bytes_key_map`] (map values) to apply proto-JSON
442/// encoding to each element.
443pub trait ProtoElemJson: Sized {
444    /// Serialize this value with proto3 JSON semantics.
445    fn serialize_proto_json<S: serde::Serializer>(v: &Self, s: S) -> Result<S::Ok, S::Error>;
446    /// Deserialize a value with proto3 JSON semantics.
447    fn deserialize_proto_json<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error>;
448    /// Deserialize a JSON `null` when it is a valid representation of this
449    /// protobuf type inside a container. Most protobuf element types reject
450    /// `null`; `google.protobuf.Value` overrides this for its null variant.
451    fn deserialize_proto_json_null<E: serde::de::Error>() -> Result<Self, E> {
452        Err(E::custom(
453            "null is not a valid repeated-field element or map value",
454        ))
455    }
456}
457
458/// Wraps `&T: ProtoElemJson` as `serde::Serialize`.
459///
460/// Generated code uses this (and the sibling `*Json` adapters below) where
461/// a value needs proto3-JSON encoding inside a hand-rolled `Serialize` impl
462/// — oneof variant entries, view map/sequence elements — instead of
463/// emitting a local newtype + impl at every site.
464///
465/// The adapters are generated-code plumbing, not a stable consumer-facing
466/// surface (the `#[serde(with = ...)]` modules in this file are the
467/// supported API); they are hidden from rustdoc accordingly.
468#[doc(hidden)]
469pub struct ProtoJson<'a, T>(pub &'a T);
470impl<T: ProtoElemJson> serde::Serialize for ProtoJson<'_, T> {
471    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
472        T::serialize_proto_json(self.0, s)
473    }
474}
475
476/// Serialize a borrowed `bytes` payload as base64 (the proto3 JSON
477/// encoding), for view types whose bytes fields are `&[u8]` (no
478/// [`ProtoElemJson`] impl exists for the unsized slice).
479#[doc(hidden)]
480pub struct BytesJson<'a>(pub &'a [u8]);
481impl serde::Serialize for BytesJson<'_> {
482    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
483        bytes::serialize(self.0, s)
484    }
485}
486
487/// Serialize a closed enum as its proto name string.
488#[doc(hidden)]
489pub struct ClosedEnumJson<'a, E>(pub &'a E);
490impl<E: crate::Enumeration> serde::Serialize for ClosedEnumJson<'_, E> {
491    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
492        closed_enum::serialize(self.0, s)
493    }
494}
495
496/// Serialize a proto map key by stringification (proto3 JSON maps always
497/// use string keys), mirroring [`proto_map`]'s internal `DisplayKey`.
498#[doc(hidden)]
499pub struct MapKeyJson<'a, T: ?Sized>(pub &'a T);
500impl<T: ?Sized + core::fmt::Display> serde::Serialize for MapKeyJson<'_, T> {
501    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
502        s.collect_str(self.0)
503    }
504}
505
506/// Serialize a slice of proto-JSON-encoded elements (see [`proto_seq`]).
507#[doc(hidden)]
508pub struct RepeatedJson<'a, T>(pub &'a [T]);
509impl<T: ProtoElemJson> serde::Serialize for RepeatedJson<'_, T> {
510    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
511        proto_seq::serialize(self.0, s)
512    }
513}
514
515/// Serialize a slice of borrowed `bytes` payloads, each base64-encoded.
516#[doc(hidden)]
517pub struct BytesSeqJson<'a>(pub &'a [&'a [u8]]);
518impl serde::Serialize for BytesSeqJson<'_> {
519    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
520        use serde::ser::SerializeSeq;
521        let mut seq = s.serialize_seq(Some(self.0.len()))?;
522        for v in self.0 {
523            seq.serialize_element(&BytesJson(v))?;
524        }
525        seq.end()
526    }
527}
528
529/// Serialize a slice of open-enum values (see [`repeated_enum`]).
530#[doc(hidden)]
531pub struct EnumSeqJson<'a, E: crate::Enumeration>(pub &'a [crate::EnumValue<E>]);
532impl<E: crate::Enumeration> serde::Serialize for EnumSeqJson<'_, E> {
533    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
534        repeated_enum::serialize(self.0, s)
535    }
536}
537
538/// Serialize a slice of closed-enum values as proto name strings.
539#[doc(hidden)]
540pub struct ClosedEnumSeqJson<'a, E>(pub &'a [E]);
541impl<E: crate::Enumeration> serde::Serialize for ClosedEnumSeqJson<'_, E> {
542    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
543        repeated_closed_enum::serialize(self.0, s)
544    }
545}
546
547/// Bridge seed: deserializes a single T via `ProtoElemJson::deserialize_proto_json`,
548/// but routes `null` to [`ProtoElemJson::deserialize_proto_json_null`], which
549/// REJECTS it by default. Per proto3 JSON spec, `null` as an element of a
550/// repeated field or as a map value is invalid (only the container itself may be
551/// `null`, meaning empty); `google.protobuf.Value` is the one type that
552/// overrides the hook, because `null` is one of its variants. The singular
553/// helper modules accept null → default, which is correct for singular fields
554/// but wrong for container elements.
555struct ProtoElemSeed<T>(core::marker::PhantomData<T>);
556impl<'de, T: ProtoElemJson> serde::de::DeserializeSeed<'de> for ProtoElemSeed<T> {
557    type Value = T;
558    fn deserialize<D: serde::Deserializer<'de>>(self, d: D) -> Result<T, D::Error> {
559        // Peek-via-Option: serde_json calls visit_none for null. If the element
560        // is null, that's an error; otherwise deserialize normally.
561        struct NoNull<T>(core::marker::PhantomData<T>);
562        impl<'de, T: ProtoElemJson> serde::de::Visitor<'de> for NoNull<T> {
563            type Value = T;
564            fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
565                f.write_str("a non-null value")
566            }
567            fn visit_none<E: serde::de::Error>(self) -> Result<T, E> {
568                T::deserialize_proto_json_null()
569            }
570            fn visit_unit<E: serde::de::Error>(self) -> Result<T, E> {
571                T::deserialize_proto_json_null()
572            }
573            fn visit_some<D2: serde::Deserializer<'de>>(self, d: D2) -> Result<T, D2::Error> {
574                T::deserialize_proto_json(d)
575            }
576            crate::reject_other_json_kinds!(
577                bool, i64, u64, i128, u128, f64, str, string, bytes, byte_buf
578            );
579        }
580        d.deserialize_option(NoNull::<T>(core::marker::PhantomData))
581    }
582}
583
584// ── Primitive impls ──────────────────────────────────────────────────────────
585
586/// Delegate-to-existing-module macro: for types where a singular `with`
587/// module already exists (int64, float, bytes, etc.), the ProtoElemJson
588/// impl just forwards to that module's serialize/deserialize.
589macro_rules! proto_elem_json_delegate {
590    ($ty:ty, $mod:ident, null = $expected:literal) => {
591        impl ProtoElemJson for $ty {
592            fn serialize_proto_json<S: serde::Serializer>(
593                v: &Self,
594                s: S,
595            ) -> Result<S::Ok, S::Error> {
596                $mod::serialize(v, s)
597            }
598            fn deserialize_proto_json<'de, D: serde::Deserializer<'de>>(
599                d: D,
600            ) -> Result<Self, D::Error> {
601                $mod::deserialize(d)
602            }
603            // The diagnostic native serde gave a `null` element or map value
604            // before these types were routed through the containers.
605            fn deserialize_proto_json_null<E: serde::de::Error>() -> Result<Self, E> {
606                Err(E::invalid_type(serde::de::Unexpected::Unit, &$expected))
607            }
608        }
609    };
610    ($ty:ty, $mod:ident) => {
611        impl ProtoElemJson for $ty {
612            fn serialize_proto_json<S: serde::Serializer>(
613                v: &Self,
614                s: S,
615            ) -> Result<S::Ok, S::Error> {
616                $mod::serialize(v, s)
617            }
618            fn deserialize_proto_json<'de, D: serde::Deserializer<'de>>(
619                d: D,
620            ) -> Result<Self, D::Error> {
621                $mod::deserialize(d)
622            }
623        }
624    };
625}
626
627// ── proto_seq: generic repeated-field module ─────────────────────────────────
628
629/// Serde with-module for `repeated T` fields where `T: ProtoElemJson`.
630///
631/// Each element is serialized/deserialized via [`ProtoElemJson`], applying
632/// proto3 JSON semantics (quoted int64, NaN/Inf strings, base64 bytes, etc.).
633/// Generated code also uses it for bool and `String` elements, whose
634/// wrong-kind errors then omit the value. JSON `null` deserializes to an
635/// empty vec.
636///
637/// Use with `#[serde(with = "::buffa::json_helpers::proto_seq")]`.
638pub mod proto_seq {
639    use super::{ProtoElemJson, ProtoElemSeed, ProtoJson};
640    use alloc::vec::Vec;
641    use serde::{Deserializer, Serializer};
642
643    pub fn serialize<T: ProtoElemJson, S: Serializer>(v: &[T], s: S) -> Result<S::Ok, S::Error> {
644        use serde::ser::SerializeSeq;
645        let mut seq = s.serialize_seq(Some(v.len()))?;
646        for elem in v {
647            seq.serialize_element(&ProtoJson(elem))?;
648        }
649        seq.end()
650    }
651
652    pub fn deserialize<'de, T, C, D>(d: D) -> Result<C, D::Error>
653    where
654        T: ProtoElemJson,
655        C: From<Vec<T>>,
656        D: Deserializer<'de>,
657    {
658        struct V<T>(core::marker::PhantomData<T>);
659        impl<'de, T: ProtoElemJson> serde::de::Visitor<'de> for V<T> {
660            type Value = Vec<T>;
661            fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
662                f.write_str("an array or null")
663            }
664            fn visit_enum<A: serde::de::EnumAccess<'de>>(
665                self,
666                tagged: A,
667            ) -> Result<Self::Value, A::Error> {
668                super::deserialize_tagged(self, tagged)
669            }
670            fn visit_unit<E>(self) -> Result<Vec<T>, E> {
671                Ok(Vec::new())
672            }
673            crate::reject_other_json_kinds!(
674                bool, i64, u64, i128, u128, f64, str, string, bytes, byte_buf
675            );
676            fn visit_seq<A: serde::de::SeqAccess<'de>>(
677                self,
678                mut seq: A,
679            ) -> Result<Vec<T>, A::Error> {
680                let mut out = Vec::with_capacity(super::clamp_size_hint(seq.size_hint()));
681                while let Some(elem) =
682                    seq.next_element_seed(ProtoElemSeed::<T>(core::marker::PhantomData))?
683                {
684                    out.push(elem);
685                }
686                Ok(out)
687            }
688        }
689        d.deserialize_any(V::<T>(core::marker::PhantomData))
690            .map(C::from)
691    }
692}
693
694/// Wraps a `Display`-able key as a serde string without allocating.
695///
696/// `collect_str` lets serde_json write the Display output directly to
697/// its internal buffer. For `K = String`, this is still one copy (into
698/// serde_json's buffer) but avoids the intermediate `String` allocation
699/// that `.to_string()` would create.
700struct DisplayKey<'a, K: ?Sized>(&'a K);
701impl<K: core::fmt::Display + ?Sized> serde::Serialize for DisplayKey<'_, K> {
702    #[inline]
703    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
704        s.collect_str(self.0)
705    }
706}
707
708/// Serde support for native bool/string collections newly routed through
709/// ProtoJSON visitors. Keep the old native container decoder for binary
710/// formats; changing the existing generic helpers' bounds would break users.
711#[doc(hidden)]
712pub mod native_seq {
713    // These native elements already have canonical JSON scalar encodings.
714    // Keep the container's own serializer, including any binary envelope.
715    pub fn serialize<C: serde::Serialize, S: serde::Serializer>(
716        v: &C,
717        s: S,
718    ) -> Result<S::Ok, S::Error> {
719        serde::Serialize::serialize(v, s)
720    }
721
722    pub fn deserialize<'de, T, C, D>(d: D) -> Result<C, D::Error>
723    where
724        T: super::ProtoElemJson,
725        C: From<alloc::vec::Vec<T>> + serde::Deserialize<'de> + Default,
726        D: serde::Deserializer<'de>,
727    {
728        if d.is_human_readable() {
729            super::proto_seq::deserialize(d)
730        } else {
731            super::null_as_default(d)
732        }
733    }
734}
735
736/// Native string-keyed map counterpart of [`native_seq`].
737#[doc(hidden)]
738pub mod native_str_key_map {
739    pub fn serialize<C: serde::Serialize, S: serde::Serializer>(
740        v: &C,
741        s: S,
742    ) -> Result<S::Ok, S::Error> {
743        serde::Serialize::serialize(v, s)
744    }
745
746    pub fn deserialize<'de, C, D>(d: D) -> Result<C, D::Error>
747    where
748        C: crate::map_codec::MapStorage + serde::Deserialize<'de> + Default,
749        C::Key: serde::Deserialize<'de>,
750        C::Value: super::ProtoElemJson,
751        D: serde::Deserializer<'de>,
752    {
753        if d.is_human_readable() {
754            super::proto_str_key_map::deserialize(d)
755        } else {
756            super::null_as_default(d)
757        }
758    }
759}
760
761// ── proto_map: generic map module ────────────────────────────────────────────
762
763/// Serde with-module for `map<K, V>` fields where `V: ProtoElemJson`.
764///
765/// Keys are stringified (via `Display`) on serialize and parsed (via `FromStr`)
766/// on deserialize — proto3 JSON uses string keys for all maps. Values use
767/// [`ProtoElemJson`] for proto-JSON encoding; generated code also uses it for
768/// bool and `String` values, whose wrong-kind errors then omit the value.
769/// JSON `null` deserializes to an empty map.
770///
771/// Use with `#[serde(with = "::buffa::json_helpers::proto_map")]`.
772pub mod proto_map {
773    use super::{ProtoElemJson, ProtoElemSeed, ProtoJson};
774    use crate::map_codec::MapStorage;
775    use alloc::string::String;
776    use core::fmt::Display;
777    use core::str::FromStr;
778    use serde::{Deserializer, Serializer};
779
780    pub fn serialize<C, S>(m: &C, s: S) -> Result<S::Ok, S::Error>
781    where
782        C: MapStorage,
783        C::Key: Display,
784        C::Value: ProtoElemJson,
785        S: Serializer,
786    {
787        use serde::ser::SerializeMap;
788        let mut map = s.serialize_map(Some(m.storage_len()))?;
789        for (k, v) in m.storage_iter() {
790            map.serialize_entry(&super::DisplayKey(k), &ProtoJson(v))?;
791        }
792        map.end()
793    }
794
795    pub fn deserialize<'de, C, D>(d: D) -> Result<C, D::Error>
796    where
797        C: MapStorage + Default,
798        C::Key: FromStr,
799        C::Value: ProtoElemJson,
800        D: Deserializer<'de>,
801    {
802        struct Vis<C>(core::marker::PhantomData<C>);
803        impl<'de, C> serde::de::Visitor<'de> for Vis<C>
804        where
805            C: MapStorage + Default,
806            C::Key: FromStr,
807            C::Value: ProtoElemJson,
808        {
809            type Value = C;
810            fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
811                f.write_str("a JSON object with string keys, or null")
812            }
813            fn visit_unit<E>(self) -> Result<Self::Value, E> {
814                Ok(C::default())
815            }
816            crate::reject_other_json_kinds!(
817                bool, i64, u64, i128, u128, f64, str, string, bytes, byte_buf
818            );
819            fn visit_map<A: serde::de::MapAccess<'de>>(
820                self,
821                mut map: A,
822            ) -> Result<Self::Value, A::Error> {
823                let mut out = C::default();
824                while let Some(key) = map.next_key::<String>()? {
825                    let k = <C::Key as FromStr>::from_str(&key)
826                        .map_err(|_| serde::de::Error::custom(super::JsonValueError::MapKey))?;
827                    let k = crate::erasing::Erasing::new(k, C::storage_erase_key);
828                    let v =
829                        map.next_value_seed(ProtoElemSeed::<C::Value>(core::marker::PhantomData))?;
830                    out.storage_insert(k.into_inner(), v);
831                }
832                Ok(out)
833            }
834        }
835        d.deserialize_any(Vis::<C>(core::marker::PhantomData))
836    }
837}
838
839/// Serde with-module for `map<string, V>` fields whose **value** needs
840/// proto3-JSON encoding ([`ProtoElemJson`]: int64→quoted, float→NaN token,
841/// bytes→base64, or a bool or `String` whose wrong-kind errors must omit the
842/// value) and whose **key** is a `String` or a custom
843/// [`ProtoString`](crate::types::ProtoString) type.
844///
845/// This is the string-key twin of [`proto_map`]. [`proto_map`] stringifies its
846/// key via `Display` / `FromStr`, which a `ProtoString` newtype need not
847/// implement; here the key is already a JSON string, so it is serialized and
848/// deserialized through its own `serde` impls (a custom string type used in a
849/// map is required to derive `Serialize` / `Deserialize`). The value path is
850/// identical to [`proto_map`], and JSON `null` likewise deserializes to an empty
851/// map.
852pub mod proto_str_key_map {
853    use super::{ProtoElemJson, ProtoElemSeed, ProtoJson};
854    use crate::map_codec::MapStorage;
855    use serde::{Deserializer, Serializer};
856
857    pub fn serialize<C, S>(m: &C, s: S) -> Result<S::Ok, S::Error>
858    where
859        C: MapStorage,
860        C::Key: serde::Serialize,
861        C::Value: ProtoElemJson,
862        S: Serializer,
863    {
864        use serde::ser::SerializeMap;
865        let mut map = s.serialize_map(Some(m.storage_len()))?;
866        for (k, v) in m.storage_iter() {
867            map.serialize_entry(k, &ProtoJson(v))?;
868        }
869        map.end()
870    }
871
872    pub fn deserialize<'de, C, D>(d: D) -> Result<C, D::Error>
873    where
874        C: MapStorage + Default,
875        C::Key: serde::Deserialize<'de>,
876        C::Value: ProtoElemJson,
877        D: Deserializer<'de>,
878    {
879        struct Vis<C>(core::marker::PhantomData<C>);
880        impl<'de, C> serde::de::Visitor<'de> for Vis<C>
881        where
882            C: MapStorage + Default,
883            C::Key: serde::Deserialize<'de>,
884            C::Value: ProtoElemJson,
885        {
886            type Value = C;
887            fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
888                f.write_str("a JSON object with string keys, or null")
889            }
890            fn visit_enum<A: serde::de::EnumAccess<'de>>(
891                self,
892                tagged: A,
893            ) -> Result<Self::Value, A::Error> {
894                super::deserialize_tagged(self, tagged)
895            }
896            fn visit_unit<E>(self) -> Result<Self::Value, E> {
897                Ok(C::default())
898            }
899            crate::reject_other_json_kinds!(
900                bool, i64, u64, i128, u128, f64, str, string, bytes, byte_buf
901            );
902            fn visit_map<A: serde::de::MapAccess<'de>>(
903                self,
904                mut map: A,
905            ) -> Result<Self::Value, A::Error> {
906                let mut out = C::default();
907                while let Some(k) = map.next_key::<C::Key>()? {
908                    let k = crate::erasing::Erasing::new(k, C::storage_erase_key);
909                    let v =
910                        map.next_value_seed(ProtoElemSeed::<C::Value>(core::marker::PhantomData))?;
911                    out.storage_insert(k.into_inner(), v);
912                }
913                Ok(out)
914            }
915        }
916        d.deserialize_any(Vis::<C>(core::marker::PhantomData))
917    }
918}
919
920// ── bool ─────────────────────────────────────────────────────────────────────
921
922/// Serde with-module for `bool` fields that accepts JSON `null` as `false`.
923///
924/// Use with `#[serde(with = "::buffa::json_helpers::proto_bool")]`.
925pub mod proto_bool {
926    use serde::{Deserializer, Serializer};
927
928    pub fn serialize<S: Serializer>(value: &bool, s: S) -> Result<S::Ok, S::Error> {
929        s.serialize_bool(*value)
930    }
931
932    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<bool, D::Error> {
933        struct V;
934        impl<'de> serde::de::Visitor<'de> for V {
935            type Value = bool;
936            fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
937                f.write_str("a boolean or null")
938            }
939            fn visit_unit<E>(self) -> Result<bool, E> {
940                Ok(false)
941            }
942            fn visit_bool<E>(self, v: bool) -> Result<bool, E> {
943                Ok(v)
944            }
945            crate::reject_other_json_kinds!(
946                i64, u64, i128, u128, f64, str, string, bytes, byte_buf
947            );
948        }
949        d.deserialize_any(V)
950    }
951}
952
953// ── string ───────────────────────────────────────────────────────────────────
954
955/// Serde with-module for `string` fields that accepts JSON `null` as `""`.
956///
957/// Use with `#[serde(with = "::buffa::json_helpers::proto_string")]`.
958pub mod proto_string {
959    use serde::{Deserializer, Serializer};
960
961    /// Serialize a `string` field.
962    ///
963    /// Generic over `T: AsRef<str>` so configurable string types
964    /// (`smol_str::SmolStr`, `ecow::EcoString`, ...) serialize without relying
965    /// on `Deref<Target = str>` coercion at the `#[serde(with = ...)]` call
966    /// site. `String` and `&str` both satisfy the bound.
967    pub fn serialize<T: AsRef<str> + ?Sized, S: Serializer>(
968        value: &T,
969        s: S,
970    ) -> Result<S::Ok, S::Error> {
971        s.serialize_str(value.as_ref())
972    }
973
974    /// Deserialize a `string` field (or JSON `null` → `""`).
975    ///
976    /// Generic over the return type so that codegen's `string_type` knob (which
977    /// can map the field to `smol_str::SmolStr`, `ecow::EcoString`, etc.) works
978    /// without a per-type shim. The visitor constructs the target type directly:
979    /// `visit_str` goes through `ProtoString::copy_from_str`, which an SSO type
980    /// can override to inline short strings without an intermediate `String`.
981    /// `String` itself implements `ProtoString`, keeping the
982    /// default path zero-extra-cost. Type inference picks `T` from the field
983    /// type at the serde call site.
984    pub fn deserialize<'de, T, D>(d: D) -> Result<T, D::Error>
985    where
986        T: crate::ProtoString,
987        D: Deserializer<'de>,
988    {
989        struct V<T>(core::marker::PhantomData<T>);
990        impl<'de, T> serde::de::Visitor<'de> for V<T>
991        where
992            T: crate::ProtoString,
993        {
994            type Value = T;
995            fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
996                f.write_str("a string or null")
997            }
998            fn visit_unit<E>(self) -> Result<T, E> {
999                Ok(T::copy_from_str(""))
1000            }
1001            fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<T, E> {
1002                Ok(T::copy_from_str(v))
1003            }
1004            fn visit_string<E>(self, v: alloc::string::String) -> Result<T, E> {
1005                Ok(T::from(v))
1006            }
1007            crate::reject_other_json_kinds!(bool, i64, u64, i128, u128, f64, bytes, byte_buf);
1008        }
1009        d.deserialize_any(V::<T>(core::marker::PhantomData))
1010    }
1011}
1012
1013// ── enum ─────────────────────────────────────────────────────────────────────
1014
1015/// Shared reasons for protobuf enum values and collection-shape errors.
1016/// Reflective list and map fields also use the collection reasons. Diagnostics
1017/// stay independent of the input value so a parse failure does not disclose it.
1018#[doc(hidden)]
1019#[derive(Clone, Copy, Debug, thiserror::Error)]
1020#[non_exhaustive]
1021pub enum EnumJsonErrorReason {
1022    #[error("unknown enum name")]
1023    UnknownName,
1024    #[error("unknown enum number")]
1025    UnknownNumber,
1026    #[error("enum number out of i32 range")]
1027    OutOfRange,
1028    #[error("expected a protobuf enum name or integer")]
1029    InvalidType,
1030    #[error("expected a protobuf list or null")]
1031    InvalidListType,
1032    #[error("expected a protobuf map or null")]
1033    InvalidMapType,
1034}
1035
1036// Wrong-shaped scalar values must not bypass redaction at a collection boundary.
1037macro_rules! reject_container_scalar_values {
1038    ($reason:ident) => {
1039        fn visit_string<Err: serde::de::Error>(
1040            self,
1041            value: alloc::string::String,
1042        ) -> Result<Self::Value, Err> {
1043            crate::json_helpers::discard_rejected_text(value);
1044            Err(Err::custom(
1045                crate::json_helpers::EnumJsonErrorReason::$reason,
1046            ))
1047        }
1048        fn visit_str<Err: serde::de::Error>(self, _: &str) -> Result<Self::Value, Err> {
1049            Err(Err::custom(
1050                crate::json_helpers::EnumJsonErrorReason::$reason,
1051            ))
1052        }
1053        fn visit_i64<Err: serde::de::Error>(self, _: i64) -> Result<Self::Value, Err> {
1054            Err(Err::custom(
1055                crate::json_helpers::EnumJsonErrorReason::$reason,
1056            ))
1057        }
1058        fn visit_u64<Err: serde::de::Error>(self, _: u64) -> Result<Self::Value, Err> {
1059            Err(Err::custom(
1060                crate::json_helpers::EnumJsonErrorReason::$reason,
1061            ))
1062        }
1063        fn visit_i128<Err: serde::de::Error>(self, _: i128) -> Result<Self::Value, Err> {
1064            Err(Err::custom(
1065                crate::json_helpers::EnumJsonErrorReason::$reason,
1066            ))
1067        }
1068        fn visit_u128<Err: serde::de::Error>(self, _: u128) -> Result<Self::Value, Err> {
1069            Err(Err::custom(
1070                crate::json_helpers::EnumJsonErrorReason::$reason,
1071            ))
1072        }
1073        fn visit_f64<Err: serde::de::Error>(self, _: f64) -> Result<Self::Value, Err> {
1074            Err(Err::custom(
1075                crate::json_helpers::EnumJsonErrorReason::$reason,
1076            ))
1077        }
1078        fn visit_bool<Err: serde::de::Error>(self, _: bool) -> Result<Self::Value, Err> {
1079            Err(Err::custom(
1080                crate::json_helpers::EnumJsonErrorReason::$reason,
1081            ))
1082        }
1083    };
1084}
1085
1086/// Serde with-module for `EnumValue<E>` fields that accepts JSON `null` as the default.
1087///
1088/// Use with `#[serde(with = "::buffa::json_helpers::proto_enum")]`.
1089pub mod proto_enum {
1090    use super::EnumJsonErrorReason;
1091    use serde::{Deserializer, Serializer};
1092
1093    pub fn serialize<E: crate::Enumeration, S: Serializer>(
1094        value: &crate::EnumValue<E>,
1095        s: S,
1096    ) -> Result<S::Ok, S::Error> {
1097        serde::Serialize::serialize(value, s)
1098    }
1099
1100    pub fn deserialize<'de, E: crate::Enumeration, D: Deserializer<'de>>(
1101        d: D,
1102    ) -> Result<crate::EnumValue<E>, D::Error> {
1103        struct V<E>(core::marker::PhantomData<E>);
1104        impl<'de, E: crate::Enumeration> serde::de::Visitor<'de> for V<E> {
1105            type Value = crate::EnumValue<E>;
1106            fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1107                f.write_str("a protobuf enum name string, integer value, or null")
1108            }
1109            fn visit_unit<Err>(self) -> Result<crate::EnumValue<E>, Err> {
1110                Ok(crate::EnumValue::from(0))
1111            }
1112            fn visit_i64<Err: serde::de::Error>(self, v: i64) -> Result<crate::EnumValue<E>, Err> {
1113                let i =
1114                    i32::try_from(v).map_err(|_| Err::custom(EnumJsonErrorReason::OutOfRange))?;
1115                Ok(crate::EnumValue::from(i))
1116            }
1117            fn visit_u64<Err: serde::de::Error>(self, v: u64) -> Result<crate::EnumValue<E>, Err> {
1118                let i =
1119                    i32::try_from(v).map_err(|_| Err::custom(EnumJsonErrorReason::OutOfRange))?;
1120                Ok(crate::EnumValue::from(i))
1121            }
1122            // Formats that deliver 128-bit integers (YAML, for one) take the
1123            // 64-bit path; serde's defaults would echo the number.
1124            fn visit_i128<Err: serde::de::Error>(self, v: i128) -> Result<Self::Value, Err> {
1125                let v =
1126                    i64::try_from(v).map_err(|_| Err::custom(EnumJsonErrorReason::OutOfRange))?;
1127                self.visit_i64(v)
1128            }
1129            fn visit_u128<Err: serde::de::Error>(self, v: u128) -> Result<Self::Value, Err> {
1130                let v =
1131                    u64::try_from(v).map_err(|_| Err::custom(EnumJsonErrorReason::OutOfRange))?;
1132                self.visit_u64(v)
1133            }
1134            fn visit_f64<Err: serde::de::Error>(self, _: f64) -> Result<Self::Value, Err> {
1135                Err(Err::custom(EnumJsonErrorReason::InvalidType))
1136            }
1137            fn visit_bool<Err: serde::de::Error>(self, _: bool) -> Result<Self::Value, Err> {
1138                Err(Err::custom(EnumJsonErrorReason::InvalidType))
1139            }
1140            #[cfg(feature = "zeroize")]
1141            fn visit_string<Err: serde::de::Error>(
1142                self,
1143                value: alloc::string::String,
1144            ) -> Result<Self::Value, Err> {
1145                // Generated open-enum fields use this adapter rather than the
1146                // standalone EnumValue visitor. Each owns its transferred token.
1147                let value = zeroize::Zeroizing::new(value);
1148                self.visit_str(&value)
1149            }
1150            #[cfg(feature = "zeroize")]
1151            fn visit_byte_buf<Err: serde::de::Error>(
1152                self,
1153                value: alloc::vec::Vec<u8>,
1154            ) -> Result<Self::Value, Err> {
1155                // Preserve Serde's borrowed-byte rejection while wiping the
1156                // owned allocation that its default forwarding would release.
1157                let value = zeroize::Zeroizing::new(value);
1158                self.visit_bytes(&value)
1159            }
1160            fn visit_str<Err: serde::de::Error>(self, v: &str) -> Result<crate::EnumValue<E>, Err> {
1161                match E::from_proto_name(v) {
1162                    Some(e) => Ok(crate::EnumValue::from(e)),
1163                    None => {
1164                        if crate::json::ignore_unknown_enum_values() {
1165                            return Ok(crate::EnumValue::from(0));
1166                        }
1167                        Err(Err::custom(EnumJsonErrorReason::UnknownName))
1168                    }
1169                }
1170            }
1171        }
1172        d.deserialize_any(V(core::marker::PhantomData))
1173    }
1174}
1175
1176// ── lenient enum deserialization helpers ──────────────────────────────────────
1177
1178/// Try to decode a `serde_json::Value` as a closed enum via [`Enumeration`].
1179///
1180/// When `ignore_unknown_enum_values` is active, returns `Ok(None)` for a
1181/// [`ClosedEnumError::Unknown`] value, so the caller can drop the entry from
1182/// its container (or leave the optional unset). A
1183/// [`ClosedEnumError::Malformed`] value is an error in both modes. Strict
1184/// mode propagates every error. [`try_deserialize_enum`] filters unknown
1185/// names for open enums.
1186///
1187/// Why not [`try_deserialize_enum::<E>`]? It routes through
1188/// `serde_json::from_value::<E>()`, which requires `E: DeserializeOwned` —
1189/// i.e. the enum itself must `impl Deserialize`. That impl is only emitted
1190/// by codegen when `generate_json = true`, so closed-enum fields whose enum
1191/// type lives in an externally-generated crate built *without* json (e.g.
1192/// `google.protobuf.FieldDescriptorProto.Type` from `buffa-descriptor`)
1193/// would refuse to compile. Decoding directly via the [`Enumeration`] trait
1194/// removes the impl requirement. It uses `from_proto_name` for strings and
1195/// `from_i32` after range-checking integers. Null is handled by the optional
1196/// field helper before this call and rejected inside containers.
1197///
1198/// Lenient filtering works in both `std` and `no_std` builds. Unlike the
1199/// open-enum helper, this path decodes directly through [`Enumeration`], so
1200/// it never needs a scoped strict-mode override.
1201///
1202/// [`Enumeration`]: crate::Enumeration
1203#[inline]
1204fn try_deserialize_closed_enum<E: crate::Enumeration + Default>(
1205    raw: &serde_json::Value,
1206) -> Result<Option<E>, EnumJsonErrorReason> {
1207    match decode_closed_enum::<E>(raw) {
1208        Ok(e) => Ok(Some(e)),
1209        Err(ClosedEnumError::Unknown(_)) if crate::json::ignore_unknown_enum_values() => Ok(None),
1210        Err(ClosedEnumError::Unknown(reason) | ClosedEnumError::Malformed(reason)) => Err(reason),
1211    }
1212}
1213
1214/// Why a buffered JSON value is not a variant of a closed enum.
1215enum ClosedEnumError {
1216    /// A name, or a number in `i32` range, that the enum does not declare.
1217    /// Lenient parsing drops the value.
1218    Unknown(EnumJsonErrorReason),
1219    /// Null, a float, a number outside `i32`, a bool, an object or an array. An
1220    /// error whether or not parsing is lenient.
1221    Malformed(EnumJsonErrorReason),
1222}
1223
1224/// Closed-enum decode of a buffered `serde_json::Value`, bound only on
1225/// [`Enumeration`]. Every failure is an error here.
1226///
1227/// Accepts enum names and integer values. The optional-field helper handles
1228/// null before calling this function; repeated elements and map values must
1229/// reject it, even when unknown enum values are ignored.
1230///
1231/// [`Enumeration`]: crate::Enumeration
1232fn decode_closed_enum<E: crate::Enumeration + Default>(
1233    raw: &serde_json::Value,
1234) -> Result<E, ClosedEnumError> {
1235    use serde_json::Value;
1236
1237    match raw {
1238        Value::String(s) => {
1239            E::from_proto_name(s).ok_or(ClosedEnumError::Unknown(EnumJsonErrorReason::UnknownName))
1240        }
1241        Value::Number(n) if n.is_f64() => {
1242            Err(ClosedEnumError::Malformed(EnumJsonErrorReason::InvalidType))
1243        }
1244        Value::Number(n) => {
1245            // `as_i64()` / `as_u64()` are exclusive (a `Number` is stored
1246            // as exactly one of i64 / u64 / f64; the float case is handled
1247            // above). Try both before declaring it un-coerceable.
1248            let v32 = n
1249                .as_i64()
1250                .and_then(|v| i32::try_from(v).ok())
1251                .or_else(|| n.as_u64().and_then(|v| i32::try_from(v).ok()))
1252                .ok_or(ClosedEnumError::Malformed(EnumJsonErrorReason::OutOfRange))?;
1253            E::from_i32(v32).ok_or(ClosedEnumError::Unknown(EnumJsonErrorReason::UnknownNumber))
1254        }
1255        Value::Null | Value::Bool(_) | Value::Array(_) | Value::Object(_) => {
1256            Err(ClosedEnumError::Malformed(EnumJsonErrorReason::InvalidType))
1257        }
1258    }
1259}
1260
1261/// Try to deserialize a `serde_json::Value` as `T` under strict enum parsing.
1262///
1263/// When `ignore_unknown_enum_values` is active, returns `Ok(None)` for an
1264/// unknown enum name, so the caller can drop the entry from its container
1265/// (or leave the optional unset). A string is the one JSON type whose decode
1266/// can fail on an unknown value: an `EnumValue` keeps an unknown number, so
1267/// every other failure is a wrong JSON type or a number outside `i32`, and
1268/// stays an error.
1269///
1270/// In `std` builds, filtering temporarily forces strict mode so an unknown
1271/// enum name remains distinguishable from the default value. In `no_std`
1272/// builds, `EnumValue` deserialization is already strict, so the process-wide
1273/// option can filter the resulting error directly. Closed-enum containers use
1274/// [`try_deserialize_closed_enum`] and follow the same lenient behavior.
1275#[inline]
1276fn try_deserialize_enum<T: serde::de::DeserializeOwned>(
1277    raw: serde_json::Value,
1278) -> Result<Option<T>, serde_json::Error> {
1279    // Only a name can fail as unknown; see the doc comment.
1280    let raw_is_string = raw.is_string();
1281    let ignore = crate::json::ignore_unknown_enum_values();
1282    // Run the inner deserialize in STRICT mode so that an unknown enum name
1283    // is an error and not the default value.
1284    #[cfg(feature = "std")]
1285    let result = {
1286        let strict = crate::json::JsonParseOptions {
1287            ignore_unknown_enum_values: false,
1288            ..Default::default()
1289        };
1290        crate::json::with_json_parse_options(&strict, || serde_json::from_value::<T>(raw))
1291    };
1292    // The inner `EnumValue` deserialize is always strict here; see the doc
1293    // comment above.
1294    #[cfg(not(feature = "std"))]
1295    let result = serde_json::from_value::<T>(raw);
1296    match result {
1297        Ok(v) => Ok(Some(v)),
1298        Err(_) if ignore && raw_is_string => Ok(None),
1299        Err(e) => Err(e),
1300    }
1301}
1302
1303// ── repeated_enum: Vec<EnumValue<E>> with unknown-value filtering ────────────
1304
1305/// Serde with-module for `Vec<EnumValue<E>>` repeated enum fields, or any
1306/// collection that is `From<Vec<EnumValue<E>>>`.
1307///
1308/// When `ignore_unknown_enum_values` is active, unknown enum string values
1309/// are silently skipped instead of producing an error. In default mode this
1310/// accepts names and integers, rejecting null elements except for enums
1311/// explicitly representing NullValue. Whole-field null remains empty.
1312pub mod repeated_enum {
1313    use alloc::vec::Vec;
1314    use serde::{Deserializer, Serializer};
1315
1316    pub fn serialize<E: crate::Enumeration, S: Serializer>(
1317        value: &[crate::EnumValue<E>],
1318        s: S,
1319    ) -> Result<S::Ok, S::Error> {
1320        if !E::IS_NULL_VALUE || !s.is_human_readable() {
1321            return serde::Serialize::serialize(value, s);
1322        }
1323        use serde::ser::SerializeSeq as _;
1324        let mut sequence = s.serialize_seq(Some(value.len()))?;
1325        for element in value {
1326            if element.to_i32() == 0 {
1327                sequence.serialize_element(&())?;
1328            } else {
1329                sequence.serialize_element(element)?;
1330            }
1331        }
1332        sequence.end()
1333    }
1334
1335    pub fn deserialize<'de, E, C, D>(d: D) -> Result<C, D::Error>
1336    where
1337        E: crate::Enumeration,
1338        C: From<Vec<crate::EnumValue<E>>>,
1339        D: Deserializer<'de>,
1340    {
1341        struct V<E>(core::marker::PhantomData<E>);
1342        impl<'de, E: crate::Enumeration> serde::de::Visitor<'de> for V<E> {
1343            type Value = Vec<crate::EnumValue<E>>;
1344
1345            fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1346                f.write_str("a list of enum values or null")
1347            }
1348
1349            fn visit_unit<Err>(self) -> Result<Vec<crate::EnumValue<E>>, Err> {
1350                Ok(Vec::new())
1351            }
1352
1353            reject_container_scalar_values!(InvalidListType);
1354            crate::__buffa_reject_other_json_kinds!(bytes, byte_buf);
1355            fn visit_seq<A: serde::de::SeqAccess<'de>>(
1356                self,
1357                mut seq: A,
1358            ) -> Result<Vec<crate::EnumValue<E>>, A::Error> {
1359                let mut out = Vec::with_capacity(super::clamp_size_hint(seq.size_hint()));
1360                while let Some(super::BufferedValue(raw)) = seq.next_element()? {
1361                    if raw.is_null() && !E::IS_NULL_VALUE {
1362                        return Err(serde::de::Error::custom(
1363                            super::enum_list::ErrorReason::Null,
1364                        ));
1365                    }
1366                    match super::try_deserialize_enum::<crate::EnumValue<E>>(raw) {
1367                        Ok(Some(v)) => out.push(v),
1368                        Ok(None) => continue,
1369                        Err(e) => return Err(serde::de::Error::custom(e)),
1370                    }
1371                }
1372                Ok(out)
1373            }
1374        }
1375        d.deserialize_any(V::<E>(core::marker::PhantomData))
1376            .map(C::from)
1377    }
1378}
1379
1380// ── map_enum: HashMap<K, EnumValue<E>> with unknown-value filtering ─────────
1381
1382/// Serde with-module for `HashMap<K, EnumValue<E>>` map fields where the
1383/// value is an enum type.
1384///
1385/// When `ignore_unknown_enum_values` is active, map entries whose value is
1386/// an unknown enum string are silently dropped. In default mode this behaves
1387/// identically to standard deserialization with null→empty-map handling.
1388///
1389/// The lenient rule assumes that the map's value type is `EnumValue<E>`: it
1390/// drops an entry whose value is a string that fails to decode.
1391pub mod map_enum {
1392    use crate::map_codec::MapStorage;
1393    use serde::{Deserializer, Serializer};
1394
1395    pub fn serialize<C, S>(value: &C, s: S) -> Result<S::Ok, S::Error>
1396    where
1397        C: MapStorage,
1398        C::Key: serde::Serialize,
1399        C::Value: serde::Serialize,
1400        S: Serializer,
1401    {
1402        use serde::ser::SerializeMap;
1403        let mut map = s.serialize_map(Some(value.storage_len()))?;
1404        for (k, v) in value.storage_iter() {
1405            map.serialize_entry(k, v)?;
1406        }
1407        map.end()
1408    }
1409
1410    pub fn deserialize<'de, C, D>(d: D) -> Result<C, D::Error>
1411    where
1412        C: MapStorage + Default,
1413        C::Key: serde::Deserialize<'de>,
1414        C::Value: serde::de::DeserializeOwned,
1415        D: Deserializer<'de>,
1416    {
1417        struct V<C>(core::marker::PhantomData<C>);
1418        impl<'de, C> serde::de::Visitor<'de> for V<C>
1419        where
1420            C: MapStorage + Default,
1421            C::Key: serde::Deserialize<'de>,
1422            C::Value: serde::de::DeserializeOwned,
1423        {
1424            type Value = C;
1425
1426            fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1427                f.write_str("a map with enum values or null")
1428            }
1429
1430            fn visit_unit<Err>(self) -> Result<Self::Value, Err> {
1431                Ok(C::default())
1432            }
1433
1434            reject_container_scalar_values!(InvalidMapType);
1435            crate::__buffa_reject_other_json_kinds!(bytes, byte_buf);
1436            fn visit_map<A: serde::de::MapAccess<'de>>(
1437                self,
1438                mut map: A,
1439            ) -> Result<Self::Value, A::Error> {
1440                let mut out = C::default();
1441                while let Some(key) = map.next_key_seed(super::map_key::KeySeed::<C::Key>::new())? {
1442                    let key = crate::erasing::Erasing::new(key, C::storage_erase_key);
1443                    let super::BufferedValue(raw) = map.next_value()?;
1444                    match super::try_deserialize_enum::<C::Value>(raw) {
1445                        Ok(Some(v)) => {
1446                            out.storage_insert(key.into_inner(), v);
1447                        }
1448                        Ok(None) => continue,
1449                        Err(e) => return Err(serde::de::Error::custom(e)),
1450                    }
1451                }
1452                Ok(out)
1453            }
1454        }
1455        d.deserialize_any(V::<C>(core::marker::PhantomData))
1456    }
1457}
1458
1459// ── null_as_default: generic null→Default handler ────────────────────────────
1460
1461/// Generic deserialize function that treats JSON `null` as `T::default()`.
1462///
1463/// Use with `#[serde(deserialize_with = "::buffa::json_helpers::null_as_default")]`
1464/// for repeated fields, map fields, and any other type where null should
1465/// silently produce the default value.
1466pub fn null_as_default<'de, D, T>(d: D) -> Result<T, D::Error>
1467where
1468    D: serde::Deserializer<'de>,
1469    T: Default + serde::Deserialize<'de>,
1470{
1471    <Option<T> as serde::Deserialize>::deserialize(d).map(|opt| opt.unwrap_or_default())
1472}
1473
1474// ── shared helper: parse string as integer, accepting floats/exponentials ────
1475
1476/// Returns `true` if `f` has no fractional part (i.e. it is an exact integer).
1477///
1478/// Casts to `i128` and back — if the round-trip preserves the value, `f` has
1479/// no fractional part.  Deliberately not `f64::trunc()`-based: values outside
1480/// i128 range saturate, producing a mismatch that correctly returns `false`
1481/// (such values cannot fit any protobuf integer type anyway).
1482fn is_exact_integer(f: f64) -> bool {
1483    f.is_finite() && f == (f as i128 as f64)
1484}
1485
1486/// Largest integer-valued `f64` this visitor accepts from an unquoted JSON
1487/// decimal/exponent token: 2^52 - 1.
1488///
1489/// The hazard is not only f64 representability (integers up to 2^53 are
1490/// exact) but `serde_json`'s *default* float parsing, which is not
1491/// correctly rounded (that is its opt-in `float_roundtrip` feature) and can
1492/// be off by an ulp. In `[2^52, 2^53)` an ulp is exactly 1, so a one-ulp
1493/// parse error silently turns an integer token into the *adjacent* integer
1494/// — observed: `"9007199254740991.0"` parsing as `…990.0`. Below 2^52 an
1495/// ulp is at most 0.5, so the same parse error breaks integrality instead
1496/// and the exactness check below rejects the token loudly rather than
1497/// mis-decoding it. Quote larger integer values to parse them exactly —
1498/// the quoted-string path parses the token text digit-by-digit.
1499const MAX_SAFE_JSON_INTEGER_F64: f64 = 4_503_599_627_370_495.0;
1500
1501/// Try to parse a string as an integer, handling float notation like `"1.0"`,
1502/// `"1e5"`, `"1.0e2"`.  Returns `None` if the value is not an exact integer.
1503fn parse_int_from_str<I: TryFrom<i128>>(v: &str) -> Option<I> {
1504    // First try direct integer parse.
1505    if let Ok(n) = v.parse::<i128>() {
1506        return I::try_from(n).ok();
1507    }
1508    let n = parse_exact_decimal_int(v)?;
1509    I::try_from(n).ok()
1510}
1511
1512/// Parse a decimal/exponential string as an exact integer.
1513///
1514/// Accepts the numeric string forms the JSON integer helpers intentionally
1515/// support beyond plain integers: zero-fraction decimals like `"1.0"` and
1516/// decimal scientific notation like `"1e5"` / `"1.0e2"`. Returns `None` if
1517/// the value is not mathematically integral or would overflow `i128`.
1518fn parse_exact_decimal_int(v: &str) -> Option<i128> {
1519    let (mantissa, exp) = match v.split_once(['e', 'E']) {
1520        // `i64::from_str` handles the exponent's sign and rejects empty,
1521        // non-digit, and i64-overflowing exponents.
1522        Some((m, e)) => (m, e.parse::<i64>().ok()?),
1523        None => (v, 0),
1524    };
1525    let (negative, mantissa) = match mantissa.strip_prefix('-') {
1526        Some(rest) => (true, rest),
1527        None => (false, mantissa.strip_prefix('+').unwrap_or(mantissa)),
1528    };
1529    let (int_part, frac_part) = mantissa
1530        .split_once('.')
1531        .map_or((mantissa, ""), |(i, f)| (i, f));
1532    if int_part.is_empty() && frac_part.is_empty() {
1533        return None;
1534    }
1535    // Trailing zeros do not affect integrality and would only inflate the
1536    // significand before we re-scale it. Integer zeros move into the exponent.
1537    let frac_part = frac_part.trim_end_matches('0');
1538    let (int_part, trailing_zeros) = if frac_part.is_empty() {
1539        let trimmed = int_part.trim_end_matches('0');
1540        (trimmed, int_part.len() - trimmed.len())
1541    } else {
1542        (int_part, 0)
1543    };
1544
1545    let mut significand = 0i128;
1546    for digit in int_part.bytes().chain(frac_part.bytes()) {
1547        if !digit.is_ascii_digit() {
1548            return None;
1549        }
1550        significand = significand
1551            .checked_mul(10)?
1552            .checked_add(i128::from(digit - b'0'))?;
1553    }
1554    if significand == 0 {
1555        // Zero is integral under any exponent; short-circuit before the
1556        // power-of-ten scaling below can overflow on e.g. "0e100".
1557        return Some(0);
1558    }
1559
1560    // value = significand × 10^(exp + trailing_zeros − frac_len)
1561    let scale = exp
1562        .checked_add(trailing_zeros as i64)?
1563        .checked_sub(frac_part.len() as i64)?;
1564    if scale >= 0 {
1565        let pow10 = 10i128.checked_pow(u32::try_from(scale).ok()?)?;
1566        significand = significand.checked_mul(pow10)?;
1567    } else {
1568        let divisor = 10i128.checked_pow(u32::try_from(scale.unsigned_abs()).ok()?)?;
1569        if significand % divisor != 0 {
1570            return None;
1571        }
1572        significand /= divisor;
1573    }
1574
1575    if negative {
1576        significand.checked_neg()
1577    } else {
1578        Some(significand)
1579    }
1580}
1581
1582/// Try to interpret an f64 as an exact integer, rejecting magnitudes above
1583/// [`MAX_SAFE_JSON_INTEGER_F64`] where the value no longer uniquely
1584/// identifies the JSON token it was parsed from.
1585fn f64_to_int<I: TryFrom<i128>>(v: f64) -> Option<I> {
1586    if !(-MAX_SAFE_JSON_INTEGER_F64..=MAX_SAFE_JSON_INTEGER_F64).contains(&v) {
1587        return None;
1588    }
1589    if !is_exact_integer(v) {
1590        return None;
1591    }
1592    I::try_from(v as i128).ok()
1593}
1594
1595// ── int32 / uint32 / int64 / uint64 ──────────────────────────────────────────
1596//
1597// These four serde with-modules share the same structural shape: a visitor
1598// that accepts `unit` (-> 0), `i64`, `u64`, `f64`, and `str` inputs.  Only
1599// the target type and serialization format differ (32-bit as JSON numbers,
1600// 64-bit as quoted decimal strings).
1601
1602/// Generates a serde with-module for an integer type.
1603///
1604/// Parameters:
1605/// - `$mod_name` / `$int_type`: module name and Rust integer type.
1606/// - `serialize_body`: expression for the `serialize` function body, given
1607///   value identifier and serializer identifier.
1608/// - `expecting`: expecting string for the visitor.
1609/// - `doc`: doc string for the generated module.
1610/// - `reason`: fixed diagnostic for malformed or out-of-range values.
1611/// - `parse_str`: parser for the quoted numeric form.
1612macro_rules! int_serde_module {
1613    (
1614        $mod_name:ident, $int_type:ty,
1615        doc = $doc:expr,
1616        serialize_body = |$val:ident, $ser:ident| $ser_body:expr,
1617        expecting = $expecting:expr,
1618        reason = $reason:ident,
1619        parse_str = $parse_str:ident $(,)?
1620    ) => {
1621        #[doc = $doc]
1622        pub mod $mod_name {
1623            use super::*;
1624            use serde::{Deserializer, Serializer};
1625
1626            pub fn serialize<S: Serializer>(value: &$int_type, s: S) -> Result<S::Ok, S::Error> {
1627                let $val = value;
1628                let $ser = s;
1629                $ser_body
1630            }
1631
1632            pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<$int_type, D::Error> {
1633                struct Vis;
1634                impl<'de> serde::de::Visitor<'de> for Vis {
1635                    type Value = $int_type;
1636                    fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1637                        f.write_str($expecting)
1638                    }
1639                    fn visit_unit<E>(self) -> Result<$int_type, E> {
1640                        Ok(0)
1641                    }
1642                    fn visit_bool<E: serde::de::Error>(self, _: bool) -> Result<$int_type, E> {
1643                        Err(E::custom(JsonValueError::$reason))
1644                    }
1645                    fn visit_i64<E: serde::de::Error>(self, v: i64) -> Result<$int_type, E> {
1646                        <$int_type>::try_from(v).map_err(|_| E::custom(JsonValueError::$reason))
1647                    }
1648                    fn visit_u64<E: serde::de::Error>(self, v: u64) -> Result<$int_type, E> {
1649                        <$int_type>::try_from(v).map_err(|_| E::custom(JsonValueError::$reason))
1650                    }
1651                    fn visit_f64<E: serde::de::Error>(self, v: f64) -> Result<$int_type, E> {
1652                        f64_to_int::<$int_type>(v).ok_or_else(|| E::custom(JsonValueError::$reason))
1653                    }
1654                    fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<$int_type, E> {
1655                        $parse_str(v).ok_or_else(|| E::custom(JsonValueError::$reason))
1656                    }
1657                    fn visit_string<E: serde::de::Error>(
1658                        self,
1659                        value: alloc::string::String,
1660                    ) -> Result<$int_type, E> {
1661                        // A transferred token is ours to erase even if parsing fails.
1662                        #[cfg(feature = "zeroize")]
1663                        let value = zeroize::Zeroizing::new(value);
1664                        self.visit_str(&value)
1665                    }
1666                    visit_wide_ints!(JsonValueError::$reason);
1667                    crate::reject_other_json_kinds!(bytes, byte_buf);
1668                }
1669                d.deserialize_any(Vis)
1670            }
1671        }
1672    };
1673}
1674
1675int_serde_module!(
1676    int32,
1677    i32,
1678    doc = "Serde with-module for `i32` fields.\n\n\
1679           Proto JSON accepts integers as numbers, quoted decimal strings, or\n\
1680           float notation (e.g. `1.0`, `1e5`).  Serializes as a JSON number.\n\n\
1681           Use with `#[serde(with = \"::buffa::json_helpers::int32\")]`.",
1682    serialize_body = |v, s| s.serialize_i32(*v),
1683    expecting = "an i32 as integer, string, float, or null",
1684    reason = Int32,
1685    parse_str = parse_int_from_str,
1686);
1687
1688int_serde_module!(
1689    uint32,
1690    u32,
1691    doc = "Serde with-module for `u32` fields.\n\n\
1692           Proto JSON accepts integers as numbers, quoted decimal strings, or\n\
1693           float notation (e.g. `1.0`, `1e5`).  Serializes as a JSON number.\n\n\
1694           Use with `#[serde(with = \"::buffa::json_helpers::uint32\")]`.",
1695    serialize_body = |v, s| s.serialize_u32(*v),
1696    expecting = "a u32 as integer, string, float, or null",
1697    reason = Uint32,
1698    parse_str = parse_int_from_str,
1699);
1700
1701int_serde_module!(
1702    int64,
1703    i64,
1704    doc = "Serde with-module for `i64` fields encoded as a quoted decimal string.\n\n\
1705           Proto JSON also accepts unquoted integers and float notation.\n\n\
1706           Use with `#[serde(with = \"::buffa::json_helpers::int64\")]`.",
1707    serialize_body = |v, s| {
1708        #[cfg(feature = "zeroize")]
1709        {
1710            crate::sensitive::serialize_decimal(v, s)
1711        }
1712        #[cfg(not(feature = "zeroize"))]
1713        {
1714            s.collect_str(v)
1715        }
1716    },
1717    expecting = "an i64 as a quoted decimal string, integer, float, or null",
1718    reason = Int64,
1719    parse_str = parse_int_from_str,
1720);
1721
1722// Try the full unsigned range before accepting decimal or exponent notation.
1723fn parse_u64(value: &str) -> Option<u64> {
1724    value.parse().ok().or_else(|| parse_int_from_str(value))
1725}
1726
1727int_serde_module!(
1728    uint64,
1729    u64,
1730    doc = "Serde with-module for `u64` fields encoded as a quoted decimal string.\n\n\
1731           Proto JSON also accepts unquoted integers and float notation.\n\n\
1732           Use with `#[serde(with = \"::buffa::json_helpers::uint64\")]`.",
1733    serialize_body = |v, s| {
1734        #[cfg(feature = "zeroize")]
1735        {
1736            crate::sensitive::serialize_decimal(v, s)
1737        }
1738        #[cfg(not(feature = "zeroize"))]
1739        {
1740            s.collect_str(v)
1741        }
1742    },
1743    expecting = "a u64 as a quoted decimal string, integer, float, or null",
1744    reason = Uint64,
1745    parse_str = parse_u64,
1746);
1747
1748// ── float ────────────────────────────────────────────────────────────────────
1749
1750/// Serde with-module for `float` fields.
1751///
1752/// Serializes finite values as JSON numbers. Serializes `NaN` as `"NaN"`,
1753/// positive infinity as `"Infinity"`, and negative infinity as `"-Infinity"`.
1754/// Accepts numbers, quoted decimal numbers, and those three string literals on
1755/// deserialization. A number or quoted decimal outside the `f32` range is an
1756/// error, not infinity, and `"inf"` / `"nan"` in other spellings are rejected.
1757///
1758/// A quoted decimal is parsed straight to `f32`, so it is rounded once, and
1759/// so is an unquoted integer in the `i64` or `u64` range. Any other unquoted
1760/// number reaches the visitor as the `f64` the deserializer parsed and is then
1761/// narrowed to `f32`, so it is rounded twice. The results differ, by one `f32`
1762/// ulp, when a decimal close to the midpoint between two adjacent `f32` values
1763/// becomes that midpoint as an `f64`, which then rounds to even:
1764/// `1.0000000596046448` decodes to `1.0` unquoted and to its nearest `f32`,
1765/// `1.0000001`, quoted. How close is close enough depends on the `f64` parse
1766/// (half an `f64` ulp with `serde_json`'s `float_roundtrip` feature, somewhat
1767/// more without it). Just below the `f32` overflow threshold, the same effect
1768/// makes an unquoted value an error that parses when quoted.
1769///
1770/// protobuf C++ also narrows a parsed `double`; protobuf-go rounds once. The
1771/// `f64` does not identify the decimal it came from, so the decoding side
1772/// cannot avoid this. A producer that wants single rounding can quote the
1773/// value. Tracked in [#647](https://github.com/anthropics/buffa/issues/647).
1774///
1775/// Use with `#[serde(with = "::buffa::json_helpers::float")]`.
1776pub mod float {
1777    use serde::{Deserializer, Serializer};
1778
1779    pub fn serialize<S: Serializer>(value: &f32, s: S) -> Result<S::Ok, S::Error> {
1780        if value.is_nan() {
1781            s.serialize_str("NaN")
1782        } else if *value == f32::INFINITY {
1783            s.serialize_str("Infinity")
1784        } else if *value == f32::NEG_INFINITY {
1785            s.serialize_str("-Infinity")
1786        } else {
1787            s.serialize_f32(*value)
1788        }
1789    }
1790
1791    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<f32, D::Error> {
1792        struct V;
1793        impl<'de> serde::de::Visitor<'de> for V {
1794            type Value = f32;
1795
1796            fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1797                f.write_str(r#"a float, "NaN", "Infinity", "-Infinity", or null"#)
1798            }
1799
1800            fn visit_unit<E>(self) -> Result<f32, E> {
1801                Ok(0.0)
1802            }
1803
1804            fn visit_bool<E: serde::de::Error>(self, _: bool) -> Result<f32, E> {
1805                Err(E::custom(super::JsonValueError::Float))
1806            }
1807
1808            fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<f32, E> {
1809                match v {
1810                    "NaN" => Ok(f32::NAN),
1811                    "Infinity" => Ok(f32::INFINITY),
1812                    "-Infinity" => Ok(f32::NEG_INFINITY),
1813                    // Rust's float parser saturates to infinity on overflow
1814                    // and also spells non-finite values "inf" / "nan" in any
1815                    // case. The three ProtoJSON tokens were matched above, so
1816                    // any non-finite result is out of range or not a float.
1817                    // Parsing straight to f32 rounds once; going via f64
1818                    // could round a value just below the f32::MAX boundary
1819                    // up to infinity.
1820                    _ => match v.parse::<f32>() {
1821                        Ok(f) if f.is_finite() => Ok(f),
1822                        _ => Err(E::custom(super::JsonValueError::Float)),
1823                    },
1824                }
1825            }
1826
1827            fn visit_string<E: serde::de::Error>(
1828                self,
1829                value: alloc::string::String,
1830            ) -> Result<f32, E> {
1831                #[cfg(feature = "zeroize")]
1832                let value = zeroize::Zeroizing::new(value);
1833                self.visit_str(&value)
1834            }
1835
1836            fn visit_f32<E: serde::de::Error>(self, v: f32) -> Result<f32, E> {
1837                Ok(v)
1838            }
1839
1840            fn visit_f64<E: serde::de::Error>(self, v: f64) -> Result<f32, E> {
1841                // The range check is on the narrowed `f32`: a decimal just
1842                // above `f32::MAX` that rounds back into range parses, as the
1843                // canonical text of `f32::MAX` (`3.4028235e+38`) does.
1844                let f = v as f32;
1845                if v.is_finite() && !f.is_finite() {
1846                    return Err(E::custom(super::JsonValueError::Float));
1847                }
1848                Ok(f)
1849            }
1850
1851            fn visit_i64<E: serde::de::Error>(self, v: i64) -> Result<f32, E> {
1852                Ok(v as f32)
1853            }
1854
1855            visit_wide_ints!(super::JsonValueError::Float);
1856            crate::reject_other_json_kinds!(bytes, byte_buf);
1857
1858            fn visit_u64<E: serde::de::Error>(self, v: u64) -> Result<f32, E> {
1859                Ok(v as f32)
1860            }
1861        }
1862        d.deserialize_any(V)
1863    }
1864}
1865
1866// ── double ───────────────────────────────────────────────────────────────────
1867
1868/// Serde with-module for `double` fields.
1869///
1870/// Serializes finite values as JSON numbers. Serializes `NaN` as `"NaN"`,
1871/// positive infinity as `"Infinity"`, and negative infinity as `"-Infinity"`.
1872/// Accepts numbers, quoted decimal numbers, and those three string literals on
1873/// deserialization. A quoted decimal outside the `f64` range is an error, not
1874/// infinity, and `"inf"` / `"nan"` in other spellings are rejected.
1875///
1876/// Use with `#[serde(with = "::buffa::json_helpers::double")]`.
1877pub mod double {
1878    use serde::{Deserializer, Serializer};
1879
1880    pub fn serialize<S: Serializer>(value: &f64, s: S) -> Result<S::Ok, S::Error> {
1881        if value.is_nan() {
1882            s.serialize_str("NaN")
1883        } else if *value == f64::INFINITY {
1884            s.serialize_str("Infinity")
1885        } else if *value == f64::NEG_INFINITY {
1886            s.serialize_str("-Infinity")
1887        } else {
1888            s.serialize_f64(*value)
1889        }
1890    }
1891
1892    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<f64, D::Error> {
1893        struct V;
1894        impl<'de> serde::de::Visitor<'de> for V {
1895            type Value = f64;
1896
1897            fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1898                f.write_str(r#"a double, "NaN", "Infinity", "-Infinity", or null"#)
1899            }
1900
1901            fn visit_unit<E>(self) -> Result<f64, E> {
1902                Ok(0.0)
1903            }
1904
1905            fn visit_bool<E: serde::de::Error>(self, _: bool) -> Result<f64, E> {
1906                Err(E::custom(super::JsonValueError::Double))
1907            }
1908
1909            fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<f64, E> {
1910                match v {
1911                    "NaN" => Ok(f64::NAN),
1912                    "Infinity" => Ok(f64::INFINITY),
1913                    "-Infinity" => Ok(f64::NEG_INFINITY),
1914                    // As for `float`: a non-finite parse result is an
1915                    // overflow or a spelling ProtoJSON does not have.
1916                    _ => match v.parse::<f64>() {
1917                        Ok(f) if f.is_finite() => Ok(f),
1918                        _ => Err(E::custom(super::JsonValueError::Double)),
1919                    },
1920                }
1921            }
1922
1923            fn visit_string<E: serde::de::Error>(
1924                self,
1925                value: alloc::string::String,
1926            ) -> Result<f64, E> {
1927                #[cfg(feature = "zeroize")]
1928                let value = zeroize::Zeroizing::new(value);
1929                self.visit_str(&value)
1930            }
1931
1932            fn visit_f64<E: serde::de::Error>(self, v: f64) -> Result<f64, E> {
1933                Ok(v)
1934            }
1935
1936            fn visit_f32<E: serde::de::Error>(self, v: f32) -> Result<f64, E> {
1937                Ok(v as f64)
1938            }
1939
1940            fn visit_i64<E: serde::de::Error>(self, v: i64) -> Result<f64, E> {
1941                Ok(v as f64)
1942            }
1943
1944            visit_wide_ints!(super::JsonValueError::Double);
1945            crate::reject_other_json_kinds!(bytes, byte_buf);
1946
1947            fn visit_u64<E: serde::de::Error>(self, v: u64) -> Result<f64, E> {
1948                Ok(v as f64)
1949            }
1950        }
1951        d.deserialize_any(V)
1952    }
1953}
1954
1955// ── bytes ─────────────────────────────────────────────────────────────────────
1956
1957/// Serde with-module for `bytes` fields encoded as standard base64 (RFC 4648).
1958///
1959/// Serializes as standard padded base64. Accepts standard base64, URL-safe
1960/// base64, and both padded and unpadded variants on deserialization, as
1961/// required by the [proto3 JSON spec].
1962///
1963/// [proto3 JSON spec]: https://protobuf.dev/programming-guides/proto3/#json
1964///
1965/// Use with `#[serde(with = "::buffa::json_helpers::bytes")]`.
1966pub mod bytes {
1967    use super::STANDARD;
1968    use base64::Engine as _;
1969    use serde::{Deserializer, Serializer};
1970
1971    /// Serialize as a base64-encoded string.
1972    ///
1973    /// Takes `&[u8]` so both `Vec<u8>` and `bytes::Bytes` fields are
1974    /// accepted via deref coercion at the `#[serde(with = ...)]` call site.
1975    ///
1976    /// The encoding is streamed through [`Serializer::collect_str`], so a
1977    /// serializer that writes strings incrementally (such as `serde_json`'s)
1978    /// receives it without an intermediate heap `String`. A serializer that
1979    /// does not override `collect_str` still builds one, and the output is
1980    /// that of the serializer's `collect_str`, which for a conforming
1981    /// serializer matches `serialize_str`.
1982    pub fn serialize<S: Serializer>(value: &[u8], s: S) -> Result<S::Ok, S::Error> {
1983        s.collect_str(&base64::display::Base64Display::new(value, &STANDARD))
1984    }
1985
1986    /// Upper bound on the number of bytes `text` decodes to, for sizing the
1987    /// buffer passed to [`decode_into`].
1988    ///
1989    /// The bound is computed from the length of `text` alone: it does not
1990    /// validate `text` and can exceed the decoded size, so keep only the
1991    /// length [`decode_into`] returns.
1992    #[must_use]
1993    pub fn max_decoded_len(text: &str) -> usize {
1994        base64::decoded_len_estimate(text.len())
1995    }
1996
1997    /// Decode base64 `text` into storage the caller owns, returning the number
1998    /// of bytes written to the front of `out`.
1999    ///
2000    /// Accepts exactly the strings [`deserialize`] accepts (standard or
2001    /// URL-safe alphabet, padded or unpadded) and decodes once, without
2002    /// allocating. `out` needs room only for the decoded bytes, so a
2003    /// fixed-size key buffer works; a buffer of [`max_decoded_len`] bytes is
2004    /// always enough. With a fixed-size buffer, check that the returned length
2005    /// is the size you expect: shorter input succeeds and leaves the rest of
2006    /// `out` untouched, and longer input fails with the buffer error, not with
2007    /// a message about the key's length. Meant for a
2008    /// [`ProtoBytesJson`](super::ProtoBytesJson) implementation whose visitor
2009    /// borrows the JSON string and wants the decoded bytes to land in storage
2010    /// it wipes. The decoder itself keeps at most a few decoded bytes in stack
2011    /// slots and registers while it runs, which nothing wipes.
2012    ///
2013    /// The error type is generic so that the call fits a
2014    /// [`Visitor`](serde::de::Visitor) method; name it with a turbofish, as
2015    /// `?` alone cannot infer it. Outside a visitor,
2016    /// [`serde::de::value::Error`] is a ready-made choice.
2017    ///
2018    /// ```
2019    /// use buffa::json_helpers::bytes;
2020    /// use serde::de::{Deserializer as _, Error, Visitor};
2021    ///
2022    /// /// Stands in for storage that the policy wipes.
2023    /// struct Secret(Vec<u8>);
2024    ///
2025    /// struct SecretVisitor;
2026    /// impl<'de> Visitor<'de> for SecretVisitor {
2027    ///     type Value = Secret;
2028    ///     fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2029    ///         f.write_str("a base64-encoded string")
2030    ///     }
2031    ///     fn visit_str<E: Error>(self, text: &str) -> Result<Secret, E> {
2032    ///         let mut buf = vec![0; bytes::max_decoded_len(text)];
2033    ///         // Real code must also wipe `buf` when this returns early.
2034    ///         let len = bytes::decode_into::<E>(text, &mut buf)?;
2035    ///         buf.truncate(len);
2036    ///         Ok(Secret(buf))
2037    ///     }
2038    /// }
2039    ///
2040    /// let mut de = serde_json::Deserializer::from_str(r#""AP-A""#);
2041    /// let secret = de.deserialize_str(SecretVisitor).unwrap();
2042    /// assert_eq!(secret.0, [0, 255, 128]);
2043    /// ```
2044    ///
2045    /// # Errors
2046    ///
2047    /// Returns an error built with [`serde::de::Error::custom`] whose message
2048    /// is fixed and never quotes a symbol or an offset from `text`:
2049    ///
2050    /// - `"base64 output buffer too small"` when `out` cannot hold the
2051    ///   decoded bytes. The size is checked before the symbols, so this
2052    ///   error also hides invalid input.
2053    /// - `"invalid base64"` when `text` is not valid base64.
2054    ///
2055    /// On error, `out` may hold part of the decoded bytes.
2056    pub fn decode_into<E: serde::de::Error>(text: &str, out: &mut [u8]) -> Result<usize, E> {
2057        super::lenient_engine(text)
2058            .decode_slice(text, out)
2059            .map_err(|error| {
2060                E::custom(match error {
2061                    base64::DecodeSliceError::OutputSliceTooSmall => {
2062                        Base64ErrorReason::BufferTooSmall
2063                    }
2064                    base64::DecodeSliceError::DecodeError(_) => Base64ErrorReason::Invalid,
2065                })
2066            })
2067    }
2068
2069    /// Fixed reasons for a [`decode_into`] failure, so the error never
2070    /// carries part of the input.
2071    #[derive(Debug, thiserror::Error)]
2072    enum Base64ErrorReason {
2073        #[error("invalid base64")]
2074        Invalid,
2075        #[error("base64 output buffer too small")]
2076        BufferTooSmall,
2077    }
2078
2079    /// Deserialize from a base64-encoded string (or JSON `null` → empty).
2080    ///
2081    /// The bytes are decoded once into a `Vec<u8>` sized from the base64
2082    /// length, which `T::from` then takes ownership of. Use [`decode_into`]
2083    /// to decode into storage the caller provides instead.
2084    ///
2085    /// Generic over the return type so that codegen's `use_bytes_type()`
2086    /// (which types the field as `bytes::Bytes`) works without a shim:
2087    /// the visitor produces `Vec<u8>`, the final `.into()` converts.
2088    /// `Vec<u8>: From<Vec<u8>>` (identity) keeps the default path zero-cost.
2089    /// Type inference picks `T` from the field type at the serde call site.
2090    pub fn deserialize<'de, T, D>(d: D) -> Result<T, D::Error>
2091    where
2092        T: From<alloc::vec::Vec<u8>>,
2093        D: Deserializer<'de>,
2094    {
2095        struct V;
2096        impl<'de> serde::de::Visitor<'de> for V {
2097            type Value = alloc::vec::Vec<u8>;
2098
2099            fn visit_unit<E>(self) -> Result<alloc::vec::Vec<u8>, E> {
2100                Ok(alloc::vec::Vec::new())
2101            }
2102
2103            fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2104                f.write_str("a base64-encoded string, or null")
2105            }
2106
2107            fn visit_bool<E: serde::de::Error>(self, _: bool) -> Result<alloc::vec::Vec<u8>, E> {
2108                Err(E::custom(super::JsonValueError::Base64))
2109            }
2110
2111            fn visit_i64<E: serde::de::Error>(self, _: i64) -> Result<alloc::vec::Vec<u8>, E> {
2112                Err(E::custom(super::JsonValueError::Base64))
2113            }
2114
2115            fn visit_u64<E: serde::de::Error>(self, _: u64) -> Result<alloc::vec::Vec<u8>, E> {
2116                Err(E::custom(super::JsonValueError::Base64))
2117            }
2118
2119            fn visit_f64<E: serde::de::Error>(self, _: f64) -> Result<alloc::vec::Vec<u8>, E> {
2120                Err(E::custom(super::JsonValueError::Base64))
2121            }
2122
2123            visit_wide_ints!(super::JsonValueError::Base64);
2124            crate::reject_other_json_kinds!(bytes, byte_buf);
2125
2126            fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<alloc::vec::Vec<u8>, E> {
2127                super::decode_base64(v).map_err(serde::de::Error::custom)
2128            }
2129        }
2130        // Use deserialize_any (not deserialize_str) so null reaches visit_unit.
2131        d.deserialize_any(V).map(T::from)
2132    }
2133}
2134
2135// ── ProtoElemJson primitive impls ────────────────────────────────────────────
2136//
2137// Delegates to the singular `with` modules above. This is the complete set
2138// of proto scalar types that can appear as repeated elements or map values.
2139
2140proto_elem_json_delegate!(i32, int32);
2141proto_elem_json_delegate!(u32, uint32);
2142proto_elem_json_delegate!(i64, int64);
2143proto_elem_json_delegate!(u64, uint64);
2144proto_elem_json_delegate!(f32, float);
2145proto_elem_json_delegate!(f64, double);
2146proto_elem_json_delegate!(bool, proto_bool, null = "a boolean");
2147proto_elem_json_delegate!(alloc::string::String, proto_string, null = "a string");
2148proto_elem_json_delegate!(alloc::vec::Vec<u8>, bytes);
2149
2150// Only an unlisted custom `bytes` element used in a `repeated` / `map` field
2151// gets a codegen-emitted `ProtoElemJson` impl (forwarding to the `bytes`
2152// base64 with-module) into the generating crate, where the type is local. A
2153// type listed with `json_policy_type` does not: the policy with-modules wrap
2154// it in their own element adapter. An unlisted custom `string` element does
2155// not either: `repeated_serde_module` returns `None` for `TYPE_STRING`, so a
2156// repeated string serializes through the element's own native
2157// `Serialize`/`Deserialize` rather than `proto_seq`/`ProtoElemJson`.
2158
2159// bytes::Bytes — for codegen's `use_bytes_type()` with `repeated bytes`.
2160// Serialize: `Bytes: Deref<Target=[u8]>` → `bytes::serialize(&[u8], s)`.
2161// Deserialize: `bytes::deserialize` is generic over `T: From<Vec<u8>>`;
2162// `Bytes::from(Vec<u8>)` takes ownership of the buffer (zero-copy).
2163//
2164// Not using the macro because `bytes::serialize(v, s)` needs `v: &[u8]`
2165// but `ProtoElemJson::serialize_proto_json` gets `v: &Self = &Bytes`.
2166// Deref coercion handles it, but being explicit avoids confusion.
2167impl ProtoElemJson for ::bytes::Bytes {
2168    fn serialize_proto_json<S: serde::Serializer>(v: &Self, s: S) -> Result<S::Ok, S::Error> {
2169        bytes::serialize(v, s)
2170    }
2171    fn deserialize_proto_json<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
2172        bytes::deserialize(d)
2173    }
2174}
2175
2176// EnumValue<E> (open enums) — uses its own Serialize/Deserialize (which
2177// handle proto JSON enum semantics: name string on serialize, accept name
2178// or integer on deserialize, preserve unknown values as the int).
2179impl<E: crate::Enumeration> ProtoElemJson for crate::EnumValue<E>
2180where
2181    Self: serde::Serialize + serde::de::DeserializeOwned,
2182{
2183    fn serialize_proto_json<S: serde::Serializer>(v: &Self, s: S) -> Result<S::Ok, S::Error> {
2184        serde::Serialize::serialize(v, s)
2185    }
2186    fn deserialize_proto_json<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
2187        <Self as serde::Deserialize>::deserialize(d)
2188    }
2189}
2190
2191/// Serde with-module for `map<string, ...>` fields where the key's
2192/// `utf8_validation = NONE` produced `Vec<u8>` keys under strict mapping.
2193///
2194/// Keys are serialized/deserialized as base64 strings (same as bytes values).
2195/// Values use [`ProtoElemJson`] so container-specific ProtoJSON rules apply and
2196/// `null` values are rejected.
2197///
2198/// Use with `#[serde(with = "::buffa::json_helpers::bytes_key_map")]`.
2199pub mod bytes_key_map {
2200    use super::{ProtoElemJson, ProtoElemSeed, ProtoJson};
2201    use crate::map_codec::MapStorage;
2202    use serde::{Deserializer, Serializer};
2203
2204    pub fn serialize<C, S>(value: &C, s: S) -> Result<S::Ok, S::Error>
2205    where
2206        C: MapStorage<Key = alloc::vec::Vec<u8>>,
2207        C::Value: ProtoElemJson,
2208        S: Serializer,
2209    {
2210        use serde::ser::SerializeMap;
2211        let mut map = s.serialize_map(Some(value.storage_len()))?;
2212        for (k, v) in value.storage_iter() {
2213            map.serialize_entry(&super::Base64Wrapper(k), &ProtoJson(v))?;
2214        }
2215        map.end()
2216    }
2217
2218    pub fn deserialize<'de, C, D>(d: D) -> Result<C, D::Error>
2219    where
2220        C: MapStorage<Key = alloc::vec::Vec<u8>> + Default,
2221        C::Value: ProtoElemJson,
2222        D: Deserializer<'de>,
2223    {
2224        struct Vis<C>(core::marker::PhantomData<C>);
2225        impl<'de, C> serde::de::Visitor<'de> for Vis<C>
2226        where
2227            C: MapStorage<Key = alloc::vec::Vec<u8>> + Default,
2228            C::Value: ProtoElemJson,
2229        {
2230            type Value = C;
2231            fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2232                f.write_str("a map with base64-encoded keys, or null")
2233            }
2234            fn visit_unit<E>(self) -> Result<Self::Value, E> {
2235                Ok(C::default())
2236            }
2237            crate::reject_other_json_kinds!(
2238                bool, i64, u64, i128, u128, f64, str, string, bytes, byte_buf
2239            );
2240            fn visit_map<A: serde::de::MapAccess<'de>>(
2241                self,
2242                mut map: A,
2243            ) -> Result<Self::Value, A::Error> {
2244                let mut out = C::default();
2245                while let Some(key_str) = map.next_key::<alloc::string::String>()? {
2246                    #[cfg(feature = "zeroize")]
2247                    let key_str = zeroize::Zeroizing::new(key_str);
2248                    let k = super::decode_base64(&key_str).map_err(serde::de::Error::custom)?;
2249                    let k = crate::erasing::Erasing::new(k, C::storage_erase_key);
2250                    let v =
2251                        map.next_value_seed(ProtoElemSeed::<C::Value>(core::marker::PhantomData))?;
2252                    out.storage_insert(k.into_inner(), v);
2253                }
2254                Ok(out)
2255            }
2256        }
2257        d.deserialize_any(Vis::<C>(core::marker::PhantomData))
2258    }
2259}
2260
2261/// Serde with-module for `HashMap<Vec<u8>, Vec<u8>>` — both key and value
2262/// base64-encoded. This covers `map<string, string>` with `utf8_validation
2263/// = NONE` under strict mapping (both key and value normalized to bytes),
2264/// and `map<string, bytes>` with NONE on the key.
2265///
2266/// Use with `#[serde(with = "::buffa::json_helpers::bytes_key_bytes_val_map")]`.
2267pub mod bytes_key_bytes_val_map {
2268    use crate::map_codec::MapStorage;
2269    use serde::{Deserializer, Serializer};
2270
2271    pub fn serialize<C, S>(value: &C, s: S) -> Result<S::Ok, S::Error>
2272    where
2273        C: MapStorage<Key = alloc::vec::Vec<u8>, Value = alloc::vec::Vec<u8>>,
2274        S: Serializer,
2275    {
2276        use serde::ser::SerializeMap;
2277        let mut map = s.serialize_map(Some(value.storage_len()))?;
2278        for (k, v) in value.storage_iter() {
2279            map.serialize_entry(&super::Base64Wrapper(k), &super::Base64Wrapper(v))?;
2280        }
2281        map.end()
2282    }
2283
2284    pub fn deserialize<'de, C, D>(d: D) -> Result<C, D::Error>
2285    where
2286        C: MapStorage<Key = alloc::vec::Vec<u8>, Value = alloc::vec::Vec<u8>> + Default,
2287        D: Deserializer<'de>,
2288    {
2289        struct V<C>(core::marker::PhantomData<C>);
2290        impl<'de, C> serde::de::Visitor<'de> for V<C>
2291        where
2292            C: MapStorage<Key = alloc::vec::Vec<u8>, Value = alloc::vec::Vec<u8>> + Default,
2293        {
2294            type Value = C;
2295            fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2296                f.write_str("a map with base64-encoded keys and values, or null")
2297            }
2298            fn visit_unit<E>(self) -> Result<Self::Value, E> {
2299                Ok(C::default())
2300            }
2301            crate::reject_other_json_kinds!(
2302                bool, i64, u64, i128, u128, f64, str, string, bytes, byte_buf
2303            );
2304            fn visit_map<A: serde::de::MapAccess<'de>>(
2305                self,
2306                mut map: A,
2307            ) -> Result<Self::Value, A::Error> {
2308                let mut out = C::default();
2309                while let Some(ks) = map.next_key::<alloc::string::String>()? {
2310                    #[cfg(feature = "zeroize")]
2311                    let ks = zeroize::Zeroizing::new(ks);
2312                    let k = super::decode_base64(&ks).map_err(serde::de::Error::custom)?;
2313                    let k = crate::erasing::Erasing::new(k, C::storage_erase_key);
2314                    let vs = map.next_value::<alloc::string::String>()?;
2315                    #[cfg(feature = "zeroize")]
2316                    let vs = zeroize::Zeroizing::new(vs);
2317                    let v = super::decode_base64(&vs).map_err(serde::de::Error::custom)?;
2318                    out.storage_insert(k.into_inner(), v);
2319                }
2320                Ok(out)
2321            }
2322        }
2323        d.deserialize_any(V::<C>(core::marker::PhantomData))
2324    }
2325}
2326
2327// ── string_key_map: non-string keys stringified, any MapStorage container ────
2328
2329/// Serde with-module for map fields with non-string key types (int32, int64,
2330/// uint32, uint64, bool, etc.).
2331///
2332/// In proto3 JSON, all map keys are strings.  For non-string key types, the
2333/// key string is parsed using `FromStr` during deserialization and formatted
2334/// directly into the serializer during serialization.
2335///
2336/// Use with `#[serde(with = "::buffa::json_helpers::string_key_map")]`.
2337pub mod string_key_map {
2338    use crate::map_codec::MapStorage;
2339    use core::fmt::Display;
2340    use core::str::FromStr;
2341    use serde::{Deserializer, Serializer};
2342
2343    pub fn serialize<C, S>(value: &C, s: S) -> Result<S::Ok, S::Error>
2344    where
2345        C: MapStorage,
2346        C::Key: Display,
2347        C::Value: serde::Serialize,
2348        S: Serializer,
2349    {
2350        use serde::ser::SerializeMap;
2351        let mut map = s.serialize_map(Some(value.storage_len()))?;
2352        for (k, v) in value.storage_iter() {
2353            map.serialize_entry(&super::DisplayKey(k), v)?;
2354        }
2355        map.end()
2356    }
2357
2358    pub fn deserialize<'de, C, D>(d: D) -> Result<C, D::Error>
2359    where
2360        C: MapStorage + Default,
2361        C::Key: FromStr,
2362        C::Value: serde::Deserialize<'de>,
2363        D: Deserializer<'de>,
2364    {
2365        struct MapVisitor<C>(core::marker::PhantomData<C>);
2366        impl<'de, C> serde::de::Visitor<'de> for MapVisitor<C>
2367        where
2368            C: MapStorage + Default,
2369            C::Key: FromStr,
2370            C::Value: serde::Deserialize<'de>,
2371        {
2372            type Value = C;
2373            fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2374                f.write_str("a JSON object with string keys, or null")
2375            }
2376            fn visit_unit<E>(self) -> Result<Self::Value, E> {
2377                Ok(C::default())
2378            }
2379            crate::reject_other_json_kinds!(
2380                bool, i64, u64, i128, u128, f64, str, string, bytes, byte_buf
2381            );
2382            fn visit_map<A: serde::de::MapAccess<'de>>(
2383                self,
2384                mut map: A,
2385            ) -> Result<Self::Value, A::Error> {
2386                let mut out = C::default();
2387                while let Some(key_str) = map.next_key::<alloc::string::String>()? {
2388                    let key = key_str
2389                        .parse::<C::Key>()
2390                        .map_err(|_| serde::de::Error::custom(super::JsonValueError::MapKey))?;
2391                    let key = crate::erasing::Erasing::new(key, C::storage_erase_key);
2392                    let value = map.next_value()?;
2393                    out.storage_insert(key.into_inner(), value);
2394                }
2395                Ok(out)
2396            }
2397        }
2398        d.deserialize_any(MapVisitor::<C>(core::marker::PhantomData))
2399    }
2400}
2401
2402/// Newtype for serializing `&[u8]` as base64 without a separate `with` module.
2403struct Base64Wrapper<'a>(&'a [u8]);
2404
2405impl serde::Serialize for Base64Wrapper<'_> {
2406    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
2407        bytes::serialize(self.0, s)
2408    }
2409}
2410
2411/// The lenient engine for `v`'s alphabet.
2412///
2413/// `-` and `_` occur only in the URL-safe alphabet, and `+` and `/` only in
2414/// the standard one; the other symbols decode to the same values in both, and
2415/// both engines share one padding and trailing-bit configuration. The first of
2416/// these four symbols therefore decides: an input that mixes the alphabets
2417/// fails under either engine. Choosing this way accepts exactly the inputs
2418/// that "standard, else URL-safe" accepts, with the same output, while
2419/// decoding only once and usually scanning only a short prefix.
2420fn lenient_engine(v: &str) -> &'static GeneralPurpose {
2421    match v.bytes().find(|b| matches!(b, b'+' | b'/' | b'-' | b'_')) {
2422        Some(b'-' | b'_') => &URL_SAFE_LENIENT,
2423        _ => &STANDARD_LENIENT,
2424    }
2425}
2426
2427/// Decode a base64 string, accepting standard and URL-safe alphabets with
2428/// lenient trailing-bit and padding handling.
2429pub(crate) fn decode_base64(v: &str) -> Result<alloc::vec::Vec<u8>, JsonValueError> {
2430    use base64::Engine as _;
2431    lenient_engine(v)
2432        .decode(v)
2433        .map_err(|_| JsonValueError::Base64)
2434}
2435
2436// ── Option<T> wrappers for proto2 optional scalar fields ─────────────────────
2437//
2438// serde's `#[serde(with = "...")]` on an `Option<T>` field needs the module
2439// to handle `&Option<T>` / `Option<T>`.  These thin wrappers delegate to the
2440// inner module for `Some` and pass through `None` transparently.
2441
2442macro_rules! opt_serde_module {
2443    ($(#[$attr:meta])* $mod_name:ident, $inner:ident, $ty:ty) => {
2444        $(#[$attr])*
2445        pub mod $mod_name {
2446            use serde::{Deserializer, Serializer};
2447
2448            pub fn serialize<S: Serializer>(value: &Option<$ty>, s: S) -> Result<S::Ok, S::Error> {
2449                match value {
2450                    Some(v) => super::$inner::serialize(v, s),
2451                    None => s.serialize_none(),
2452                }
2453            }
2454
2455            pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<$ty>, D::Error> {
2456                // null → None (unset), not Some(default). Non-null values go
2457                // to the inner module's deserializer.
2458                serde::de::DeserializeSeed::deserialize(super::NullableDeserializeSeed(Inner), d)
2459            }
2460
2461            /// Seed that deserializes via the inner module.
2462            struct Inner;
2463
2464            impl<'de> serde::de::DeserializeSeed<'de> for Inner {
2465                type Value = $ty;
2466                fn deserialize<D: Deserializer<'de>>(self, d: D) -> Result<$ty, D::Error> {
2467                    super::$inner::deserialize(d)
2468                }
2469            }
2470        }
2471    };
2472}
2473
2474opt_serde_module!(opt_int32, int32, i32);
2475opt_serde_module!(opt_uint32, uint32, u32);
2476opt_serde_module!(opt_int64, int64, i64);
2477opt_serde_module!(opt_uint64, uint64, u64);
2478opt_serde_module!(opt_float, float, f32);
2479opt_serde_module!(opt_double, double, f64);
2480/// Option wrapper for bool fields with explicit presence.
2481/// Pair it with `#[serde(default)]` so an omitted field remains `None`.
2482/// Non-human-readable formats retain native Option encoding.
2483pub mod opt_bool {
2484    /// Serialize the optional bool using the carrier's existing representation.
2485    ///
2486    /// # Errors
2487    /// Returns the serializer's error if writing fails.
2488    pub fn serialize<S: serde::Serializer>(value: &Option<bool>, s: S) -> Result<S::Ok, S::Error> {
2489        if s.is_human_readable() {
2490            match value {
2491                Some(value) => super::proto_bool::serialize(value, s),
2492                None => s.serialize_none(),
2493            }
2494        } else {
2495            serde::Serialize::serialize(value, s)
2496        }
2497    }
2498    /// Deserialize an optional bool, preserving null as absence.
2499    ///
2500    /// # Errors
2501    /// Returns the deserializer's error for invalid input or source failure.
2502    pub fn deserialize<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<bool>, D::Error> {
2503        if !d.is_human_readable() {
2504            return serde::Deserialize::deserialize(d);
2505        }
2506        struct Inner;
2507        impl<'de> serde::de::DeserializeSeed<'de> for Inner {
2508            type Value = bool;
2509            fn deserialize<D: serde::Deserializer<'de>>(self, d: D) -> Result<bool, D::Error> {
2510                super::proto_bool::deserialize(d)
2511            }
2512        }
2513        serde::de::DeserializeSeed::deserialize(super::NullableDeserializeSeed(Inner), d)
2514    }
2515}
2516
2517/// Option wrapper for `string` fields with explicit presence.
2518///
2519/// Generic over the string type, like
2520/// [`proto_string`]: `Option<String>` and
2521/// any configured [`ProtoString`](crate::ProtoString) work. JSON `null`
2522/// deserializes to `None`; other values go through `proto_string`. As with
2523/// any `with` module on an `Option`, add `#[serde(default)]` so a missing key
2524/// is `None`. Non-human-readable formats keep native `Option<String>`
2525/// encoding. Generated non-default string representations retain their own
2526/// Serde implementation rather than selecting this helper.
2527pub mod opt_string {
2528    use serde::{Deserializer, Serializer};
2529
2530    /// Serialize an optional `string` field.
2531    pub fn serialize<T, S>(value: &Option<T>, s: S) -> Result<S::Ok, S::Error>
2532    where
2533        T: AsRef<str>,
2534        S: Serializer,
2535    {
2536        match value {
2537            Some(v) if s.is_human_readable() => super::proto_string::serialize(v.as_ref(), s),
2538            Some(v) => s.serialize_some(v.as_ref()),
2539            None => s.serialize_none(),
2540        }
2541    }
2542
2543    /// Deserialize an optional `string` field (JSON `null` → `None`).
2544    ///
2545    /// # Errors
2546    ///
2547    /// Returns the deserializer's `invalid_type` error, which names the JSON
2548    /// kind but not the value, for any input that is not a string or `null`.
2549    pub fn deserialize<'de, T, D>(d: D) -> Result<Option<T>, D::Error>
2550    where
2551        T: crate::ProtoString,
2552        D: Deserializer<'de>,
2553    {
2554        if !d.is_human_readable() {
2555            return <Option<alloc::string::String> as serde::Deserialize>::deserialize(d)
2556                .map(|value| value.map(T::from));
2557        }
2558        struct Inner<T>(core::marker::PhantomData<T>);
2559        impl<'de, T: crate::ProtoString> serde::de::DeserializeSeed<'de> for Inner<T> {
2560            type Value = T;
2561            fn deserialize<D2: Deserializer<'de>>(self, d: D2) -> Result<T, D2::Error> {
2562                super::proto_string::deserialize(d)
2563            }
2564        }
2565        serde::de::DeserializeSeed::deserialize(
2566            super::NullableDeserializeSeed(Inner(core::marker::PhantomData)),
2567            d,
2568        )
2569    }
2570}
2571
2572/// Option wrapper for bytes fields (base64 encoding).
2573///
2574/// Generic over the inner type so both `Option<Vec<u8>>` (default) and
2575/// `Option<bytes::Bytes>` (codegen's `use_bytes_type()`) work. The
2576/// `AsRef<[u8]>` bound on serialize and `From<Vec<u8>>` on deserialize are
2577/// satisfied by both. `bytes::serialize` takes `&[u8]`, so we can't use
2578/// the `opt_*` macro — `&Option<T>` → `&[u8]` needs explicit unwrap.
2579pub mod opt_bytes {
2580    use serde::{Deserializer, Serializer};
2581
2582    pub fn serialize<T, S>(value: &Option<T>, s: S) -> Result<S::Ok, S::Error>
2583    where
2584        T: AsRef<[u8]>,
2585        S: Serializer,
2586    {
2587        match value {
2588            Some(v) => super::bytes::serialize(v.as_ref(), s),
2589            None => s.serialize_none(),
2590        }
2591    }
2592
2593    pub fn deserialize<'de, T, D>(d: D) -> Result<Option<T>, D::Error>
2594    where
2595        T: From<alloc::vec::Vec<u8>>,
2596        D: Deserializer<'de>,
2597    {
2598        // null → None (unset), non-null → delegate to bytes module.
2599        // The visitor stays Vec<u8>-typed; convert on the way out.
2600        struct Inner;
2601        impl<'de> serde::de::DeserializeSeed<'de> for Inner {
2602            type Value = alloc::vec::Vec<u8>;
2603            fn deserialize<D2: Deserializer<'de>>(
2604                self,
2605                d: D2,
2606            ) -> Result<alloc::vec::Vec<u8>, D2::Error> {
2607                super::bytes::deserialize(d)
2608            }
2609        }
2610        serde::de::DeserializeSeed::deserialize(super::NullableDeserializeSeed(Inner), d)
2611            .map(|opt| opt.map(T::from))
2612    }
2613}
2614
2615// ── opt_enum: Option<EnumValue<E>> with unknown-value → None ─────────────────
2616
2617/// Serde with-module for `Option<EnumValue<E>>` optional enum fields (proto2).
2618///
2619/// When `ignore_unknown_enum_values` is active, unknown enum string values
2620/// produce `None` (field not set) instead of `Some(default)`. In default
2621/// mode unknown strings produce an error.
2622pub mod opt_enum {
2623    use serde::{Deserializer, Serializer};
2624
2625    pub fn serialize<E: crate::Enumeration, S: Serializer>(
2626        value: &Option<crate::EnumValue<E>>,
2627        s: S,
2628    ) -> Result<S::Ok, S::Error> {
2629        match value {
2630            Some(v) => serde::Serialize::serialize(v, s),
2631            None => s.serialize_none(),
2632        }
2633    }
2634
2635    pub fn deserialize<'de, E: crate::Enumeration, D: Deserializer<'de>>(
2636        d: D,
2637    ) -> Result<Option<crate::EnumValue<E>>, D::Error> {
2638        // First, deserialize the raw value. null → None immediately.
2639        let raw: Option<super::BufferedValue> = serde::Deserialize::deserialize(d)?;
2640        let raw = match raw {
2641            Some(super::BufferedValue(v)) => v,
2642            None => return Ok(None),
2643        };
2644
2645        super::try_deserialize_enum::<crate::EnumValue<E>>(raw).map_err(serde::de::Error::custom)
2646    }
2647}
2648
2649// ── NullableDeserializeSeed ───────────────────────────────────────────────────
2650
2651/// `DeserializeSeed` that detects JSON null and returns `None` instead of
2652/// delegating to the inner seed. Used by generated oneof deserializers so
2653/// that `null` means "this variant is not set", and by the `opt_*` modules so
2654/// that `null` means "this field is not set".
2655pub struct NullableDeserializeSeed<S>(pub S);
2656
2657impl<'de, S> serde::de::DeserializeSeed<'de> for NullableDeserializeSeed<S>
2658where
2659    S: serde::de::DeserializeSeed<'de>,
2660{
2661    type Value = Option<S::Value>;
2662
2663    fn deserialize<D: serde::Deserializer<'de>>(self, d: D) -> Result<Self::Value, D::Error> {
2664        d.deserialize_option(NullableVisitor(self.0))
2665    }
2666}
2667
2668struct NullableVisitor<S>(S);
2669
2670impl<'de, S> serde::de::Visitor<'de> for NullableVisitor<S>
2671where
2672    S: serde::de::DeserializeSeed<'de>,
2673{
2674    type Value = Option<S::Value>;
2675
2676    fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2677        f.write_str("a value or null")
2678    }
2679
2680    fn visit_none<E>(self) -> Result<Self::Value, E> {
2681        Ok(None)
2682    }
2683
2684    crate::reject_other_json_kinds!(bool, i64, u64, i128, u128, f64, str, string, bytes, byte_buf);
2685
2686    fn visit_unit<E>(self) -> Result<Self::Value, E> {
2687        Ok(None)
2688    }
2689
2690    fn visit_some<D: serde::Deserializer<'de>>(self, d: D) -> Result<Self::Value, D::Error> {
2691        self.0.deserialize(d).map(Some)
2692    }
2693}
2694
2695// ── DefaultDeserializeSeed ───────────────────────────────────────────────────
2696
2697/// `DeserializeSeed` that delegates to the type's standard `Deserialize` impl.
2698/// Pairs with `NullableDeserializeSeed` for oneof variants that don't
2699/// need a custom serde helper.
2700pub struct DefaultDeserializeSeed<T>(core::marker::PhantomData<T>);
2701
2702impl<T> DefaultDeserializeSeed<T> {
2703    pub fn new() -> Self {
2704        Self(core::marker::PhantomData)
2705    }
2706}
2707
2708impl<T> Default for DefaultDeserializeSeed<T> {
2709    fn default() -> Self {
2710        Self::new()
2711    }
2712}
2713
2714impl<'de, T: serde::Deserialize<'de>> serde::de::DeserializeSeed<'de>
2715    for DefaultDeserializeSeed<T>
2716{
2717    type Value = T;
2718    fn deserialize<D: serde::Deserializer<'de>>(self, d: D) -> Result<T, D::Error> {
2719        T::deserialize(d)
2720    }
2721}
2722
2723// ── message_field_always_present ──────────────────────────────────────────────
2724
2725/// Deserialize a `MessageField<T>` by always forwarding to `T::deserialize`,
2726/// including for JSON `null`.
2727///
2728/// Normally, `MessageField<T>::deserialize` delegates to `Option<T>`, which
2729/// maps `null` → `None` (field absent). For types like `google.protobuf.Value`
2730/// where `null` is a valid value (`NullValue`), this function ensures `null`
2731/// reaches `T::deserialize` and the field is set rather than absent.
2732pub fn message_field_always_present<'de, T, P, D>(
2733    d: D,
2734) -> Result<crate::MessageField<T, P>, D::Error>
2735where
2736    T: Default + serde::Deserialize<'de>,
2737    P: crate::ProtoBox<T>,
2738    D: serde::Deserializer<'de>,
2739{
2740    T::deserialize(d).map(crate::MessageField::some)
2741}
2742
2743// ── EnumProtoNameRef ──────────────────────────────────────────────────────────
2744
2745/// Helper to serialize a `&E` by its proto name string.
2746///
2747/// Used by `repeated_closed_enum` and `map_closed_enum` serialize functions
2748/// where elements need proto JSON encoding (name string, not integer).
2749pub(crate) struct EnumProtoNameRef<'a, E: crate::Enumeration>(pub &'a E);
2750
2751impl<E: crate::Enumeration> serde::Serialize for EnumProtoNameRef<'_, E> {
2752    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
2753        s.serialize_str(self.0.proto_name())
2754    }
2755}
2756
2757// ── skip_if ───────────────────────────────────────────────────────────────────
2758
2759/// Predicates for `#[serde(skip_serializing_if = "...")]` on implicit-presence
2760/// fields.
2761///
2762/// Proto3 JSON omits such a field at its protobuf default. Generated
2763/// `Serialize` impls attach these to the matching field types.
2764pub mod skip_if {
2765    pub fn is_zero_i32(v: &i32) -> bool {
2766        *v == 0
2767    }
2768    pub fn is_zero_i64(v: &i64) -> bool {
2769        *v == 0
2770    }
2771    pub fn is_zero_u32(v: &u32) -> bool {
2772        *v == 0
2773    }
2774    pub fn is_zero_u64(v: &u64) -> bool {
2775        *v == 0
2776    }
2777    pub fn is_false(v: &bool) -> bool {
2778        !*v
2779    }
2780    /// Returns `true` only for `+0.0` (all bits clear). Returns `false` for
2781    /// `-0.0` and NaN, so both are serialized. Differs from `*v == 0.0`, which
2782    /// is also `true` for `-0.0`.
2783    pub fn is_zero_f32(v: &f32) -> bool {
2784        v.to_bits() == 0
2785    }
2786    /// Returns `true` only for `+0.0` (all bits clear), and `false` for `-0.0`
2787    /// and NaN.
2788    pub fn is_zero_f64(v: &f64) -> bool {
2789        v.to_bits() == 0
2790    }
2791    pub fn is_empty_str(v: &str) -> bool {
2792        v.is_empty()
2793    }
2794    pub fn is_empty_bytes(v: &[u8]) -> bool {
2795        v.is_empty()
2796    }
2797    pub fn is_empty_vec<T>(v: &[T]) -> bool {
2798        v.is_empty()
2799    }
2800    /// Empty-check for a non-default map collection (`BTreeMap` or a custom
2801    /// map) via the [`MapStorage`](crate::map_codec::MapStorage) surface, so the
2802    /// `skip_serializing_if` predicate works regardless of the concrete map
2803    /// type. The default `HashMap` map fields keep `HashMap::is_empty`, so their
2804    /// generated output is unchanged.
2805    pub fn is_empty_map<C>(m: &C) -> bool
2806    where
2807        C: crate::map_codec::MapStorage,
2808    {
2809        m.storage_len() == 0
2810    }
2811    pub fn is_unset_message_field<T: Default, P: crate::ProtoBox<T>>(
2812        v: &crate::MessageField<T, P>,
2813    ) -> bool {
2814        v.is_unset()
2815    }
2816    pub fn is_default_enum_value<E: crate::Enumeration>(v: &crate::EnumValue<E>) -> bool {
2817        v.to_i32() == 0
2818    }
2819    pub fn is_default_closed_enum<E: crate::Enumeration>(v: &E) -> bool {
2820        v.to_i32() == 0
2821    }
2822}
2823
2824// ── closed_enum: bare E with proto JSON handling ─────────────────────────────
2825
2826/// Serde with-module for singular closed enum fields (bare `E`).
2827///
2828/// Accepts JSON `null` as `E::default()`, string via `from_proto_name`,
2829/// and integer via `from_i32`. When `ignore_unknown_enum_values` is active,
2830/// unknown string values produce `E::default()` instead of an error.
2831pub mod closed_enum {
2832    use super::EnumJsonErrorReason;
2833    use serde::{Deserializer, Serializer};
2834
2835    pub fn serialize<E: crate::Enumeration, S: Serializer>(
2836        value: &E,
2837        s: S,
2838    ) -> Result<S::Ok, S::Error> {
2839        s.serialize_str(value.proto_name())
2840    }
2841
2842    pub fn deserialize<'de, E: crate::Enumeration + Default, D: Deserializer<'de>>(
2843        d: D,
2844    ) -> Result<E, D::Error> {
2845        deserialize_with_unknown_names(d, true)
2846    }
2847
2848    /// Standalone enum values always reject unknown names, even in lenient mode.
2849    #[doc(hidden)]
2850    pub fn deserialize_strict<'de, E: crate::Enumeration + Default, D: Deserializer<'de>>(
2851        d: D,
2852    ) -> Result<E, D::Error> {
2853        deserialize_with_unknown_names(d, false)
2854    }
2855
2856    fn deserialize_with_unknown_names<
2857        'de,
2858        E: crate::Enumeration + Default,
2859        D: Deserializer<'de>,
2860    >(
2861        d: D,
2862        allow_lenient: bool,
2863    ) -> Result<E, D::Error> {
2864        struct V<E> {
2865            allow_lenient: bool,
2866            marker: core::marker::PhantomData<E>,
2867        }
2868        impl<'de, E: crate::Enumeration + Default> serde::de::Visitor<'de> for V<E> {
2869            type Value = E;
2870            fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2871                f.write_str("a protobuf enum name string, integer value, or null")
2872            }
2873            fn visit_unit<Err>(self) -> Result<E, Err> {
2874                Ok(E::default())
2875            }
2876            fn visit_i64<Err: serde::de::Error>(self, v: i64) -> Result<E, Err> {
2877                let v32 =
2878                    i32::try_from(v).map_err(|_| Err::custom(EnumJsonErrorReason::OutOfRange))?;
2879                E::from_i32(v32).ok_or_else(|| Err::custom(EnumJsonErrorReason::UnknownNumber))
2880            }
2881            fn visit_u64<Err: serde::de::Error>(self, v: u64) -> Result<E, Err> {
2882                let v32 =
2883                    i32::try_from(v).map_err(|_| Err::custom(EnumJsonErrorReason::OutOfRange))?;
2884                E::from_i32(v32).ok_or_else(|| Err::custom(EnumJsonErrorReason::UnknownNumber))
2885            }
2886            // Formats that deliver 128-bit integers (YAML, for one) take the
2887            // 64-bit path; serde's defaults would echo the number.
2888            fn visit_i128<Err: serde::de::Error>(self, v: i128) -> Result<E, Err> {
2889                let v =
2890                    i64::try_from(v).map_err(|_| Err::custom(EnumJsonErrorReason::OutOfRange))?;
2891                self.visit_i64(v)
2892            }
2893            fn visit_u128<Err: serde::de::Error>(self, v: u128) -> Result<E, Err> {
2894                let v =
2895                    u64::try_from(v).map_err(|_| Err::custom(EnumJsonErrorReason::OutOfRange))?;
2896                self.visit_u64(v)
2897            }
2898            fn visit_f64<Err: serde::de::Error>(self, _: f64) -> Result<E, Err> {
2899                Err(Err::custom(EnumJsonErrorReason::InvalidType))
2900            }
2901            fn visit_bool<Err: serde::de::Error>(self, _: bool) -> Result<E, Err> {
2902                Err(Err::custom(EnumJsonErrorReason::InvalidType))
2903            }
2904            #[cfg(feature = "zeroize")]
2905            fn visit_string<Err: serde::de::Error>(
2906                self,
2907                value: alloc::string::String,
2908            ) -> Result<E, Err> {
2909                // Only the owned-token callback transfers the allocation.
2910                // Borrowed text and parser scratch stay with the deserializer.
2911                let value = zeroize::Zeroizing::new(value);
2912                self.visit_str(&value)
2913            }
2914            #[cfg(feature = "zeroize")]
2915            fn visit_byte_buf<Err: serde::de::Error>(
2916                self,
2917                value: alloc::vec::Vec<u8>,
2918            ) -> Result<Self::Value, Err> {
2919                // Preserve Serde's borrowed-byte rejection while wiping the
2920                // owned allocation that its default forwarding would release.
2921                let value = zeroize::Zeroizing::new(value);
2922                self.visit_bytes(&value)
2923            }
2924            fn visit_str<Err: serde::de::Error>(self, v: &str) -> Result<E, Err> {
2925                match E::from_proto_name(v) {
2926                    Some(e) => Ok(e),
2927                    None => {
2928                        if self.allow_lenient && crate::json::ignore_unknown_enum_values() {
2929                            return Ok(E::default());
2930                        }
2931                        Err(Err::custom(EnumJsonErrorReason::UnknownName))
2932                    }
2933                }
2934            }
2935        }
2936        d.deserialize_any(V {
2937            allow_lenient,
2938            marker: core::marker::PhantomData,
2939        })
2940    }
2941}
2942
2943// ── opt_closed_enum: Option<E> with unknown-value handling ───────────────────
2944
2945/// Serde with-module for `Option<E>` optional closed enum fields (proto2).
2946///
2947/// When `ignore_unknown_enum_values` is active, an unknown enum name, or a
2948/// number in `i32` range that the enum does not declare, produces `None`
2949/// (field not set) instead of an error.
2950pub mod opt_closed_enum {
2951    use serde::{Deserializer, Serializer};
2952
2953    pub fn serialize<E: crate::Enumeration, S: Serializer>(
2954        value: &Option<E>,
2955        s: S,
2956    ) -> Result<S::Ok, S::Error> {
2957        match value {
2958            Some(v) => s.serialize_str(v.proto_name()),
2959            None => s.serialize_none(),
2960        }
2961    }
2962
2963    pub fn deserialize<'de, E: crate::Enumeration + Default, D: Deserializer<'de>>(
2964        d: D,
2965    ) -> Result<Option<E>, D::Error> {
2966        let raw: Option<super::BufferedValue> = serde::Deserialize::deserialize(d)?;
2967        let raw = match raw {
2968            Some(super::BufferedValue(v)) => v,
2969            None => return Ok(None),
2970        };
2971
2972        super::try_deserialize_closed_enum::<E>(&raw).map_err(serde::de::Error::custom)
2973    }
2974}
2975
2976// ── repeated_closed_enum: Vec<E> with unknown-value filtering ────────────────
2977
2978/// Serde with-module for `Vec<E>` repeated closed enum fields, or any
2979/// collection that is `From<Vec<E>>`.
2980///
2981/// When `ignore_unknown_enum_values` is active, an unknown enum name, or a
2982/// number in `i32` range that the enum does not declare, is silently
2983/// skipped.
2984/// JSON null deserializes to an empty vec, but null elements are rejected.
2985pub mod repeated_closed_enum {
2986    use alloc::vec::Vec;
2987    use serde::{Deserializer, Serializer};
2988
2989    pub fn serialize<E: crate::Enumeration, S: Serializer>(
2990        value: &[E],
2991        s: S,
2992    ) -> Result<S::Ok, S::Error> {
2993        use serde::ser::SerializeSeq;
2994        let null_sentinel = E::IS_NULL_VALUE && s.is_human_readable();
2995        let mut seq = s.serialize_seq(Some(value.len()))?;
2996        for v in value {
2997            if null_sentinel && v.to_i32() == 0 {
2998                seq.serialize_element(&())?;
2999            } else {
3000                seq.serialize_element(&crate::json_helpers::EnumProtoNameRef(v))?;
3001            }
3002        }
3003        seq.end()
3004    }
3005
3006    pub fn deserialize<'de, E, C, D>(d: D) -> Result<C, D::Error>
3007    where
3008        E: crate::Enumeration + Default,
3009        C: From<Vec<E>>,
3010        D: Deserializer<'de>,
3011    {
3012        struct V<E>(core::marker::PhantomData<E>);
3013        impl<'de, E: crate::Enumeration + Default> serde::de::Visitor<'de> for V<E> {
3014            type Value = Vec<E>;
3015
3016            fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
3017                f.write_str("a list of enum values or null")
3018            }
3019
3020            fn visit_unit<Err>(self) -> Result<Vec<E>, Err> {
3021                Ok(Vec::new())
3022            }
3023
3024            reject_container_scalar_values!(InvalidListType);
3025            crate::__buffa_reject_other_json_kinds!(bytes, byte_buf);
3026            fn visit_seq<A: serde::de::SeqAccess<'de>>(
3027                self,
3028                mut seq: A,
3029            ) -> Result<Vec<E>, A::Error> {
3030                let mut out = Vec::with_capacity(super::clamp_size_hint(seq.size_hint()));
3031                while let Some(super::BufferedValue(raw)) = seq.next_element()? {
3032                    if raw.is_null() && E::IS_NULL_VALUE {
3033                        let value = E::from_i32(0).ok_or_else(|| {
3034                            <A::Error as serde::de::Error>::custom(
3035                                super::enum_list::ErrorReason::Unknown,
3036                            )
3037                        })?;
3038                        out.push(value);
3039                        continue;
3040                    }
3041                    match super::try_deserialize_closed_enum::<E>(&raw) {
3042                        Ok(Some(v)) => out.push(v),
3043                        Ok(None) => continue,
3044                        Err(e) => return Err(serde::de::Error::custom(e)),
3045                    }
3046                }
3047                Ok(out)
3048            }
3049        }
3050        d.deserialize_any(V::<E>(core::marker::PhantomData))
3051            .map(C::from)
3052    }
3053}
3054
3055// ── map_closed_enum: HashMap<K, E> with unknown-value filtering ──────────────
3056
3057/// Serde with-module for `HashMap<K, E>` map fields where the value is a
3058/// closed enum type.
3059///
3060/// When `ignore_unknown_enum_values` is active, map entries whose value is
3061/// an unknown enum name, or a number in `i32` range that the enum does not
3062/// declare, are silently dropped.
3063/// JSON null deserializes to an empty map, but null values are rejected.
3064pub mod map_closed_enum {
3065    use crate::map_codec::MapStorage;
3066    use serde::{Deserializer, Serializer};
3067
3068    pub fn serialize<C, S>(value: &C, s: S) -> Result<S::Ok, S::Error>
3069    where
3070        C: MapStorage,
3071        C::Key: serde::Serialize,
3072        C::Value: crate::Enumeration,
3073        S: Serializer,
3074    {
3075        use serde::ser::SerializeMap;
3076        let mut map = s.serialize_map(Some(value.storage_len()))?;
3077        for (k, v) in value.storage_iter() {
3078            map.serialize_entry(k, &crate::json_helpers::EnumProtoNameRef(v))?;
3079        }
3080        map.end()
3081    }
3082
3083    pub fn deserialize<'de, C, D>(d: D) -> Result<C, D::Error>
3084    where
3085        C: MapStorage + Default,
3086        C::Key: serde::Deserialize<'de>,
3087        C::Value: crate::Enumeration + Default,
3088        D: Deserializer<'de>,
3089    {
3090        struct V<C>(core::marker::PhantomData<C>);
3091        impl<'de, C> serde::de::Visitor<'de> for V<C>
3092        where
3093            C: MapStorage + Default,
3094            C::Key: serde::Deserialize<'de>,
3095            C::Value: crate::Enumeration + Default,
3096        {
3097            type Value = C;
3098
3099            fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
3100                f.write_str("a map with enum values or null")
3101            }
3102
3103            fn visit_unit<Err>(self) -> Result<Self::Value, Err> {
3104                Ok(C::default())
3105            }
3106
3107            reject_container_scalar_values!(InvalidMapType);
3108            crate::__buffa_reject_other_json_kinds!(bytes, byte_buf);
3109            fn visit_map<A: serde::de::MapAccess<'de>>(
3110                self,
3111                mut map: A,
3112            ) -> Result<Self::Value, A::Error> {
3113                let mut out = C::default();
3114                while let Some(key) = map.next_key_seed(super::map_key::KeySeed::<C::Key>::new())? {
3115                    let key = crate::erasing::Erasing::new(key, C::storage_erase_key);
3116                    let super::BufferedValue(raw) = map.next_value()?;
3117                    match super::try_deserialize_closed_enum::<C::Value>(&raw) {
3118                        Ok(Some(v)) => {
3119                            out.storage_insert(key.into_inner(), v);
3120                        }
3121                        Ok(None) => continue,
3122                        Err(e) => return Err(serde::de::Error::custom(e)),
3123                    }
3124                }
3125                Ok(out)
3126            }
3127        }
3128        d.deserialize_any(V::<C>(core::marker::PhantomData))
3129    }
3130}
3131
3132// ── tests ─────────────────────────────────────────────────────────────────────
3133
3134#[cfg(test)]
3135mod tests;
3136
3137/// Enum collection decoding without intermediate owned containers.
3138pub mod enum_list;
3139/// Streaming enum helpers for cleanup-enabled generated messages.
3140#[doc(hidden)]
3141#[cfg(feature = "zeroize")]
3142pub mod guarded_enum;
3143mod guarded_key;
3144/// Direct-key map decoding for cleanup-enabled generated messages.
3145#[doc(hidden)]
3146#[cfg(feature = "zeroize")]
3147pub mod guarded_map;