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 policy;
37pub mod proto_list;
38#[doc(hidden)]
39pub mod wkt;
40
41#[doc(hidden)]
42pub use policy::{
43    bytes_policy, opt_bytes_policy, opt_string_policy, policy_str_key_map, string_policy,
44    BytesPolicyJson, BytesPolicySeed, BytesPolicySeqJson, StringPolicyJson, StringPolicySeed,
45    StringPolicySeqJson, ViewJsonErrorReason,
46};
47pub use policy::{ProtoBytesJson, ProtoStringJson};
48
49use buffered::BufferedValue;
50
51/// Fixed diagnostics shared by the runtime and its well-known type codecs.
52///
53/// Never include the token or a parser's original error in these reasons.
54#[doc(hidden)]
55#[derive(Clone, Copy, Debug, thiserror::Error)]
56#[non_exhaustive]
57pub enum JsonValueError {
58    #[error("invalid protobuf map key")]
59    MapKey,
60    #[error("invalid i32 value")]
61    Int32,
62    #[error("invalid u32 value")]
63    Uint32,
64    #[error("invalid i64 value")]
65    Int64,
66    #[error("invalid u64 value")]
67    Uint64,
68    #[error("invalid float value, expected a finite f32 or a protobuf special value")]
69    Float,
70    #[error("invalid double value, expected a finite f64 or a protobuf special value")]
71    Double,
72    #[error("invalid base64 string")]
73    Base64,
74    #[error("invalid Duration string")]
75    Duration,
76    #[error("invalid RFC 3339 timestamp")]
77    Timestamp,
78    #[error("invalid JSON payload for a registered Any message")]
79    AnyMessage,
80    #[error("invalid JSON value for a registered Any well-known type")]
81    AnyWellKnownType,
82    #[error("@type is not a valid type URL: it names no type")]
83    AnyEmptyType,
84    #[error("@type must contain a '/' (e.g. type.googleapis.com/pkg.Type)")]
85    AnyBareType,
86    #[error("Any with a well-known type requires a \"value\" key")]
87    AnyMissingValue,
88    #[error("Any with a well-known type has an unexpected field")]
89    AnyUnexpectedField,
90    #[error("Any type is not registered in the descriptor pool")]
91    AnyUnregisteredType,
92    #[error("Any: no type registry is installed to resolve a bare @type; install one with `set_type_registry`, or send a type URL")]
93    AnyBareTypeWithoutRegistry,
94    #[error("Any: bare @type has no JSON entry in the type registry; register the message or send a type URL")]
95    AnyBareTypeWithoutEntry,
96    #[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`")]
97    AnyOpaqueWithoutRegistry,
98    #[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`")]
99    AnyOpaqueWithoutEntry,
100    #[error("Any opaque payload field cannot be parsed")]
101    AnyOpaqueField,
102}
103
104// ── Lenient base64 engines ──────────────────────────────────────────────────
105//
106// The pre-built `general_purpose` engines reject non-zero trailing bits.
107// The protobuf JSON spec requires accepting any valid standard or URL-safe
108// base64, so we configure lenient engines that tolerate trailing bits and
109// optional padding.
110
111use base64::alphabet;
112use base64::engine::{
113    general_purpose::STANDARD, DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig,
114};
115
116const LENIENT_CFG: GeneralPurposeConfig = GeneralPurposeConfig::new()
117    .with_decode_allow_trailing_bits(true)
118    .with_decode_padding_mode(DecodePaddingMode::Indifferent);
119
120const STANDARD_LENIENT: GeneralPurpose = GeneralPurpose::new(&alphabet::STANDARD, LENIENT_CFG);
121const URL_SAFE_LENIENT: GeneralPurpose = GeneralPurpose::new(&alphabet::URL_SAFE, LENIENT_CFG);
122
123/// Maximum elements to pre-allocate from a deserializer's `size_hint`.
124///
125/// `size_hint` comes from untrusted input in the general case (any
126/// `Deserializer<'de>`, not just `serde_json`). A hostile implementation
127/// could return `Some(usize::MAX)`, causing `Vec::with_capacity` to abort.
128/// Capping the hint bounds worst-case preallocation while still avoiding
129/// reallocs for small-to-medium collections.
130const MAX_PREALLOC_HINT: usize = 4096;
131
132/// Clamp a deserializer size hint to [`MAX_PREALLOC_HINT`].
133#[inline]
134fn clamp_size_hint(hint: Option<usize>) -> usize {
135    hint.unwrap_or(0).min(MAX_PREALLOC_HINT)
136}
137
138// ── ProtoElemJson: per-element proto3-JSON dispatch trait ───────────────────
139//
140// Proto3 JSON has per-type encoding rules (int64 → quoted string, float NaN
141// → "NaN", bytes → base64). For singular/optional fields these are handled
142// by the int64/float/bytes/etc. modules below. For CONTAINERS (repeated, map
143// values) we need to apply the same per-element encoding, but serde's `with =`
144// attribute doesn't compose. This trait provides the dispatch point.
145//
146// proto_seq, proto_map, proto_str_key_map and bytes_key_map are the container
147// modules — they are generic over T: ProtoElemJson. Codegen emits ProtoElemJson
148// impls for each generated message and enum type.
149//
150// Named `Json` (not `Serde`) because these are JSON-specific encoding rules.
151// A future YAML encoder would have different per-element rules (YAML has native
152// int64, no quoting needed) and would get its own trait.
153
154/// Per-element proto3-JSON encoding.
155///
156/// Implemented in this crate for primitives (i64 → quoted, f64 → NaN/Inf
157/// strings, `Vec<u8>` → base64, etc.). Codegen generates impls for message
158/// and enum types. Used by [`proto_seq`] (repeated fields), [`proto_map`],
159/// [`proto_str_key_map`] and [`bytes_key_map`] (map values) to apply proto-JSON
160/// encoding to each element.
161pub trait ProtoElemJson: Sized {
162    /// Serialize this value with proto3 JSON semantics.
163    fn serialize_proto_json<S: serde::Serializer>(v: &Self, s: S) -> Result<S::Ok, S::Error>;
164    /// Deserialize a value with proto3 JSON semantics.
165    fn deserialize_proto_json<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error>;
166    /// Deserialize a JSON `null` when it is a valid representation of this
167    /// protobuf type inside a container. Most protobuf element types reject
168    /// `null`; `google.protobuf.Value` overrides this for its null variant.
169    fn deserialize_proto_json_null<E: serde::de::Error>() -> Result<Self, E> {
170        Err(E::custom(
171            "null is not a valid repeated-field element or map value",
172        ))
173    }
174}
175
176/// Wraps `&T: ProtoElemJson` as `serde::Serialize`.
177///
178/// Generated code uses this (and the sibling `*Json` adapters below) where
179/// a value needs proto3-JSON encoding inside a hand-rolled `Serialize` impl
180/// — oneof variant entries, view map/sequence elements — instead of
181/// emitting a local newtype + impl at every site.
182///
183/// The adapters are generated-code plumbing, not a stable consumer-facing
184/// surface (the `#[serde(with = ...)]` modules in this file are the
185/// supported API); they are hidden from rustdoc accordingly.
186#[doc(hidden)]
187pub struct ProtoJson<'a, T>(pub &'a T);
188impl<T: ProtoElemJson> serde::Serialize for ProtoJson<'_, T> {
189    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
190        T::serialize_proto_json(self.0, s)
191    }
192}
193
194/// Serialize a borrowed `bytes` payload as base64 (the proto3 JSON
195/// encoding), for view types whose bytes fields are `&[u8]` (no
196/// [`ProtoElemJson`] impl exists for the unsized slice).
197#[doc(hidden)]
198pub struct BytesJson<'a>(pub &'a [u8]);
199impl serde::Serialize for BytesJson<'_> {
200    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
201        bytes::serialize(self.0, s)
202    }
203}
204
205/// Serialize a closed enum as its proto name string.
206#[doc(hidden)]
207pub struct ClosedEnumJson<'a, E>(pub &'a E);
208impl<E: crate::Enumeration> serde::Serialize for ClosedEnumJson<'_, E> {
209    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
210        closed_enum::serialize(self.0, s)
211    }
212}
213
214/// Serialize a proto map key by stringification (proto3 JSON maps always
215/// use string keys), mirroring [`proto_map`]'s internal `DisplayKey`.
216#[doc(hidden)]
217pub struct MapKeyJson<'a, T: ?Sized>(pub &'a T);
218impl<T: ?Sized + core::fmt::Display> serde::Serialize for MapKeyJson<'_, T> {
219    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
220        s.collect_str(self.0)
221    }
222}
223
224/// Serialize a slice of proto-JSON-encoded elements (see [`proto_seq`]).
225#[doc(hidden)]
226pub struct RepeatedJson<'a, T>(pub &'a [T]);
227impl<T: ProtoElemJson> serde::Serialize for RepeatedJson<'_, T> {
228    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
229        proto_seq::serialize(self.0, s)
230    }
231}
232
233/// Serialize a slice of borrowed `bytes` payloads, each base64-encoded.
234#[doc(hidden)]
235pub struct BytesSeqJson<'a>(pub &'a [&'a [u8]]);
236impl serde::Serialize for BytesSeqJson<'_> {
237    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
238        use serde::ser::SerializeSeq;
239        let mut seq = s.serialize_seq(Some(self.0.len()))?;
240        for v in self.0 {
241            seq.serialize_element(&BytesJson(v))?;
242        }
243        seq.end()
244    }
245}
246
247/// Serialize a slice of open-enum values (see [`repeated_enum`]).
248#[doc(hidden)]
249pub struct EnumSeqJson<'a, E: crate::Enumeration>(pub &'a [crate::EnumValue<E>]);
250impl<E: crate::Enumeration> serde::Serialize for EnumSeqJson<'_, E> {
251    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
252        repeated_enum::serialize(self.0, s)
253    }
254}
255
256/// Serialize a slice of closed-enum values as proto name strings.
257#[doc(hidden)]
258pub struct ClosedEnumSeqJson<'a, E>(pub &'a [E]);
259impl<E: crate::Enumeration> serde::Serialize for ClosedEnumSeqJson<'_, E> {
260    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
261        repeated_closed_enum::serialize(self.0, s)
262    }
263}
264
265/// Bridge seed: deserializes a single T via `ProtoElemJson::deserialize_proto_json`,
266/// but routes `null` to [`ProtoElemJson::deserialize_proto_json_null`], which
267/// REJECTS it by default. Per proto3 JSON spec, `null` as an element of a
268/// repeated field or as a map value is invalid (only the container itself may be
269/// `null`, meaning empty); `google.protobuf.Value` is the one type that
270/// overrides the hook, because `null` is one of its variants. The singular
271/// helper modules accept null → default, which is correct for singular fields
272/// but wrong for container elements.
273struct ProtoElemSeed<T>(core::marker::PhantomData<T>);
274impl<'de, T: ProtoElemJson> serde::de::DeserializeSeed<'de> for ProtoElemSeed<T> {
275    type Value = T;
276    fn deserialize<D: serde::Deserializer<'de>>(self, d: D) -> Result<T, D::Error> {
277        // Peek-via-Option: serde_json calls visit_none for null. If the element
278        // is null, that's an error; otherwise deserialize normally.
279        struct NoNull<T>(core::marker::PhantomData<T>);
280        impl<'de, T: ProtoElemJson> serde::de::Visitor<'de> for NoNull<T> {
281            type Value = T;
282            fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
283                f.write_str("a non-null value")
284            }
285            fn visit_none<E: serde::de::Error>(self) -> Result<T, E> {
286                T::deserialize_proto_json_null()
287            }
288            fn visit_unit<E: serde::de::Error>(self) -> Result<T, E> {
289                T::deserialize_proto_json_null()
290            }
291            fn visit_some<D2: serde::Deserializer<'de>>(self, d: D2) -> Result<T, D2::Error> {
292                T::deserialize_proto_json(d)
293            }
294        }
295        d.deserialize_option(NoNull::<T>(core::marker::PhantomData))
296    }
297}
298
299// ── Primitive impls ──────────────────────────────────────────────────────────
300
301/// Delegate-to-existing-module macro: for types where a singular `with`
302/// module already exists (int64, float, bytes, etc.), the ProtoElemJson
303/// impl just forwards to that module's serialize/deserialize.
304macro_rules! proto_elem_json_delegate {
305    ($ty:ty, $mod:ident) => {
306        impl ProtoElemJson for $ty {
307            fn serialize_proto_json<S: serde::Serializer>(
308                v: &Self,
309                s: S,
310            ) -> Result<S::Ok, S::Error> {
311                $mod::serialize(v, s)
312            }
313            fn deserialize_proto_json<'de, D: serde::Deserializer<'de>>(
314                d: D,
315            ) -> Result<Self, D::Error> {
316                $mod::deserialize(d)
317            }
318        }
319    };
320}
321
322// ── proto_seq: generic repeated-field module ─────────────────────────────────
323
324/// Serde with-module for `repeated T` fields where `T: ProtoElemJson`.
325///
326/// Each element is serialized/deserialized via [`ProtoElemJson`], applying
327/// proto3 JSON semantics (quoted int64, NaN/Inf strings, base64 bytes, etc.).
328/// JSON `null` deserializes to an empty vec.
329///
330/// Use with `#[serde(with = "::buffa::json_helpers::proto_seq")]`.
331pub mod proto_seq {
332    use super::{ProtoElemJson, ProtoElemSeed, ProtoJson};
333    use alloc::vec::Vec;
334    use serde::{Deserializer, Serializer};
335
336    pub fn serialize<T: ProtoElemJson, S: Serializer>(v: &[T], s: S) -> Result<S::Ok, S::Error> {
337        use serde::ser::SerializeSeq;
338        let mut seq = s.serialize_seq(Some(v.len()))?;
339        for elem in v {
340            seq.serialize_element(&ProtoJson(elem))?;
341        }
342        seq.end()
343    }
344
345    pub fn deserialize<'de, T, C, D>(d: D) -> Result<C, D::Error>
346    where
347        T: ProtoElemJson,
348        C: From<Vec<T>>,
349        D: Deserializer<'de>,
350    {
351        struct V<T>(core::marker::PhantomData<T>);
352        impl<'de, T: ProtoElemJson> serde::de::Visitor<'de> for V<T> {
353            type Value = Vec<T>;
354            fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
355                f.write_str("an array or null")
356            }
357            fn visit_unit<E>(self) -> Result<Vec<T>, E> {
358                Ok(Vec::new())
359            }
360            fn visit_seq<A: serde::de::SeqAccess<'de>>(
361                self,
362                mut seq: A,
363            ) -> Result<Vec<T>, A::Error> {
364                let mut out = Vec::with_capacity(super::clamp_size_hint(seq.size_hint()));
365                while let Some(elem) =
366                    seq.next_element_seed(ProtoElemSeed::<T>(core::marker::PhantomData))?
367                {
368                    out.push(elem);
369                }
370                Ok(out)
371            }
372        }
373        d.deserialize_any(V::<T>(core::marker::PhantomData))
374            .map(C::from)
375    }
376}
377
378/// Wraps a `Display`-able key as a serde string without allocating.
379///
380/// `collect_str` lets serde_json write the Display output directly to
381/// its internal buffer. For `K = String`, this is still one copy (into
382/// serde_json's buffer) but avoids the intermediate `String` allocation
383/// that `.to_string()` would create.
384struct DisplayKey<'a, K: ?Sized>(&'a K);
385impl<K: core::fmt::Display + ?Sized> serde::Serialize for DisplayKey<'_, K> {
386    #[inline]
387    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
388        s.collect_str(self.0)
389    }
390}
391
392// ── proto_map: generic map module ────────────────────────────────────────────
393
394/// Serde with-module for `map<K, V>` fields where `V: ProtoElemJson`.
395///
396/// Keys are stringified (via `Display`) on serialize and parsed (via `FromStr`)
397/// on deserialize — proto3 JSON uses string keys for all maps. Values use
398/// [`ProtoElemJson`] for proto-JSON encoding. JSON `null` deserializes to
399/// an empty map.
400///
401/// Use with `#[serde(with = "::buffa::json_helpers::proto_map")]`.
402pub mod proto_map {
403    use super::{ProtoElemJson, ProtoElemSeed, ProtoJson};
404    use crate::map_codec::MapStorage;
405    use alloc::string::String;
406    use core::fmt::Display;
407    use core::str::FromStr;
408    use serde::{Deserializer, Serializer};
409
410    pub fn serialize<C, S>(m: &C, s: S) -> Result<S::Ok, S::Error>
411    where
412        C: MapStorage,
413        C::Key: Display,
414        C::Value: ProtoElemJson,
415        S: Serializer,
416    {
417        use serde::ser::SerializeMap;
418        let mut map = s.serialize_map(Some(m.storage_len()))?;
419        for (k, v) in m.storage_iter() {
420            map.serialize_entry(&super::DisplayKey(k), &ProtoJson(v))?;
421        }
422        map.end()
423    }
424
425    pub fn deserialize<'de, C, D>(d: D) -> Result<C, D::Error>
426    where
427        C: MapStorage + Default,
428        C::Key: FromStr,
429        C::Value: ProtoElemJson,
430        D: Deserializer<'de>,
431    {
432        struct Vis<C>(core::marker::PhantomData<C>);
433        impl<'de, C> serde::de::Visitor<'de> for Vis<C>
434        where
435            C: MapStorage + Default,
436            C::Key: FromStr,
437            C::Value: ProtoElemJson,
438        {
439            type Value = C;
440            fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
441                f.write_str("a JSON object with string keys, or null")
442            }
443            fn visit_unit<E>(self) -> Result<Self::Value, E> {
444                Ok(C::default())
445            }
446            fn visit_map<A: serde::de::MapAccess<'de>>(
447                self,
448                mut map: A,
449            ) -> Result<Self::Value, A::Error> {
450                let mut out = C::default();
451                while let Some(key) = map.next_key::<String>()? {
452                    let k = <C::Key as FromStr>::from_str(&key)
453                        .map_err(|_| serde::de::Error::custom(super::JsonValueError::MapKey))?;
454                    let k = crate::erasing::Erasing::new(k, C::storage_erase_key);
455                    let v =
456                        map.next_value_seed(ProtoElemSeed::<C::Value>(core::marker::PhantomData))?;
457                    out.storage_insert(k.into_inner(), v);
458                }
459                Ok(out)
460            }
461        }
462        d.deserialize_any(Vis::<C>(core::marker::PhantomData))
463    }
464}
465
466/// Serde with-module for `map<string, V>` fields whose **value** needs
467/// proto3-JSON encoding ([`ProtoElemJson`]: int64→quoted, float→NaN token,
468/// bytes→base64) and whose **key** is a custom
469/// [`ProtoString`](crate::types::ProtoString) type.
470///
471/// This is the string-key twin of [`proto_map`]. [`proto_map`] stringifies its
472/// key via `Display` / `FromStr`, which a `ProtoString` newtype need not
473/// implement; here the key is already a JSON string, so it is serialized and
474/// deserialized through its own `serde` impls (a custom string type used in a
475/// map is required to derive `Serialize` / `Deserialize`). The value path is
476/// identical to [`proto_map`], and JSON `null` likewise deserializes to an empty
477/// map.
478pub mod proto_str_key_map {
479    use super::{ProtoElemJson, ProtoElemSeed, ProtoJson};
480    use crate::map_codec::MapStorage;
481    use serde::{Deserializer, Serializer};
482
483    pub fn serialize<C, S>(m: &C, s: S) -> Result<S::Ok, S::Error>
484    where
485        C: MapStorage,
486        C::Key: serde::Serialize,
487        C::Value: ProtoElemJson,
488        S: Serializer,
489    {
490        use serde::ser::SerializeMap;
491        let mut map = s.serialize_map(Some(m.storage_len()))?;
492        for (k, v) in m.storage_iter() {
493            map.serialize_entry(k, &ProtoJson(v))?;
494        }
495        map.end()
496    }
497
498    pub fn deserialize<'de, C, D>(d: D) -> Result<C, D::Error>
499    where
500        C: MapStorage + Default,
501        C::Key: serde::Deserialize<'de>,
502        C::Value: ProtoElemJson,
503        D: Deserializer<'de>,
504    {
505        struct Vis<C>(core::marker::PhantomData<C>);
506        impl<'de, C> serde::de::Visitor<'de> for Vis<C>
507        where
508            C: MapStorage + Default,
509            C::Key: serde::Deserialize<'de>,
510            C::Value: ProtoElemJson,
511        {
512            type Value = C;
513            fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
514                f.write_str("a JSON object with string keys, or null")
515            }
516            fn visit_unit<E>(self) -> Result<Self::Value, E> {
517                Ok(C::default())
518            }
519            fn visit_map<A: serde::de::MapAccess<'de>>(
520                self,
521                mut map: A,
522            ) -> Result<Self::Value, A::Error> {
523                let mut out = C::default();
524                while let Some(k) = map.next_key::<C::Key>()? {
525                    let k = crate::erasing::Erasing::new(k, C::storage_erase_key);
526                    let v =
527                        map.next_value_seed(ProtoElemSeed::<C::Value>(core::marker::PhantomData))?;
528                    out.storage_insert(k.into_inner(), v);
529                }
530                Ok(out)
531            }
532        }
533        d.deserialize_any(Vis::<C>(core::marker::PhantomData))
534    }
535}
536
537// ── bool ─────────────────────────────────────────────────────────────────────
538
539/// Serde with-module for `bool` fields that accepts JSON `null` as `false`.
540///
541/// Use with `#[serde(with = "::buffa::json_helpers::proto_bool")]`.
542pub mod proto_bool {
543    use serde::{Deserializer, Serializer};
544
545    pub fn serialize<S: Serializer>(value: &bool, s: S) -> Result<S::Ok, S::Error> {
546        s.serialize_bool(*value)
547    }
548
549    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<bool, D::Error> {
550        struct V;
551        impl<'de> serde::de::Visitor<'de> for V {
552            type Value = bool;
553            fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
554                f.write_str("a boolean or null")
555            }
556            fn visit_unit<E>(self) -> Result<bool, E> {
557                Ok(false)
558            }
559            fn visit_bool<E>(self, v: bool) -> Result<bool, E> {
560                Ok(v)
561            }
562        }
563        d.deserialize_any(V)
564    }
565}
566
567// ── string ───────────────────────────────────────────────────────────────────
568
569/// Serde with-module for `string` fields that accepts JSON `null` as `""`.
570///
571/// Use with `#[serde(with = "::buffa::json_helpers::proto_string")]`.
572pub mod proto_string {
573    use serde::{Deserializer, Serializer};
574
575    /// Serialize a `string` field.
576    ///
577    /// Generic over `T: AsRef<str>` so configurable string types
578    /// (`smol_str::SmolStr`, `ecow::EcoString`, ...) serialize without relying
579    /// on `Deref<Target = str>` coercion at the `#[serde(with = ...)]` call
580    /// site. `String` and `&str` both satisfy the bound.
581    pub fn serialize<T: AsRef<str> + ?Sized, S: Serializer>(
582        value: &T,
583        s: S,
584    ) -> Result<S::Ok, S::Error> {
585        s.serialize_str(value.as_ref())
586    }
587
588    /// Deserialize a `string` field (or JSON `null` → `""`).
589    ///
590    /// Generic over the return type so that codegen's `string_type` knob (which
591    /// can map the field to `smol_str::SmolStr`, `ecow::EcoString`, etc.) works
592    /// without a per-type shim. The visitor constructs the target type directly:
593    /// `visit_str` goes through `ProtoString::copy_from_str`, which an SSO type
594    /// can override to inline short strings without an intermediate `String`.
595    /// `String` itself implements `ProtoString`, keeping the
596    /// default path zero-extra-cost. Type inference picks `T` from the field
597    /// type at the serde call site.
598    pub fn deserialize<'de, T, D>(d: D) -> Result<T, D::Error>
599    where
600        T: crate::ProtoString,
601        D: Deserializer<'de>,
602    {
603        struct V<T>(core::marker::PhantomData<T>);
604        impl<'de, T> serde::de::Visitor<'de> for V<T>
605        where
606            T: crate::ProtoString,
607        {
608            type Value = T;
609            fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
610                f.write_str("a string or null")
611            }
612            fn visit_unit<E>(self) -> Result<T, E> {
613                Ok(T::copy_from_str(""))
614            }
615            fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<T, E> {
616                Ok(T::copy_from_str(v))
617            }
618            fn visit_string<E>(self, v: alloc::string::String) -> Result<T, E> {
619                Ok(T::from(v))
620            }
621        }
622        d.deserialize_any(V::<T>(core::marker::PhantomData))
623    }
624}
625
626// ── enum ─────────────────────────────────────────────────────────────────────
627
628/// Shared reasons for protobuf enum JSON errors. Keep diagnostics independent
629/// of the input value so reporting a parse failure does not disclose it.
630#[doc(hidden)]
631#[derive(Clone, Copy, Debug, thiserror::Error)]
632#[non_exhaustive]
633pub enum EnumJsonErrorReason {
634    #[error("unknown enum name")]
635    UnknownName,
636    #[error("unknown enum number")]
637    UnknownNumber,
638    #[error("enum number out of i32 range")]
639    OutOfRange,
640    #[error("expected a protobuf enum name or integer")]
641    InvalidType,
642}
643
644/// Serde with-module for `EnumValue<E>` fields that accepts JSON `null` as the default.
645///
646/// Use with `#[serde(with = "::buffa::json_helpers::proto_enum")]`.
647pub mod proto_enum {
648    use super::EnumJsonErrorReason;
649    use serde::{Deserializer, Serializer};
650
651    pub fn serialize<E: crate::Enumeration, S: Serializer>(
652        value: &crate::EnumValue<E>,
653        s: S,
654    ) -> Result<S::Ok, S::Error> {
655        serde::Serialize::serialize(value, s)
656    }
657
658    pub fn deserialize<'de, E: crate::Enumeration, D: Deserializer<'de>>(
659        d: D,
660    ) -> Result<crate::EnumValue<E>, D::Error> {
661        struct V<E>(core::marker::PhantomData<E>);
662        impl<'de, E: crate::Enumeration> serde::de::Visitor<'de> for V<E> {
663            type Value = crate::EnumValue<E>;
664            fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
665                f.write_str("a protobuf enum name string, integer value, or null")
666            }
667            fn visit_unit<Err>(self) -> Result<crate::EnumValue<E>, Err> {
668                Ok(crate::EnumValue::from(0))
669            }
670            fn visit_i64<Err: serde::de::Error>(self, v: i64) -> Result<crate::EnumValue<E>, Err> {
671                let i =
672                    i32::try_from(v).map_err(|_| Err::custom(EnumJsonErrorReason::OutOfRange))?;
673                Ok(crate::EnumValue::from(i))
674            }
675            fn visit_u64<Err: serde::de::Error>(self, v: u64) -> Result<crate::EnumValue<E>, Err> {
676                let i =
677                    i32::try_from(v).map_err(|_| Err::custom(EnumJsonErrorReason::OutOfRange))?;
678                Ok(crate::EnumValue::from(i))
679            }
680            fn visit_f64<Err: serde::de::Error>(self, _: f64) -> Result<Self::Value, Err> {
681                Err(Err::custom(EnumJsonErrorReason::InvalidType))
682            }
683            fn visit_bool<Err: serde::de::Error>(self, _: bool) -> Result<Self::Value, Err> {
684                Err(Err::custom(EnumJsonErrorReason::InvalidType))
685            }
686            fn visit_str<Err: serde::de::Error>(self, v: &str) -> Result<crate::EnumValue<E>, Err> {
687                match E::from_proto_name(v) {
688                    Some(e) => Ok(crate::EnumValue::from(e)),
689                    None => {
690                        if crate::json::ignore_unknown_enum_values() {
691                            return Ok(crate::EnumValue::from(0));
692                        }
693                        Err(Err::custom(EnumJsonErrorReason::UnknownName))
694                    }
695                }
696            }
697        }
698        d.deserialize_any(V(core::marker::PhantomData))
699    }
700}
701
702// ── lenient enum deserialization helpers ──────────────────────────────────────
703
704/// Try to decode a `serde_json::Value` as a closed enum via [`Enumeration`].
705///
706/// When `ignore_unknown_enum_values` is active, returns `Ok(None)` for a
707/// [`ClosedEnumError::Unknown`] value, so the caller can drop the entry from
708/// its container (or leave the optional unset). A
709/// [`ClosedEnumError::Malformed`] value is an error in both modes. Strict
710/// mode propagates every error. [`try_deserialize_enum`] filters unknown
711/// names for open enums.
712///
713/// Why not [`try_deserialize_enum::<E>`]? It routes through
714/// `serde_json::from_value::<E>()`, which requires `E: DeserializeOwned` —
715/// i.e. the enum itself must `impl Deserialize`. That impl is only emitted
716/// by codegen when `generate_json = true`, so closed-enum fields whose enum
717/// type lives in an externally-generated crate built *without* json (e.g.
718/// `google.protobuf.FieldDescriptorProto.Type` from `buffa-descriptor`)
719/// would refuse to compile. Decoding directly via the [`Enumeration`] trait
720/// removes the impl requirement. It uses `from_proto_name` for strings and
721/// `from_i32` after range-checking integers. Null is handled by the optional
722/// field helper before this call and rejected inside containers.
723///
724/// Lenient filtering works in both `std` and `no_std` builds. Unlike the
725/// open-enum helper, this path decodes directly through [`Enumeration`], so
726/// it never needs a scoped strict-mode override.
727///
728/// [`Enumeration`]: crate::Enumeration
729#[inline]
730fn try_deserialize_closed_enum<E: crate::Enumeration + Default>(
731    raw: &serde_json::Value,
732) -> Result<Option<E>, EnumJsonErrorReason> {
733    match decode_closed_enum::<E>(raw) {
734        Ok(e) => Ok(Some(e)),
735        Err(ClosedEnumError::Unknown(_)) if crate::json::ignore_unknown_enum_values() => Ok(None),
736        Err(ClosedEnumError::Unknown(reason) | ClosedEnumError::Malformed(reason)) => Err(reason),
737    }
738}
739
740/// Why a buffered JSON value is not a variant of a closed enum.
741enum ClosedEnumError {
742    /// A name, or a number in `i32` range, that the enum does not declare.
743    /// Lenient parsing drops the value.
744    Unknown(EnumJsonErrorReason),
745    /// Null, a float, a number outside `i32`, a bool, an object or an array. An
746    /// error whether or not parsing is lenient.
747    Malformed(EnumJsonErrorReason),
748}
749
750/// Closed-enum decode of a buffered `serde_json::Value`, bound only on
751/// [`Enumeration`]. Every failure is an error here.
752///
753/// Accepts enum names and integer values. The optional-field helper handles
754/// null before calling this function; repeated elements and map values must
755/// reject it, even when unknown enum values are ignored.
756///
757/// [`Enumeration`]: crate::Enumeration
758fn decode_closed_enum<E: crate::Enumeration + Default>(
759    raw: &serde_json::Value,
760) -> Result<E, ClosedEnumError> {
761    use serde_json::Value;
762
763    match raw {
764        Value::String(s) => {
765            E::from_proto_name(s).ok_or(ClosedEnumError::Unknown(EnumJsonErrorReason::UnknownName))
766        }
767        Value::Number(n) if n.is_f64() => {
768            Err(ClosedEnumError::Malformed(EnumJsonErrorReason::InvalidType))
769        }
770        Value::Number(n) => {
771            // `as_i64()` / `as_u64()` are exclusive (a `Number` is stored
772            // as exactly one of i64 / u64 / f64; the float case is handled
773            // above). Try both before declaring it un-coerceable.
774            let v32 = n
775                .as_i64()
776                .and_then(|v| i32::try_from(v).ok())
777                .or_else(|| n.as_u64().and_then(|v| i32::try_from(v).ok()))
778                .ok_or(ClosedEnumError::Malformed(EnumJsonErrorReason::OutOfRange))?;
779            E::from_i32(v32).ok_or(ClosedEnumError::Unknown(EnumJsonErrorReason::UnknownNumber))
780        }
781        Value::Null | Value::Bool(_) | Value::Array(_) | Value::Object(_) => {
782            Err(ClosedEnumError::Malformed(EnumJsonErrorReason::InvalidType))
783        }
784    }
785}
786
787/// Try to deserialize a `serde_json::Value` as `T` under strict enum parsing.
788///
789/// When `ignore_unknown_enum_values` is active, returns `Ok(None)` for an
790/// unknown enum name, so the caller can drop the entry from its container
791/// (or leave the optional unset). A string is the one JSON type whose decode
792/// can fail on an unknown value: an `EnumValue` keeps an unknown number, so
793/// every other failure is a wrong JSON type or a number outside `i32`, and
794/// stays an error.
795///
796/// In `std` builds, filtering temporarily forces strict mode so an unknown
797/// enum name remains distinguishable from the default value. In `no_std`
798/// builds, `EnumValue` deserialization is already strict, so the process-wide
799/// option can filter the resulting error directly. Closed-enum containers use
800/// [`try_deserialize_closed_enum`] and follow the same lenient behavior.
801#[inline]
802fn try_deserialize_enum<T: serde::de::DeserializeOwned>(
803    raw: serde_json::Value,
804) -> Result<Option<T>, serde_json::Error> {
805    // Only a name can fail as unknown; see the doc comment.
806    let raw_is_string = raw.is_string();
807    let ignore = crate::json::ignore_unknown_enum_values();
808    // Run the inner deserialize in STRICT mode so that an unknown enum name
809    // is an error and not the default value.
810    #[cfg(feature = "std")]
811    let result = {
812        let strict = crate::json::JsonParseOptions {
813            ignore_unknown_enum_values: false,
814            ..Default::default()
815        };
816        crate::json::with_json_parse_options(&strict, || serde_json::from_value::<T>(raw))
817    };
818    // The inner `EnumValue` deserialize is always strict here; see the doc
819    // comment above.
820    #[cfg(not(feature = "std"))]
821    let result = serde_json::from_value::<T>(raw);
822    match result {
823        Ok(v) => Ok(Some(v)),
824        Err(_) if ignore && raw_is_string => Ok(None),
825        Err(e) => Err(e),
826    }
827}
828
829// ── repeated_enum: Vec<EnumValue<E>> with unknown-value filtering ────────────
830
831/// Serde with-module for `Vec<EnumValue<E>>` repeated enum fields, or any
832/// collection that is `From<Vec<EnumValue<E>>>`.
833///
834/// When `ignore_unknown_enum_values` is active, unknown enum string values
835/// are silently skipped instead of producing an error. In default mode this
836/// behaves identically to the standard `Vec<EnumValue<E>>` deserialization
837/// with null→empty-vec handling.
838pub mod repeated_enum {
839    use alloc::vec::Vec;
840    use serde::{Deserializer, Serializer};
841
842    pub fn serialize<E: crate::Enumeration, S: Serializer>(
843        value: &[crate::EnumValue<E>],
844        s: S,
845    ) -> Result<S::Ok, S::Error> {
846        serde::Serialize::serialize(value, s)
847    }
848
849    pub fn deserialize<'de, E, C, D>(d: D) -> Result<C, D::Error>
850    where
851        E: crate::Enumeration,
852        C: From<Vec<crate::EnumValue<E>>>,
853        D: Deserializer<'de>,
854    {
855        struct V<E>(core::marker::PhantomData<E>);
856        impl<'de, E: crate::Enumeration> serde::de::Visitor<'de> for V<E> {
857            type Value = Vec<crate::EnumValue<E>>;
858
859            fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
860                f.write_str("a list of enum values or null")
861            }
862
863            fn visit_unit<Err>(self) -> Result<Vec<crate::EnumValue<E>>, Err> {
864                Ok(Vec::new())
865            }
866
867            fn visit_seq<A: serde::de::SeqAccess<'de>>(
868                self,
869                mut seq: A,
870            ) -> Result<Vec<crate::EnumValue<E>>, A::Error> {
871                let mut out = Vec::with_capacity(super::clamp_size_hint(seq.size_hint()));
872                while let Some(super::BufferedValue(raw)) = seq.next_element()? {
873                    match super::try_deserialize_enum::<crate::EnumValue<E>>(raw) {
874                        Ok(Some(v)) => out.push(v),
875                        Ok(None) => continue,
876                        Err(e) => return Err(serde::de::Error::custom(e)),
877                    }
878                }
879                Ok(out)
880            }
881        }
882        d.deserialize_any(V::<E>(core::marker::PhantomData))
883            .map(C::from)
884    }
885}
886
887// ── map_enum: HashMap<K, EnumValue<E>> with unknown-value filtering ─────────
888
889/// Serde with-module for `HashMap<K, EnumValue<E>>` map fields where the
890/// value is an enum type.
891///
892/// When `ignore_unknown_enum_values` is active, map entries whose value is
893/// an unknown enum string are silently dropped. In default mode this behaves
894/// identically to standard deserialization with null→empty-map handling.
895///
896/// The lenient rule assumes that the map's value type is `EnumValue<E>`: it
897/// drops an entry whose value is a string that fails to decode.
898pub mod map_enum {
899    use crate::map_codec::MapStorage;
900    use serde::{Deserializer, Serializer};
901
902    pub fn serialize<C, S>(value: &C, s: S) -> Result<S::Ok, S::Error>
903    where
904        C: MapStorage,
905        C::Key: serde::Serialize,
906        C::Value: serde::Serialize,
907        S: Serializer,
908    {
909        use serde::ser::SerializeMap;
910        let mut map = s.serialize_map(Some(value.storage_len()))?;
911        for (k, v) in value.storage_iter() {
912            map.serialize_entry(k, v)?;
913        }
914        map.end()
915    }
916
917    pub fn deserialize<'de, C, D>(d: D) -> Result<C, D::Error>
918    where
919        C: MapStorage + Default,
920        C::Key: serde::Deserialize<'de>,
921        C::Value: serde::de::DeserializeOwned,
922        D: Deserializer<'de>,
923    {
924        struct V<C>(core::marker::PhantomData<C>);
925        impl<'de, C> serde::de::Visitor<'de> for V<C>
926        where
927            C: MapStorage + Default,
928            C::Key: serde::Deserialize<'de>,
929            C::Value: serde::de::DeserializeOwned,
930        {
931            type Value = C;
932
933            fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
934                f.write_str("a map with enum values or null")
935            }
936
937            fn visit_unit<Err>(self) -> Result<Self::Value, Err> {
938                Ok(C::default())
939            }
940
941            fn visit_map<A: serde::de::MapAccess<'de>>(
942                self,
943                mut map: A,
944            ) -> Result<Self::Value, A::Error> {
945                let mut out = C::default();
946                while let Some(key) = map.next_key::<C::Key>()? {
947                    let key = crate::erasing::Erasing::new(key, C::storage_erase_key);
948                    let super::BufferedValue(raw) = map.next_value()?;
949                    match super::try_deserialize_enum::<C::Value>(raw) {
950                        Ok(Some(v)) => {
951                            out.storage_insert(key.into_inner(), v);
952                        }
953                        Ok(None) => continue,
954                        Err(e) => return Err(serde::de::Error::custom(e)),
955                    }
956                }
957                Ok(out)
958            }
959        }
960        d.deserialize_any(V::<C>(core::marker::PhantomData))
961    }
962}
963
964// ── null_as_default: generic null→Default handler ────────────────────────────
965
966/// Generic deserialize function that treats JSON `null` as `T::default()`.
967///
968/// Use with `#[serde(deserialize_with = "::buffa::json_helpers::null_as_default")]`
969/// for repeated fields, map fields, and any other type where null should
970/// silently produce the default value.
971pub fn null_as_default<'de, D, T>(d: D) -> Result<T, D::Error>
972where
973    D: serde::Deserializer<'de>,
974    T: Default + serde::Deserialize<'de>,
975{
976    <Option<T> as serde::Deserialize>::deserialize(d).map(|opt| opt.unwrap_or_default())
977}
978
979// ── shared helper: parse string as integer, accepting floats/exponentials ────
980
981/// Returns `true` if `f` has no fractional part (i.e. it is an exact integer).
982///
983/// Casts to `i128` and back — if the round-trip preserves the value, `f` has
984/// no fractional part.  Deliberately not `f64::trunc()`-based: values outside
985/// i128 range saturate, producing a mismatch that correctly returns `false`
986/// (such values cannot fit any protobuf integer type anyway).
987fn is_exact_integer(f: f64) -> bool {
988    f.is_finite() && f == (f as i128 as f64)
989}
990
991/// Largest integer-valued `f64` this visitor accepts from an unquoted JSON
992/// decimal/exponent token: 2^52 - 1.
993///
994/// The hazard is not only f64 representability (integers up to 2^53 are
995/// exact) but `serde_json`'s *default* float parsing, which is not
996/// correctly rounded (that is its opt-in `float_roundtrip` feature) and can
997/// be off by an ulp. In `[2^52, 2^53)` an ulp is exactly 1, so a one-ulp
998/// parse error silently turns an integer token into the *adjacent* integer
999/// — observed: `"9007199254740991.0"` parsing as `…990.0`. Below 2^52 an
1000/// ulp is at most 0.5, so the same parse error breaks integrality instead
1001/// and the exactness check below rejects the token loudly rather than
1002/// mis-decoding it. Quote larger integer values to parse them exactly —
1003/// the quoted-string path parses the token text digit-by-digit.
1004const MAX_SAFE_JSON_INTEGER_F64: f64 = 4_503_599_627_370_495.0;
1005
1006/// Try to parse a string as an integer, handling float notation like `"1.0"`,
1007/// `"1e5"`, `"1.0e2"`.  Returns `None` if the value is not an exact integer.
1008fn parse_int_from_str<I: TryFrom<i128>>(v: &str) -> Option<I> {
1009    // First try direct integer parse.
1010    if let Ok(n) = v.parse::<i128>() {
1011        return I::try_from(n).ok();
1012    }
1013    let n = parse_exact_decimal_int(v)?;
1014    I::try_from(n).ok()
1015}
1016
1017/// Parse a decimal/exponential string as an exact integer.
1018///
1019/// Accepts the numeric string forms the JSON integer helpers intentionally
1020/// support beyond plain integers: zero-fraction decimals like `"1.0"` and
1021/// decimal scientific notation like `"1e5"` / `"1.0e2"`. Returns `None` if
1022/// the value is not mathematically integral or would overflow `i128`.
1023fn parse_exact_decimal_int(v: &str) -> Option<i128> {
1024    let (mantissa, exp) = match v.split_once(['e', 'E']) {
1025        // `i64::from_str` handles the exponent's sign and rejects empty,
1026        // non-digit, and i64-overflowing exponents.
1027        Some((m, e)) => (m, e.parse::<i64>().ok()?),
1028        None => (v, 0),
1029    };
1030    let (negative, mantissa) = match mantissa.strip_prefix('-') {
1031        Some(rest) => (true, rest),
1032        None => (false, mantissa.strip_prefix('+').unwrap_or(mantissa)),
1033    };
1034    let (int_part, frac_part) = mantissa
1035        .split_once('.')
1036        .map_or((mantissa, ""), |(i, f)| (i, f));
1037    if int_part.is_empty() && frac_part.is_empty() {
1038        return None;
1039    }
1040    // Trailing zeros do not affect integrality and would only inflate the
1041    // significand before we re-scale it. Integer zeros move into the exponent.
1042    let frac_part = frac_part.trim_end_matches('0');
1043    let (int_part, trailing_zeros) = if frac_part.is_empty() {
1044        let trimmed = int_part.trim_end_matches('0');
1045        (trimmed, int_part.len() - trimmed.len())
1046    } else {
1047        (int_part, 0)
1048    };
1049
1050    let mut significand = 0i128;
1051    for digit in int_part.bytes().chain(frac_part.bytes()) {
1052        if !digit.is_ascii_digit() {
1053            return None;
1054        }
1055        significand = significand
1056            .checked_mul(10)?
1057            .checked_add(i128::from(digit - b'0'))?;
1058    }
1059    if significand == 0 {
1060        // Zero is integral under any exponent; short-circuit before the
1061        // power-of-ten scaling below can overflow on e.g. "0e100".
1062        return Some(0);
1063    }
1064
1065    // value = significand × 10^(exp + trailing_zeros − frac_len)
1066    let scale = exp
1067        .checked_add(trailing_zeros as i64)?
1068        .checked_sub(frac_part.len() as i64)?;
1069    if scale >= 0 {
1070        let pow10 = 10i128.checked_pow(u32::try_from(scale).ok()?)?;
1071        significand = significand.checked_mul(pow10)?;
1072    } else {
1073        let divisor = 10i128.checked_pow(u32::try_from(scale.unsigned_abs()).ok()?)?;
1074        if significand % divisor != 0 {
1075            return None;
1076        }
1077        significand /= divisor;
1078    }
1079
1080    if negative {
1081        significand.checked_neg()
1082    } else {
1083        Some(significand)
1084    }
1085}
1086
1087/// Try to interpret an f64 as an exact integer, rejecting magnitudes above
1088/// [`MAX_SAFE_JSON_INTEGER_F64`] where the value no longer uniquely
1089/// identifies the JSON token it was parsed from.
1090fn f64_to_int<I: TryFrom<i128>>(v: f64) -> Option<I> {
1091    if !(-MAX_SAFE_JSON_INTEGER_F64..=MAX_SAFE_JSON_INTEGER_F64).contains(&v) {
1092        return None;
1093    }
1094    if !is_exact_integer(v) {
1095        return None;
1096    }
1097    I::try_from(v as i128).ok()
1098}
1099
1100// ── int32 / uint32 / int64 / uint64 ──────────────────────────────────────────
1101//
1102// These four serde with-modules share the same structural shape: a visitor
1103// that accepts `unit` (-> 0), `i64`, `u64`, `f64`, and `str` inputs.  Only
1104// the target type and serialization format differ (32-bit as JSON numbers,
1105// 64-bit as quoted decimal strings).
1106
1107/// Generates a serde with-module for an integer type.
1108///
1109/// Parameters:
1110/// - `$mod_name` / `$int_type`: module name and Rust integer type.
1111/// - `serialize_body`: expression for the `serialize` function body, given
1112///   value identifier and serializer identifier.
1113/// - `expecting`: expecting string for the visitor.
1114/// - `doc`: doc string for the generated module.
1115/// - `reason`: fixed diagnostic for malformed or out-of-range values.
1116/// - `parse_str`: parser for the quoted numeric form.
1117macro_rules! int_serde_module {
1118    (
1119        $mod_name:ident, $int_type:ty,
1120        doc = $doc:expr,
1121        serialize_body = |$val:ident, $ser:ident| $ser_body:expr,
1122        expecting = $expecting:expr,
1123        reason = $reason:ident,
1124        parse_str = $parse_str:ident $(,)?
1125    ) => {
1126        #[doc = $doc]
1127        pub mod $mod_name {
1128            use super::*;
1129            use serde::{Deserializer, Serializer};
1130
1131            pub fn serialize<S: Serializer>(value: &$int_type, s: S) -> Result<S::Ok, S::Error> {
1132                let $val = value;
1133                let $ser = s;
1134                $ser_body
1135            }
1136
1137            pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<$int_type, D::Error> {
1138                struct Vis;
1139                impl<'de> serde::de::Visitor<'de> for Vis {
1140                    type Value = $int_type;
1141                    fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1142                        f.write_str($expecting)
1143                    }
1144                    fn visit_unit<E>(self) -> Result<$int_type, E> {
1145                        Ok(0)
1146                    }
1147                    fn visit_bool<E: serde::de::Error>(self, _: bool) -> Result<$int_type, E> {
1148                        Err(E::custom(JsonValueError::$reason))
1149                    }
1150                    fn visit_i64<E: serde::de::Error>(self, v: i64) -> Result<$int_type, E> {
1151                        <$int_type>::try_from(v).map_err(|_| E::custom(JsonValueError::$reason))
1152                    }
1153                    fn visit_u64<E: serde::de::Error>(self, v: u64) -> Result<$int_type, E> {
1154                        <$int_type>::try_from(v).map_err(|_| E::custom(JsonValueError::$reason))
1155                    }
1156                    fn visit_f64<E: serde::de::Error>(self, v: f64) -> Result<$int_type, E> {
1157                        f64_to_int::<$int_type>(v).ok_or_else(|| E::custom(JsonValueError::$reason))
1158                    }
1159                    fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<$int_type, E> {
1160                        $parse_str(v).ok_or_else(|| E::custom(JsonValueError::$reason))
1161                    }
1162                }
1163                d.deserialize_any(Vis)
1164            }
1165        }
1166    };
1167}
1168
1169int_serde_module!(
1170    int32,
1171    i32,
1172    doc = "Serde with-module for `i32` fields.\n\n\
1173           Proto JSON accepts integers as numbers, quoted decimal strings, or\n\
1174           float notation (e.g. `1.0`, `1e5`).  Serializes as a JSON number.\n\n\
1175           Use with `#[serde(with = \"::buffa::json_helpers::int32\")]`.",
1176    serialize_body = |v, s| s.serialize_i32(*v),
1177    expecting = "an i32 as integer, string, float, or null",
1178    reason = Int32,
1179    parse_str = parse_int_from_str,
1180);
1181
1182int_serde_module!(
1183    uint32,
1184    u32,
1185    doc = "Serde with-module for `u32` fields.\n\n\
1186           Proto JSON accepts integers as numbers, quoted decimal strings, or\n\
1187           float notation (e.g. `1.0`, `1e5`).  Serializes as a JSON number.\n\n\
1188           Use with `#[serde(with = \"::buffa::json_helpers::uint32\")]`.",
1189    serialize_body = |v, s| s.serialize_u32(*v),
1190    expecting = "a u32 as integer, string, float, or null",
1191    reason = Uint32,
1192    parse_str = parse_int_from_str,
1193);
1194
1195int_serde_module!(
1196    int64,
1197    i64,
1198    doc = "Serde with-module for `i64` fields encoded as a quoted decimal string.\n\n\
1199           Proto JSON also accepts unquoted integers and float notation.\n\n\
1200           Use with `#[serde(with = \"::buffa::json_helpers::int64\")]`.",
1201    serialize_body = |v, s| {
1202        #[cfg(feature = "zeroize")]
1203        {
1204            crate::sensitive::serialize_decimal(v, s)
1205        }
1206        #[cfg(not(feature = "zeroize"))]
1207        {
1208            s.collect_str(v)
1209        }
1210    },
1211    expecting = "an i64 as a quoted decimal string, integer, float, or null",
1212    reason = Int64,
1213    parse_str = parse_int_from_str,
1214);
1215
1216// Try the full unsigned range before accepting decimal or exponent notation.
1217fn parse_u64(value: &str) -> Option<u64> {
1218    value.parse().ok().or_else(|| parse_int_from_str(value))
1219}
1220
1221int_serde_module!(
1222    uint64,
1223    u64,
1224    doc = "Serde with-module for `u64` fields encoded as a quoted decimal string.\n\n\
1225           Proto JSON also accepts unquoted integers and float notation.\n\n\
1226           Use with `#[serde(with = \"::buffa::json_helpers::uint64\")]`.",
1227    serialize_body = |v, s| {
1228        #[cfg(feature = "zeroize")]
1229        {
1230            crate::sensitive::serialize_decimal(v, s)
1231        }
1232        #[cfg(not(feature = "zeroize"))]
1233        {
1234            s.collect_str(v)
1235        }
1236    },
1237    expecting = "a u64 as a quoted decimal string, integer, float, or null",
1238    reason = Uint64,
1239    parse_str = parse_u64,
1240);
1241
1242// ── float ────────────────────────────────────────────────────────────────────
1243
1244/// Serde with-module for `float` fields.
1245///
1246/// Serializes finite values as JSON numbers. Serializes `NaN` as `"NaN"`,
1247/// positive infinity as `"Infinity"`, and negative infinity as `"-Infinity"`.
1248/// Accepts numbers, quoted decimal numbers, and those three string literals on
1249/// deserialization. A number or quoted decimal outside the `f32` range is an
1250/// error, not infinity, and `"inf"` / `"nan"` in other spellings are rejected.
1251///
1252/// A quoted decimal is parsed straight to `f32`, so it is rounded once, and
1253/// so is an unquoted integer in the `i64` or `u64` range. Any other unquoted
1254/// number reaches the visitor as the `f64` the deserializer parsed and is then
1255/// narrowed to `f32`, so it is rounded twice. The results differ, by one `f32`
1256/// ulp, when a decimal close to the midpoint between two adjacent `f32` values
1257/// becomes that midpoint as an `f64`, which then rounds to even:
1258/// `1.0000000596046448` decodes to `1.0` unquoted and to its nearest `f32`,
1259/// `1.0000001`, quoted. How close is close enough depends on the `f64` parse
1260/// (half an `f64` ulp with `serde_json`'s `float_roundtrip` feature, somewhat
1261/// more without it). Just below the `f32` overflow threshold, the same effect
1262/// makes an unquoted value an error that parses when quoted.
1263///
1264/// protobuf C++ also narrows a parsed `double`; protobuf-go rounds once. The
1265/// `f64` does not identify the decimal it came from, so the decoding side
1266/// cannot avoid this. A producer that wants single rounding can quote the
1267/// value. Tracked in [#647](https://github.com/anthropics/buffa/issues/647).
1268///
1269/// Use with `#[serde(with = "::buffa::json_helpers::float")]`.
1270pub mod float {
1271    use serde::{Deserializer, Serializer};
1272
1273    pub fn serialize<S: Serializer>(value: &f32, s: S) -> Result<S::Ok, S::Error> {
1274        if value.is_nan() {
1275            s.serialize_str("NaN")
1276        } else if *value == f32::INFINITY {
1277            s.serialize_str("Infinity")
1278        } else if *value == f32::NEG_INFINITY {
1279            s.serialize_str("-Infinity")
1280        } else {
1281            s.serialize_f32(*value)
1282        }
1283    }
1284
1285    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<f32, D::Error> {
1286        struct V;
1287        impl<'de> serde::de::Visitor<'de> for V {
1288            type Value = f32;
1289
1290            fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1291                f.write_str(r#"a float, "NaN", "Infinity", "-Infinity", or null"#)
1292            }
1293
1294            fn visit_unit<E>(self) -> Result<f32, E> {
1295                Ok(0.0)
1296            }
1297
1298            fn visit_bool<E: serde::de::Error>(self, _: bool) -> Result<f32, E> {
1299                Err(E::custom(super::JsonValueError::Float))
1300            }
1301
1302            fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<f32, E> {
1303                match v {
1304                    "NaN" => Ok(f32::NAN),
1305                    "Infinity" => Ok(f32::INFINITY),
1306                    "-Infinity" => Ok(f32::NEG_INFINITY),
1307                    // Rust's float parser saturates to infinity on overflow
1308                    // and also spells non-finite values "inf" / "nan" in any
1309                    // case. The three ProtoJSON tokens were matched above, so
1310                    // any non-finite result is out of range or not a float.
1311                    // Parsing straight to f32 rounds once; going via f64
1312                    // could round a value just below the f32::MAX boundary
1313                    // up to infinity.
1314                    _ => match v.parse::<f32>() {
1315                        Ok(f) if f.is_finite() => Ok(f),
1316                        _ => Err(E::custom(super::JsonValueError::Float)),
1317                    },
1318                }
1319            }
1320
1321            fn visit_f32<E: serde::de::Error>(self, v: f32) -> Result<f32, E> {
1322                Ok(v)
1323            }
1324
1325            fn visit_f64<E: serde::de::Error>(self, v: f64) -> Result<f32, E> {
1326                // The range check is on the narrowed `f32`: a decimal just
1327                // above `f32::MAX` that rounds back into range parses, as the
1328                // canonical text of `f32::MAX` (`3.4028235e+38`) does.
1329                let f = v as f32;
1330                if v.is_finite() && !f.is_finite() {
1331                    return Err(E::custom(super::JsonValueError::Float));
1332                }
1333                Ok(f)
1334            }
1335
1336            fn visit_i64<E: serde::de::Error>(self, v: i64) -> Result<f32, E> {
1337                Ok(v as f32)
1338            }
1339
1340            fn visit_u64<E: serde::de::Error>(self, v: u64) -> Result<f32, E> {
1341                Ok(v as f32)
1342            }
1343        }
1344        d.deserialize_any(V)
1345    }
1346}
1347
1348// ── double ───────────────────────────────────────────────────────────────────
1349
1350/// Serde with-module for `double` fields.
1351///
1352/// Serializes finite values as JSON numbers. Serializes `NaN` as `"NaN"`,
1353/// positive infinity as `"Infinity"`, and negative infinity as `"-Infinity"`.
1354/// Accepts numbers, quoted decimal numbers, and those three string literals on
1355/// deserialization. A quoted decimal outside the `f64` range is an error, not
1356/// infinity, and `"inf"` / `"nan"` in other spellings are rejected.
1357///
1358/// Use with `#[serde(with = "::buffa::json_helpers::double")]`.
1359pub mod double {
1360    use serde::{Deserializer, Serializer};
1361
1362    pub fn serialize<S: Serializer>(value: &f64, s: S) -> Result<S::Ok, S::Error> {
1363        if value.is_nan() {
1364            s.serialize_str("NaN")
1365        } else if *value == f64::INFINITY {
1366            s.serialize_str("Infinity")
1367        } else if *value == f64::NEG_INFINITY {
1368            s.serialize_str("-Infinity")
1369        } else {
1370            s.serialize_f64(*value)
1371        }
1372    }
1373
1374    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<f64, D::Error> {
1375        struct V;
1376        impl<'de> serde::de::Visitor<'de> for V {
1377            type Value = f64;
1378
1379            fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1380                f.write_str(r#"a double, "NaN", "Infinity", "-Infinity", or null"#)
1381            }
1382
1383            fn visit_unit<E>(self) -> Result<f64, E> {
1384                Ok(0.0)
1385            }
1386
1387            fn visit_bool<E: serde::de::Error>(self, _: bool) -> Result<f64, E> {
1388                Err(E::custom(super::JsonValueError::Double))
1389            }
1390
1391            fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<f64, E> {
1392                match v {
1393                    "NaN" => Ok(f64::NAN),
1394                    "Infinity" => Ok(f64::INFINITY),
1395                    "-Infinity" => Ok(f64::NEG_INFINITY),
1396                    // As for `float`: a non-finite parse result is an
1397                    // overflow or a spelling ProtoJSON does not have.
1398                    _ => match v.parse::<f64>() {
1399                        Ok(f) if f.is_finite() => Ok(f),
1400                        _ => Err(E::custom(super::JsonValueError::Double)),
1401                    },
1402                }
1403            }
1404
1405            fn visit_f64<E: serde::de::Error>(self, v: f64) -> Result<f64, E> {
1406                Ok(v)
1407            }
1408
1409            fn visit_f32<E: serde::de::Error>(self, v: f32) -> Result<f64, E> {
1410                Ok(v as f64)
1411            }
1412
1413            fn visit_i64<E: serde::de::Error>(self, v: i64) -> Result<f64, E> {
1414                Ok(v as f64)
1415            }
1416
1417            fn visit_u64<E: serde::de::Error>(self, v: u64) -> Result<f64, E> {
1418                Ok(v as f64)
1419            }
1420        }
1421        d.deserialize_any(V)
1422    }
1423}
1424
1425// ── bytes ─────────────────────────────────────────────────────────────────────
1426
1427/// Serde with-module for `bytes` fields encoded as standard base64 (RFC 4648).
1428///
1429/// Serializes as standard padded base64. Accepts standard base64, URL-safe
1430/// base64, and both padded and unpadded variants on deserialization, as
1431/// required by the [proto3 JSON spec].
1432///
1433/// [proto3 JSON spec]: https://protobuf.dev/programming-guides/proto3/#json
1434///
1435/// Use with `#[serde(with = "::buffa::json_helpers::bytes")]`.
1436pub mod bytes {
1437    use super::STANDARD;
1438    use base64::Engine as _;
1439    use serde::{Deserializer, Serializer};
1440
1441    /// Serialize as a base64-encoded string.
1442    ///
1443    /// Takes `&[u8]` so both `Vec<u8>` and `bytes::Bytes` fields are
1444    /// accepted via deref coercion at the `#[serde(with = ...)]` call site.
1445    pub fn serialize<S: Serializer>(value: &[u8], s: S) -> Result<S::Ok, S::Error> {
1446        s.serialize_str(&STANDARD.encode(value))
1447    }
1448
1449    /// Deserialize from a base64-encoded string (or JSON `null` → empty).
1450    ///
1451    /// Generic over the return type so that codegen's `use_bytes_type()`
1452    /// (which types the field as `bytes::Bytes`) works without a shim:
1453    /// the visitor produces `Vec<u8>`, the final `.into()` converts.
1454    /// `Vec<u8>: From<Vec<u8>>` (identity) keeps the default path zero-cost.
1455    /// Type inference picks `T` from the field type at the serde call site.
1456    pub fn deserialize<'de, T, D>(d: D) -> Result<T, D::Error>
1457    where
1458        T: From<alloc::vec::Vec<u8>>,
1459        D: Deserializer<'de>,
1460    {
1461        struct V;
1462        impl<'de> serde::de::Visitor<'de> for V {
1463            type Value = alloc::vec::Vec<u8>;
1464
1465            fn visit_unit<E>(self) -> Result<alloc::vec::Vec<u8>, E> {
1466                Ok(alloc::vec::Vec::new())
1467            }
1468
1469            fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1470                f.write_str("a base64-encoded string, or null")
1471            }
1472
1473            fn visit_bool<E: serde::de::Error>(self, _: bool) -> Result<alloc::vec::Vec<u8>, E> {
1474                Err(E::custom(super::JsonValueError::Base64))
1475            }
1476
1477            fn visit_i64<E: serde::de::Error>(self, _: i64) -> Result<alloc::vec::Vec<u8>, E> {
1478                Err(E::custom(super::JsonValueError::Base64))
1479            }
1480
1481            fn visit_u64<E: serde::de::Error>(self, _: u64) -> Result<alloc::vec::Vec<u8>, E> {
1482                Err(E::custom(super::JsonValueError::Base64))
1483            }
1484
1485            fn visit_f64<E: serde::de::Error>(self, _: f64) -> Result<alloc::vec::Vec<u8>, E> {
1486                Err(E::custom(super::JsonValueError::Base64))
1487            }
1488
1489            fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<alloc::vec::Vec<u8>, E> {
1490                super::decode_base64(v).map_err(serde::de::Error::custom)
1491            }
1492        }
1493        // Use deserialize_any (not deserialize_str) so null reaches visit_unit.
1494        d.deserialize_any(V).map(T::from)
1495    }
1496}
1497
1498// ── ProtoElemJson primitive impls ────────────────────────────────────────────
1499//
1500// Delegates to the singular `with` modules above. This is the complete set
1501// of proto scalar types that can appear as repeated elements or map values.
1502
1503proto_elem_json_delegate!(i32, int32);
1504proto_elem_json_delegate!(u32, uint32);
1505proto_elem_json_delegate!(i64, int64);
1506proto_elem_json_delegate!(u64, uint64);
1507proto_elem_json_delegate!(f32, float);
1508proto_elem_json_delegate!(f64, double);
1509proto_elem_json_delegate!(bool, proto_bool);
1510proto_elem_json_delegate!(alloc::string::String, proto_string);
1511proto_elem_json_delegate!(alloc::vec::Vec<u8>, bytes);
1512
1513// Only a custom `bytes` element used in a `repeated` / `map` field gets a
1514// codegen-emitted `ProtoElemJson` impl (forwarding to the `bytes` base64
1515// with-module) into the generating crate, where the type is local. A custom
1516// `string` element does NOT: `repeated_serde_module` returns `None` for
1517// `TYPE_STRING`, so a repeated string serializes through the element's own
1518// native `Serialize`/`Deserialize` rather than `proto_seq`/`ProtoElemJson`.
1519
1520// bytes::Bytes — for codegen's `use_bytes_type()` with `repeated bytes`.
1521// Serialize: `Bytes: Deref<Target=[u8]>` → `bytes::serialize(&[u8], s)`.
1522// Deserialize: `bytes::deserialize` is generic over `T: From<Vec<u8>>`;
1523// `Bytes::from(Vec<u8>)` takes ownership of the buffer (zero-copy).
1524//
1525// Not using the macro because `bytes::serialize(v, s)` needs `v: &[u8]`
1526// but `ProtoElemJson::serialize_proto_json` gets `v: &Self = &Bytes`.
1527// Deref coercion handles it, but being explicit avoids confusion.
1528impl ProtoElemJson for ::bytes::Bytes {
1529    fn serialize_proto_json<S: serde::Serializer>(v: &Self, s: S) -> Result<S::Ok, S::Error> {
1530        bytes::serialize(v, s)
1531    }
1532    fn deserialize_proto_json<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
1533        bytes::deserialize(d)
1534    }
1535}
1536
1537// EnumValue<E> (open enums) — uses its own Serialize/Deserialize (which
1538// handle proto JSON enum semantics: name string on serialize, accept name
1539// or integer on deserialize, preserve unknown values as the int).
1540impl<E: crate::Enumeration> ProtoElemJson for crate::EnumValue<E>
1541where
1542    Self: serde::Serialize + serde::de::DeserializeOwned,
1543{
1544    fn serialize_proto_json<S: serde::Serializer>(v: &Self, s: S) -> Result<S::Ok, S::Error> {
1545        serde::Serialize::serialize(v, s)
1546    }
1547    fn deserialize_proto_json<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
1548        <Self as serde::Deserialize>::deserialize(d)
1549    }
1550}
1551
1552/// Serde with-module for `map<string, ...>` fields where the key's
1553/// `utf8_validation = NONE` produced `Vec<u8>` keys under strict mapping.
1554///
1555/// Keys are serialized/deserialized as base64 strings (same as bytes values).
1556/// Values use [`ProtoElemJson`] so container-specific ProtoJSON rules apply and
1557/// `null` values are rejected.
1558///
1559/// Use with `#[serde(with = "::buffa::json_helpers::bytes_key_map")]`.
1560pub mod bytes_key_map {
1561    use super::{ProtoElemJson, ProtoElemSeed, ProtoJson};
1562    use crate::map_codec::MapStorage;
1563    use serde::{Deserializer, Serializer};
1564
1565    pub fn serialize<C, S>(value: &C, s: S) -> Result<S::Ok, S::Error>
1566    where
1567        C: MapStorage<Key = alloc::vec::Vec<u8>>,
1568        C::Value: ProtoElemJson,
1569        S: Serializer,
1570    {
1571        use serde::ser::SerializeMap;
1572        let mut map = s.serialize_map(Some(value.storage_len()))?;
1573        for (k, v) in value.storage_iter() {
1574            map.serialize_entry(&super::Base64Wrapper(k), &ProtoJson(v))?;
1575        }
1576        map.end()
1577    }
1578
1579    pub fn deserialize<'de, C, D>(d: D) -> Result<C, D::Error>
1580    where
1581        C: MapStorage<Key = alloc::vec::Vec<u8>> + Default,
1582        C::Value: ProtoElemJson,
1583        D: Deserializer<'de>,
1584    {
1585        struct Vis<C>(core::marker::PhantomData<C>);
1586        impl<'de, C> serde::de::Visitor<'de> for Vis<C>
1587        where
1588            C: MapStorage<Key = alloc::vec::Vec<u8>> + Default,
1589            C::Value: ProtoElemJson,
1590        {
1591            type Value = C;
1592            fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1593                f.write_str("a map with base64-encoded keys, or null")
1594            }
1595            fn visit_unit<E>(self) -> Result<Self::Value, E> {
1596                Ok(C::default())
1597            }
1598            fn visit_map<A: serde::de::MapAccess<'de>>(
1599                self,
1600                mut map: A,
1601            ) -> Result<Self::Value, A::Error> {
1602                let mut out = C::default();
1603                while let Some(key_str) = map.next_key::<alloc::string::String>()? {
1604                    #[cfg(feature = "zeroize")]
1605                    let key_str = zeroize::Zeroizing::new(key_str);
1606                    let k = super::decode_base64(&key_str).map_err(serde::de::Error::custom)?;
1607                    let k = crate::erasing::Erasing::new(k, C::storage_erase_key);
1608                    let v =
1609                        map.next_value_seed(ProtoElemSeed::<C::Value>(core::marker::PhantomData))?;
1610                    out.storage_insert(k.into_inner(), v);
1611                }
1612                Ok(out)
1613            }
1614        }
1615        d.deserialize_any(Vis::<C>(core::marker::PhantomData))
1616    }
1617}
1618
1619/// Serde with-module for `HashMap<Vec<u8>, Vec<u8>>` — both key and value
1620/// base64-encoded. This covers `map<string, string>` with `utf8_validation
1621/// = NONE` under strict mapping (both key and value normalized to bytes),
1622/// and `map<string, bytes>` with NONE on the key.
1623///
1624/// Use with `#[serde(with = "::buffa::json_helpers::bytes_key_bytes_val_map")]`.
1625pub mod bytes_key_bytes_val_map {
1626    use crate::map_codec::MapStorage;
1627    use serde::{Deserializer, Serializer};
1628
1629    pub fn serialize<C, S>(value: &C, s: S) -> Result<S::Ok, S::Error>
1630    where
1631        C: MapStorage<Key = alloc::vec::Vec<u8>, Value = alloc::vec::Vec<u8>>,
1632        S: Serializer,
1633    {
1634        use serde::ser::SerializeMap;
1635        let mut map = s.serialize_map(Some(value.storage_len()))?;
1636        for (k, v) in value.storage_iter() {
1637            map.serialize_entry(&super::Base64Wrapper(k), &super::Base64Wrapper(v))?;
1638        }
1639        map.end()
1640    }
1641
1642    pub fn deserialize<'de, C, D>(d: D) -> Result<C, D::Error>
1643    where
1644        C: MapStorage<Key = alloc::vec::Vec<u8>, Value = alloc::vec::Vec<u8>> + Default,
1645        D: Deserializer<'de>,
1646    {
1647        struct V<C>(core::marker::PhantomData<C>);
1648        impl<'de, C> serde::de::Visitor<'de> for V<C>
1649        where
1650            C: MapStorage<Key = alloc::vec::Vec<u8>, Value = alloc::vec::Vec<u8>> + Default,
1651        {
1652            type Value = C;
1653            fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1654                f.write_str("a map with base64-encoded keys and values, or null")
1655            }
1656            fn visit_unit<E>(self) -> Result<Self::Value, E> {
1657                Ok(C::default())
1658            }
1659            fn visit_map<A: serde::de::MapAccess<'de>>(
1660                self,
1661                mut map: A,
1662            ) -> Result<Self::Value, A::Error> {
1663                let mut out = C::default();
1664                while let Some(ks) = map.next_key::<alloc::string::String>()? {
1665                    #[cfg(feature = "zeroize")]
1666                    let ks = zeroize::Zeroizing::new(ks);
1667                    let k = super::decode_base64(&ks).map_err(serde::de::Error::custom)?;
1668                    let k = crate::erasing::Erasing::new(k, C::storage_erase_key);
1669                    let vs = map.next_value::<alloc::string::String>()?;
1670                    #[cfg(feature = "zeroize")]
1671                    let vs = zeroize::Zeroizing::new(vs);
1672                    let v = super::decode_base64(&vs).map_err(serde::de::Error::custom)?;
1673                    out.storage_insert(k.into_inner(), v);
1674                }
1675                Ok(out)
1676            }
1677        }
1678        d.deserialize_any(V::<C>(core::marker::PhantomData))
1679    }
1680}
1681
1682// ── string_key_map: non-string keys stringified, any MapStorage container ────
1683
1684/// Serde with-module for map fields with non-string key types (int32, int64,
1685/// uint32, uint64, bool, etc.).
1686///
1687/// In proto3 JSON, all map keys are strings.  For non-string key types, the
1688/// key string is parsed using `FromStr` during deserialization and formatted
1689/// directly into the serializer during serialization.
1690///
1691/// Use with `#[serde(with = "::buffa::json_helpers::string_key_map")]`.
1692pub mod string_key_map {
1693    use crate::map_codec::MapStorage;
1694    use core::fmt::Display;
1695    use core::str::FromStr;
1696    use serde::{Deserializer, Serializer};
1697
1698    pub fn serialize<C, S>(value: &C, s: S) -> Result<S::Ok, S::Error>
1699    where
1700        C: MapStorage,
1701        C::Key: Display,
1702        C::Value: serde::Serialize,
1703        S: Serializer,
1704    {
1705        use serde::ser::SerializeMap;
1706        let mut map = s.serialize_map(Some(value.storage_len()))?;
1707        for (k, v) in value.storage_iter() {
1708            map.serialize_entry(&super::DisplayKey(k), v)?;
1709        }
1710        map.end()
1711    }
1712
1713    pub fn deserialize<'de, C, D>(d: D) -> Result<C, D::Error>
1714    where
1715        C: MapStorage + Default,
1716        C::Key: FromStr,
1717        C::Value: serde::Deserialize<'de>,
1718        D: Deserializer<'de>,
1719    {
1720        struct MapVisitor<C>(core::marker::PhantomData<C>);
1721        impl<'de, C> serde::de::Visitor<'de> for MapVisitor<C>
1722        where
1723            C: MapStorage + Default,
1724            C::Key: FromStr,
1725            C::Value: serde::Deserialize<'de>,
1726        {
1727            type Value = C;
1728            fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1729                f.write_str("a JSON object with string keys, or null")
1730            }
1731            fn visit_unit<E>(self) -> Result<Self::Value, E> {
1732                Ok(C::default())
1733            }
1734            fn visit_map<A: serde::de::MapAccess<'de>>(
1735                self,
1736                mut map: A,
1737            ) -> Result<Self::Value, A::Error> {
1738                let mut out = C::default();
1739                while let Some(key_str) = map.next_key::<alloc::string::String>()? {
1740                    let key = key_str
1741                        .parse::<C::Key>()
1742                        .map_err(|_| serde::de::Error::custom(super::JsonValueError::MapKey))?;
1743                    let key = crate::erasing::Erasing::new(key, C::storage_erase_key);
1744                    let value = map.next_value()?;
1745                    out.storage_insert(key.into_inner(), value);
1746                }
1747                Ok(out)
1748            }
1749        }
1750        d.deserialize_any(MapVisitor::<C>(core::marker::PhantomData))
1751    }
1752}
1753
1754/// Newtype for serializing `&[u8]` as base64 without a separate `with` module.
1755struct Base64Wrapper<'a>(&'a [u8]);
1756
1757impl serde::Serialize for Base64Wrapper<'_> {
1758    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1759        bytes::serialize(self.0, s)
1760    }
1761}
1762
1763/// Decode a base64 string, accepting standard and URL-safe alphabets with
1764/// lenient trailing-bit and padding handling.
1765pub(crate) fn decode_base64(v: &str) -> Result<alloc::vec::Vec<u8>, JsonValueError> {
1766    use base64::Engine as _;
1767    STANDARD_LENIENT
1768        .decode(v)
1769        .or_else(|_| URL_SAFE_LENIENT.decode(v))
1770        .map_err(|_| JsonValueError::Base64)
1771}
1772
1773// ── Option<T> wrappers for proto2 optional scalar fields ─────────────────────
1774//
1775// serde's `#[serde(with = "...")]` on an `Option<T>` field needs the module
1776// to handle `&Option<T>` / `Option<T>`.  These thin wrappers delegate to the
1777// inner module for `Some` and pass through `None` transparently.
1778
1779macro_rules! opt_serde_module {
1780    ($mod_name:ident, $inner:ident, $ty:ty) => {
1781        pub mod $mod_name {
1782            use serde::{Deserializer, Serializer};
1783
1784            pub fn serialize<S: Serializer>(value: &Option<$ty>, s: S) -> Result<S::Ok, S::Error> {
1785                match value {
1786                    Some(v) => super::$inner::serialize(v, s),
1787                    None => s.serialize_none(),
1788                }
1789            }
1790
1791            pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<$ty>, D::Error> {
1792                // Use Option<T> deserialization so null → None (unset),
1793                // not Some(default).  For non-null values, delegate to the
1794                // inner module's deserializer.
1795                <Option<super::$mod_name::Helper> as serde::Deserialize>::deserialize(d)
1796                    .map(|opt| opt.map(|h| h.0))
1797            }
1798
1799            /// Newtype that deserializes via the inner module.
1800            struct Helper($ty);
1801
1802            impl<'de> serde::Deserialize<'de> for Helper {
1803                fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
1804                    super::$inner::deserialize(d).map(Helper)
1805                }
1806            }
1807        }
1808    };
1809}
1810
1811opt_serde_module!(opt_int32, int32, i32);
1812opt_serde_module!(opt_uint32, uint32, u32);
1813opt_serde_module!(opt_int64, int64, i64);
1814opt_serde_module!(opt_uint64, uint64, u64);
1815opt_serde_module!(opt_float, float, f32);
1816opt_serde_module!(opt_double, double, f64);
1817
1818/// Option wrapper for bytes fields (base64 encoding).
1819///
1820/// Generic over the inner type so both `Option<Vec<u8>>` (default) and
1821/// `Option<bytes::Bytes>` (codegen's `use_bytes_type()`) work. The
1822/// `AsRef<[u8]>` bound on serialize and `From<Vec<u8>>` on deserialize are
1823/// satisfied by both. `bytes::serialize` takes `&[u8]`, so we can't use
1824/// the `opt_*` macro — `&Option<T>` → `&[u8]` needs explicit unwrap.
1825pub mod opt_bytes {
1826    use serde::{Deserializer, Serializer};
1827
1828    pub fn serialize<T, S>(value: &Option<T>, s: S) -> Result<S::Ok, S::Error>
1829    where
1830        T: AsRef<[u8]>,
1831        S: Serializer,
1832    {
1833        match value {
1834            Some(v) => super::bytes::serialize(v.as_ref(), s),
1835            None => s.serialize_none(),
1836        }
1837    }
1838
1839    pub fn deserialize<'de, T, D>(d: D) -> Result<Option<T>, D::Error>
1840    where
1841        T: From<alloc::vec::Vec<u8>>,
1842        D: Deserializer<'de>,
1843    {
1844        // null → None (unset), non-null → delegate to bytes module.
1845        // The visitor stays Vec<u8>-typed; convert on the way out.
1846        struct Helper(alloc::vec::Vec<u8>);
1847        impl<'de> serde::Deserialize<'de> for Helper {
1848            fn deserialize<D2: Deserializer<'de>>(d: D2) -> Result<Self, D2::Error> {
1849                super::bytes::deserialize::<alloc::vec::Vec<u8>, _>(d).map(Helper)
1850            }
1851        }
1852        <Option<Helper> as serde::Deserialize>::deserialize(d).map(|opt| opt.map(|h| h.0.into()))
1853    }
1854}
1855
1856// ── opt_enum: Option<EnumValue<E>> with unknown-value → None ─────────────────
1857
1858/// Serde with-module for `Option<EnumValue<E>>` optional enum fields (proto2).
1859///
1860/// When `ignore_unknown_enum_values` is active, unknown enum string values
1861/// produce `None` (field not set) instead of `Some(default)`. In default
1862/// mode unknown strings produce an error.
1863pub mod opt_enum {
1864    use serde::{Deserializer, Serializer};
1865
1866    pub fn serialize<E: crate::Enumeration, S: Serializer>(
1867        value: &Option<crate::EnumValue<E>>,
1868        s: S,
1869    ) -> Result<S::Ok, S::Error> {
1870        match value {
1871            Some(v) => serde::Serialize::serialize(v, s),
1872            None => s.serialize_none(),
1873        }
1874    }
1875
1876    pub fn deserialize<'de, E: crate::Enumeration, D: Deserializer<'de>>(
1877        d: D,
1878    ) -> Result<Option<crate::EnumValue<E>>, D::Error> {
1879        // First, deserialize the raw value. null → None immediately.
1880        let raw: Option<super::BufferedValue> = serde::Deserialize::deserialize(d)?;
1881        let raw = match raw {
1882            Some(super::BufferedValue(v)) => v,
1883            None => return Ok(None),
1884        };
1885
1886        super::try_deserialize_enum::<crate::EnumValue<E>>(raw).map_err(serde::de::Error::custom)
1887    }
1888}
1889
1890// ── NullableDeserializeSeed ───────────────────────────────────────────────────
1891
1892/// `DeserializeSeed` that detects JSON null and returns `None` instead of
1893/// delegating to the inner seed. Used by generated oneof deserializers so
1894/// that `null` means "this variant is not set".
1895pub struct NullableDeserializeSeed<S>(pub S);
1896
1897impl<'de, S> serde::de::DeserializeSeed<'de> for NullableDeserializeSeed<S>
1898where
1899    S: serde::de::DeserializeSeed<'de>,
1900{
1901    type Value = Option<S::Value>;
1902
1903    fn deserialize<D: serde::Deserializer<'de>>(self, d: D) -> Result<Self::Value, D::Error> {
1904        d.deserialize_option(NullableVisitor(self.0))
1905    }
1906}
1907
1908struct NullableVisitor<S>(S);
1909
1910impl<'de, S> serde::de::Visitor<'de> for NullableVisitor<S>
1911where
1912    S: serde::de::DeserializeSeed<'de>,
1913{
1914    type Value = Option<S::Value>;
1915
1916    fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1917        f.write_str("a value or null")
1918    }
1919
1920    fn visit_none<E>(self) -> Result<Self::Value, E> {
1921        Ok(None)
1922    }
1923
1924    fn visit_unit<E>(self) -> Result<Self::Value, E> {
1925        Ok(None)
1926    }
1927
1928    fn visit_some<D: serde::Deserializer<'de>>(self, d: D) -> Result<Self::Value, D::Error> {
1929        self.0.deserialize(d).map(Some)
1930    }
1931}
1932
1933// ── DefaultDeserializeSeed ───────────────────────────────────────────────────
1934
1935/// `DeserializeSeed` that delegates to the type's standard `Deserialize` impl.
1936/// Pairs with `NullableDeserializeSeed` for oneof variants that don't
1937/// need a custom serde helper.
1938pub struct DefaultDeserializeSeed<T>(core::marker::PhantomData<T>);
1939
1940impl<T> DefaultDeserializeSeed<T> {
1941    pub fn new() -> Self {
1942        Self(core::marker::PhantomData)
1943    }
1944}
1945
1946impl<T> Default for DefaultDeserializeSeed<T> {
1947    fn default() -> Self {
1948        Self::new()
1949    }
1950}
1951
1952impl<'de, T: serde::Deserialize<'de>> serde::de::DeserializeSeed<'de>
1953    for DefaultDeserializeSeed<T>
1954{
1955    type Value = T;
1956    fn deserialize<D: serde::Deserializer<'de>>(self, d: D) -> Result<T, D::Error> {
1957        T::deserialize(d)
1958    }
1959}
1960
1961// ── message_field_always_present ──────────────────────────────────────────────
1962
1963/// Deserialize a `MessageField<T>` by always forwarding to `T::deserialize`,
1964/// including for JSON `null`.
1965///
1966/// Normally, `MessageField<T>::deserialize` delegates to `Option<T>`, which
1967/// maps `null` → `None` (field absent). For types like `google.protobuf.Value`
1968/// where `null` is a valid value (`NullValue`), this function ensures `null`
1969/// reaches `T::deserialize` and the field is set rather than absent.
1970pub fn message_field_always_present<'de, T, P, D>(
1971    d: D,
1972) -> Result<crate::MessageField<T, P>, D::Error>
1973where
1974    T: Default + serde::Deserialize<'de>,
1975    P: crate::ProtoBox<T>,
1976    D: serde::Deserializer<'de>,
1977{
1978    T::deserialize(d).map(crate::MessageField::some)
1979}
1980
1981// ── EnumProtoNameRef ──────────────────────────────────────────────────────────
1982
1983/// Helper to serialize a `&E` by its proto name string.
1984///
1985/// Used by `repeated_closed_enum` and `map_closed_enum` serialize functions
1986/// where elements need proto JSON encoding (name string, not integer).
1987pub(crate) struct EnumProtoNameRef<'a, E: crate::Enumeration>(pub &'a E);
1988
1989impl<E: crate::Enumeration> serde::Serialize for EnumProtoNameRef<'_, E> {
1990    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1991        s.serialize_str(self.0.proto_name())
1992    }
1993}
1994
1995// ── skip_if ───────────────────────────────────────────────────────────────────
1996
1997/// Predicates for `#[serde(skip_serializing_if = "...")]` on implicit-presence
1998/// fields.
1999///
2000/// Proto3 JSON omits such a field at its protobuf default. Generated
2001/// `Serialize` impls attach these to the matching field types.
2002pub mod skip_if {
2003    pub fn is_zero_i32(v: &i32) -> bool {
2004        *v == 0
2005    }
2006    pub fn is_zero_i64(v: &i64) -> bool {
2007        *v == 0
2008    }
2009    pub fn is_zero_u32(v: &u32) -> bool {
2010        *v == 0
2011    }
2012    pub fn is_zero_u64(v: &u64) -> bool {
2013        *v == 0
2014    }
2015    pub fn is_false(v: &bool) -> bool {
2016        !*v
2017    }
2018    /// Returns `true` only for `+0.0` (all bits clear). Returns `false` for
2019    /// `-0.0` and NaN, so both are serialized. Differs from `*v == 0.0`, which
2020    /// is also `true` for `-0.0`.
2021    pub fn is_zero_f32(v: &f32) -> bool {
2022        v.to_bits() == 0
2023    }
2024    /// Returns `true` only for `+0.0` (all bits clear), and `false` for `-0.0`
2025    /// and NaN.
2026    pub fn is_zero_f64(v: &f64) -> bool {
2027        v.to_bits() == 0
2028    }
2029    pub fn is_empty_str(v: &str) -> bool {
2030        v.is_empty()
2031    }
2032    pub fn is_empty_bytes(v: &[u8]) -> bool {
2033        v.is_empty()
2034    }
2035    pub fn is_empty_vec<T>(v: &[T]) -> bool {
2036        v.is_empty()
2037    }
2038    /// Empty-check for a non-default map collection (`BTreeMap` or a custom
2039    /// map) via the [`MapStorage`](crate::map_codec::MapStorage) surface, so the
2040    /// `skip_serializing_if` predicate works regardless of the concrete map
2041    /// type. The default `HashMap` map fields keep `HashMap::is_empty`, so their
2042    /// generated output is unchanged.
2043    pub fn is_empty_map<C>(m: &C) -> bool
2044    where
2045        C: crate::map_codec::MapStorage,
2046    {
2047        m.storage_len() == 0
2048    }
2049    pub fn is_unset_message_field<T: Default, P: crate::ProtoBox<T>>(
2050        v: &crate::MessageField<T, P>,
2051    ) -> bool {
2052        v.is_unset()
2053    }
2054    pub fn is_default_enum_value<E: crate::Enumeration>(v: &crate::EnumValue<E>) -> bool {
2055        v.to_i32() == 0
2056    }
2057    pub fn is_default_closed_enum<E: crate::Enumeration>(v: &E) -> bool {
2058        v.to_i32() == 0
2059    }
2060}
2061
2062// ── closed_enum: bare E with proto JSON handling ─────────────────────────────
2063
2064/// Serde with-module for singular closed enum fields (bare `E`).
2065///
2066/// Accepts JSON `null` as `E::default()`, string via `from_proto_name`,
2067/// and integer via `from_i32`. When `ignore_unknown_enum_values` is active,
2068/// unknown string values produce `E::default()` instead of an error.
2069pub mod closed_enum {
2070    use super::EnumJsonErrorReason;
2071    use serde::{Deserializer, Serializer};
2072
2073    pub fn serialize<E: crate::Enumeration, S: Serializer>(
2074        value: &E,
2075        s: S,
2076    ) -> Result<S::Ok, S::Error> {
2077        s.serialize_str(value.proto_name())
2078    }
2079
2080    pub fn deserialize<'de, E: crate::Enumeration + Default, D: Deserializer<'de>>(
2081        d: D,
2082    ) -> Result<E, D::Error> {
2083        deserialize_with_unknown_names(d, true)
2084    }
2085
2086    /// Standalone enum values always reject unknown names, even in lenient mode.
2087    #[doc(hidden)]
2088    pub fn deserialize_strict<'de, E: crate::Enumeration + Default, D: Deserializer<'de>>(
2089        d: D,
2090    ) -> Result<E, D::Error> {
2091        deserialize_with_unknown_names(d, false)
2092    }
2093
2094    fn deserialize_with_unknown_names<
2095        'de,
2096        E: crate::Enumeration + Default,
2097        D: Deserializer<'de>,
2098    >(
2099        d: D,
2100        allow_lenient: bool,
2101    ) -> Result<E, D::Error> {
2102        struct V<E> {
2103            allow_lenient: bool,
2104            marker: core::marker::PhantomData<E>,
2105        }
2106        impl<'de, E: crate::Enumeration + Default> serde::de::Visitor<'de> for V<E> {
2107            type Value = E;
2108            fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2109                f.write_str("a protobuf enum name string, integer value, or null")
2110            }
2111            fn visit_unit<Err>(self) -> Result<E, Err> {
2112                Ok(E::default())
2113            }
2114            fn visit_i64<Err: serde::de::Error>(self, v: i64) -> Result<E, Err> {
2115                let v32 =
2116                    i32::try_from(v).map_err(|_| Err::custom(EnumJsonErrorReason::OutOfRange))?;
2117                E::from_i32(v32).ok_or_else(|| Err::custom(EnumJsonErrorReason::UnknownNumber))
2118            }
2119            fn visit_u64<Err: serde::de::Error>(self, v: u64) -> Result<E, Err> {
2120                let v32 =
2121                    i32::try_from(v).map_err(|_| Err::custom(EnumJsonErrorReason::OutOfRange))?;
2122                E::from_i32(v32).ok_or_else(|| Err::custom(EnumJsonErrorReason::UnknownNumber))
2123            }
2124            fn visit_f64<Err: serde::de::Error>(self, _: f64) -> Result<E, Err> {
2125                Err(Err::custom(EnumJsonErrorReason::InvalidType))
2126            }
2127            fn visit_bool<Err: serde::de::Error>(self, _: bool) -> Result<E, Err> {
2128                Err(Err::custom(EnumJsonErrorReason::InvalidType))
2129            }
2130            #[cfg(feature = "zeroize")]
2131            fn visit_string<Err: serde::de::Error>(
2132                self,
2133                value: alloc::string::String,
2134            ) -> Result<E, Err> {
2135                // Only the owned-token callback transfers the allocation.
2136                // Borrowed text and parser scratch stay with the deserializer.
2137                let value = zeroize::Zeroizing::new(value);
2138                self.visit_str(&value)
2139            }
2140            fn visit_str<Err: serde::de::Error>(self, v: &str) -> Result<E, Err> {
2141                match E::from_proto_name(v) {
2142                    Some(e) => Ok(e),
2143                    None => {
2144                        if self.allow_lenient && crate::json::ignore_unknown_enum_values() {
2145                            return Ok(E::default());
2146                        }
2147                        Err(Err::custom(EnumJsonErrorReason::UnknownName))
2148                    }
2149                }
2150            }
2151        }
2152        d.deserialize_any(V {
2153            allow_lenient,
2154            marker: core::marker::PhantomData,
2155        })
2156    }
2157}
2158
2159// ── opt_closed_enum: Option<E> with unknown-value handling ───────────────────
2160
2161/// Serde with-module for `Option<E>` optional closed enum fields (proto2).
2162///
2163/// When `ignore_unknown_enum_values` is active, an unknown enum name, or a
2164/// number in `i32` range that the enum does not declare, produces `None`
2165/// (field not set) instead of an error.
2166pub mod opt_closed_enum {
2167    use serde::{Deserializer, Serializer};
2168
2169    pub fn serialize<E: crate::Enumeration, S: Serializer>(
2170        value: &Option<E>,
2171        s: S,
2172    ) -> Result<S::Ok, S::Error> {
2173        match value {
2174            Some(v) => s.serialize_str(v.proto_name()),
2175            None => s.serialize_none(),
2176        }
2177    }
2178
2179    pub fn deserialize<'de, E: crate::Enumeration + Default, D: Deserializer<'de>>(
2180        d: D,
2181    ) -> Result<Option<E>, D::Error> {
2182        let raw: Option<super::BufferedValue> = serde::Deserialize::deserialize(d)?;
2183        let raw = match raw {
2184            Some(super::BufferedValue(v)) => v,
2185            None => return Ok(None),
2186        };
2187
2188        super::try_deserialize_closed_enum::<E>(&raw).map_err(serde::de::Error::custom)
2189    }
2190}
2191
2192// ── repeated_closed_enum: Vec<E> with unknown-value filtering ────────────────
2193
2194/// Serde with-module for `Vec<E>` repeated closed enum fields, or any
2195/// collection that is `From<Vec<E>>`.
2196///
2197/// When `ignore_unknown_enum_values` is active, an unknown enum name, or a
2198/// number in `i32` range that the enum does not declare, is silently
2199/// skipped.
2200/// JSON null deserializes to an empty vec, but null elements are rejected.
2201pub mod repeated_closed_enum {
2202    use alloc::vec::Vec;
2203    use serde::{Deserializer, Serializer};
2204
2205    pub fn serialize<E: crate::Enumeration, S: Serializer>(
2206        value: &[E],
2207        s: S,
2208    ) -> Result<S::Ok, S::Error> {
2209        use serde::ser::SerializeSeq;
2210        let mut seq = s.serialize_seq(Some(value.len()))?;
2211        for v in value {
2212            seq.serialize_element(&crate::json_helpers::EnumProtoNameRef(v))?;
2213        }
2214        seq.end()
2215    }
2216
2217    pub fn deserialize<'de, E, C, D>(d: D) -> Result<C, D::Error>
2218    where
2219        E: crate::Enumeration + Default,
2220        C: From<Vec<E>>,
2221        D: Deserializer<'de>,
2222    {
2223        struct V<E>(core::marker::PhantomData<E>);
2224        impl<'de, E: crate::Enumeration + Default> serde::de::Visitor<'de> for V<E> {
2225            type Value = Vec<E>;
2226
2227            fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2228                f.write_str("a list of enum values or null")
2229            }
2230
2231            fn visit_unit<Err>(self) -> Result<Vec<E>, Err> {
2232                Ok(Vec::new())
2233            }
2234
2235            fn visit_seq<A: serde::de::SeqAccess<'de>>(
2236                self,
2237                mut seq: A,
2238            ) -> Result<Vec<E>, A::Error> {
2239                let mut out = Vec::with_capacity(super::clamp_size_hint(seq.size_hint()));
2240                while let Some(super::BufferedValue(raw)) = seq.next_element()? {
2241                    match super::try_deserialize_closed_enum::<E>(&raw) {
2242                        Ok(Some(v)) => out.push(v),
2243                        Ok(None) => continue,
2244                        Err(e) => return Err(serde::de::Error::custom(e)),
2245                    }
2246                }
2247                Ok(out)
2248            }
2249        }
2250        d.deserialize_any(V::<E>(core::marker::PhantomData))
2251            .map(C::from)
2252    }
2253}
2254
2255// ── map_closed_enum: HashMap<K, E> with unknown-value filtering ──────────────
2256
2257/// Serde with-module for `HashMap<K, E>` map fields where the value is a
2258/// closed enum type.
2259///
2260/// When `ignore_unknown_enum_values` is active, map entries whose value is
2261/// an unknown enum name, or a number in `i32` range that the enum does not
2262/// declare, are silently dropped.
2263/// JSON null deserializes to an empty map, but null values are rejected.
2264pub mod map_closed_enum {
2265    use crate::map_codec::MapStorage;
2266    use serde::{Deserializer, Serializer};
2267
2268    pub fn serialize<C, S>(value: &C, s: S) -> Result<S::Ok, S::Error>
2269    where
2270        C: MapStorage,
2271        C::Key: serde::Serialize,
2272        C::Value: crate::Enumeration,
2273        S: Serializer,
2274    {
2275        use serde::ser::SerializeMap;
2276        let mut map = s.serialize_map(Some(value.storage_len()))?;
2277        for (k, v) in value.storage_iter() {
2278            map.serialize_entry(k, &crate::json_helpers::EnumProtoNameRef(v))?;
2279        }
2280        map.end()
2281    }
2282
2283    pub fn deserialize<'de, C, D>(d: D) -> Result<C, D::Error>
2284    where
2285        C: MapStorage + Default,
2286        C::Key: serde::Deserialize<'de>,
2287        C::Value: crate::Enumeration + Default,
2288        D: Deserializer<'de>,
2289    {
2290        struct V<C>(core::marker::PhantomData<C>);
2291        impl<'de, C> serde::de::Visitor<'de> for V<C>
2292        where
2293            C: MapStorage + Default,
2294            C::Key: serde::Deserialize<'de>,
2295            C::Value: crate::Enumeration + Default,
2296        {
2297            type Value = C;
2298
2299            fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2300                f.write_str("a map with enum values or null")
2301            }
2302
2303            fn visit_unit<Err>(self) -> Result<Self::Value, Err> {
2304                Ok(C::default())
2305            }
2306
2307            fn visit_map<A: serde::de::MapAccess<'de>>(
2308                self,
2309                mut map: A,
2310            ) -> Result<Self::Value, A::Error> {
2311                let mut out = C::default();
2312                while let Some(key) = map.next_key::<C::Key>()? {
2313                    let key = crate::erasing::Erasing::new(key, C::storage_erase_key);
2314                    let super::BufferedValue(raw) = map.next_value()?;
2315                    match super::try_deserialize_closed_enum::<C::Value>(&raw) {
2316                        Ok(Some(v)) => {
2317                            out.storage_insert(key.into_inner(), v);
2318                        }
2319                        Ok(None) => continue,
2320                        Err(e) => return Err(serde::de::Error::custom(e)),
2321                    }
2322                }
2323                Ok(out)
2324            }
2325        }
2326        d.deserialize_any(V::<C>(core::marker::PhantomData))
2327    }
2328}
2329
2330// ── tests ─────────────────────────────────────────────────────────────────────
2331
2332#[cfg(test)]
2333mod tests;
2334
2335/// Enum collection decoding without intermediate owned containers.
2336pub mod enum_list;
2337/// Streaming enum helpers for cleanup-enabled generated messages.
2338#[doc(hidden)]
2339#[cfg(feature = "zeroize")]
2340pub mod guarded_enum;
2341#[cfg(feature = "zeroize")]
2342mod guarded_key;
2343/// Direct-key map decoding for cleanup-enabled generated messages.
2344#[doc(hidden)]
2345#[cfg(feature = "zeroize")]
2346pub mod guarded_map;