1pub mod buffered;
36mod ignored_key;
37mod map_key;
38mod policy;
39pub mod proto_list;
40#[doc(hidden)]
41pub use ignored_key::IgnoredObjectKey;
42#[doc(hidden)]
43pub mod wkt;
44
45#[doc(hidden)]
46pub use policy::{
47 bytes_policy, list_bytes_policy, list_string_policy, map_bytes_policy,
48 map_bytes_policy_bytes_key, map_bytes_policy_policy_key, map_bytes_policy_serde_key,
49 map_string_policy, map_string_policy_bytes_key, map_string_policy_policy_key,
50 map_string_policy_serde_key, opt_bytes_policy, opt_string_policy, policy_str_key_map,
51 repeated_bytes_policy, repeated_string_policy, string_policy, BytesPolicyJson, BytesPolicySeed,
52 BytesPolicySeqJson, StringPolicyJson, StringPolicySeed, StringPolicySeqJson,
53 ViewJsonErrorReason,
54};
55pub use policy::{ProtoBytesJson, ProtoStringJson};
56
57use buffered::BufferedValue;
58
59#[doc(hidden)]
68pub fn deserialize_tagged<'de, V, A>(visitor: V, tagged: A) -> Result<V::Value, A::Error>
69where
70 V: serde::de::Visitor<'de>,
71 A: serde::de::EnumAccess<'de>,
72{
73 struct Seed<V>(V);
74 impl<'de, V: serde::de::Visitor<'de>> serde::de::DeserializeSeed<'de> for Seed<V> {
75 type Value = V::Value;
76 fn deserialize<D: serde::Deserializer<'de>>(self, d: D) -> Result<V::Value, D::Error> {
77 d.deserialize_any(self.0)
78 }
79 }
80 let (_, variant) = tagged.variant::<serde::de::IgnoredAny>()?;
81 serde::de::VariantAccess::newtype_variant_seed(variant, Seed(visitor))
82}
83
84#[doc(hidden)]
88#[derive(Clone, Copy, Debug, thiserror::Error)]
89#[non_exhaustive]
90pub enum JsonValueError {
91 #[error("invalid protobuf map key")]
92 MapKey,
93 #[error("invalid i32 value")]
94 Int32,
95 #[error("invalid u32 value")]
96 Uint32,
97 #[error("invalid i64 value")]
98 Int64,
99 #[error("invalid u64 value")]
100 Uint64,
101 #[error("invalid float value, expected a finite f32 or a protobuf special value")]
102 Float,
103 #[error("invalid double value, expected a finite f64 or a protobuf special value")]
104 Double,
105 #[error("invalid base64 string")]
106 Base64,
107 #[error("invalid Duration string")]
108 Duration,
109 #[error("invalid RFC 3339 timestamp")]
110 Timestamp,
111 #[error("invalid FieldMask path, expected comma-separated lowerCamelCase paths")]
112 FieldMask,
113 #[error("invalid FieldMask path, it has no proto3 JSON representation")]
114 FieldMaskEncode,
115 #[error("invalid JSON payload for a registered Any message")]
116 AnyMessage,
117 #[error("invalid JSON value for a registered Any well-known type")]
118 AnyWellKnownType,
119 #[error("@type is not a valid type URL: it names no type")]
120 AnyEmptyType,
121 #[error("@type must contain a '/' (e.g. type.googleapis.com/pkg.Type)")]
122 AnyBareType,
123 #[error("Any with a well-known type requires a \"value\" key")]
124 AnyMissingValue,
125 #[error("Any with a well-known type has an unexpected field")]
126 AnyUnexpectedField,
127 #[error("Any type is not registered in the descriptor pool")]
128 AnyUnregisteredType,
129 #[error("Any: no type registry is installed to resolve a bare @type; install one with `set_type_registry`, or send a type URL")]
130 AnyBareTypeWithoutRegistry,
131 #[error("Any: bare @type has no JSON entry in the type registry; register the message or send a type URL")]
132 AnyBareTypeWithoutEntry,
133 #[error("Any: no type registry is installed; send the message encoded as a base64 string under \"value\", or install a registry with `set_type_registry`")]
134 AnyOpaqueWithoutRegistry,
135 #[error("Any: type has no JSON entry in the type registry; send the message encoded as a base64 string under \"value\", or register the message with `register_types`")]
136 AnyOpaqueWithoutEntry,
137 #[error("Any opaque payload field cannot be parsed")]
138 AnyOpaqueField,
139}
140
141#[doc(hidden)]
175#[macro_export]
176macro_rules! __buffa_reject_other_json_kinds {
177 ($($kind:ident),* $(,)?) => {
178 $($crate::__buffa_reject_other_json_kinds!(@kind $kind);)*
179 };
180 (@kind bool) => {
181 fn visit_bool<__E: ::serde::de::Error>(
182 self,
183 _: ::core::primitive::bool,
184 ) -> ::core::result::Result<Self::Value, __E> {
185 ::core::result::Result::Err(__E::invalid_type(
186 ::serde::de::Unexpected::Other("boolean"),
187 &self,
188 ))
189 }
190 };
191 (@kind i64) => {
192 fn visit_i64<__E: ::serde::de::Error>(
193 self,
194 _: ::core::primitive::i64,
195 ) -> ::core::result::Result<Self::Value, __E> {
196 ::core::result::Result::Err(__E::invalid_type(
197 ::serde::de::Unexpected::Other("integer"),
198 &self,
199 ))
200 }
201 };
202 (@kind u64) => {
203 fn visit_u64<__E: ::serde::de::Error>(
204 self,
205 _: ::core::primitive::u64,
206 ) -> ::core::result::Result<Self::Value, __E> {
207 ::core::result::Result::Err(__E::invalid_type(
208 ::serde::de::Unexpected::Other("integer"),
209 &self,
210 ))
211 }
212 };
213 (@kind i128) => {
214 fn visit_i128<__E: ::serde::de::Error>(
215 self,
216 value: ::core::primitive::i128,
217 ) -> ::core::result::Result<Self::Value, __E> {
218 if let ::core::result::Result::Ok(value) = <::core::primitive::i64 as ::core::convert::TryFrom<::core::primitive::i128>>::try_from(value) {
219 return ::serde::de::Visitor::visit_i64(self, value);
220 }
221 if let ::core::result::Result::Ok(value) = <::core::primitive::u64 as ::core::convert::TryFrom<::core::primitive::i128>>::try_from(value) {
222 return ::serde::de::Visitor::visit_u64(self, value);
223 }
224 ::core::result::Result::Err(__E::invalid_type(
225 ::serde::de::Unexpected::Other("integer"),
226 &self,
227 ))
228 }
229 };
230 (@kind u128) => {
231 fn visit_u128<__E: ::serde::de::Error>(
232 self,
233 value: ::core::primitive::u128,
234 ) -> ::core::result::Result<Self::Value, __E> {
235 if let ::core::result::Result::Ok(value) = <::core::primitive::u64 as ::core::convert::TryFrom<::core::primitive::u128>>::try_from(value) {
236 return ::serde::de::Visitor::visit_u64(self, value);
237 }
238 ::core::result::Result::Err(__E::invalid_type(
239 ::serde::de::Unexpected::Other("integer"),
240 &self,
241 ))
242 }
243 };
244 (@kind f64) => {
245 fn visit_f64<__E: ::serde::de::Error>(
246 self,
247 _: ::core::primitive::f64,
248 ) -> ::core::result::Result<Self::Value, __E> {
249 ::core::result::Result::Err(__E::invalid_type(
250 ::serde::de::Unexpected::Other("floating-point number"),
251 &self,
252 ))
253 }
254 };
255 (@kind str) => {
256 fn visit_str<__E: ::serde::de::Error>(
257 self,
258 _: &::core::primitive::str,
259 ) -> ::core::result::Result<Self::Value, __E> {
260 ::core::result::Result::Err(__E::invalid_type(
261 ::serde::de::Unexpected::Other("string"),
262 &self,
263 ))
264 }
265 };
266 (@kind string) => {
267 fn visit_string<__E: ::serde::de::Error>(
268 self,
269 value: $crate::alloc::string::String,
270 ) -> ::core::result::Result<Self::Value, __E> {
271 $crate::json_helpers::discard_rejected_text(value);
272 ::core::result::Result::Err(__E::invalid_type(
273 ::serde::de::Unexpected::Other("string"),
274 &self,
275 ))
276 }
277 };
278 (@kind bytes) => {
279 fn visit_bytes<__E: ::serde::de::Error>(
280 self,
281 _: &[::core::primitive::u8],
282 ) -> ::core::result::Result<Self::Value, __E> {
283 ::core::result::Result::Err(__E::invalid_type(
284 ::serde::de::Unexpected::Other("bytes"),
285 &self,
286 ))
287 }
288 };
289 (@kind byte_buf) => {
290 fn visit_byte_buf<__E: ::serde::de::Error>(
291 self,
292 value: $crate::alloc::vec::Vec<::core::primitive::u8>,
293 ) -> ::core::result::Result<Self::Value, __E> {
294 $crate::json_helpers::discard_rejected_bytes(value);
295 ::core::result::Result::Err(__E::invalid_type(
296 ::serde::de::Unexpected::Other("bytes"),
297 &self,
298 ))
299 }
300 };
301 (@kind unit) => {
302 fn visit_unit<__E: ::serde::de::Error>(self) -> ::core::result::Result<Self::Value, __E> {
303 ::core::result::Result::Err(__E::invalid_type(
304 ::serde::de::Unexpected::Other("null"),
305 &self,
306 ))
307 }
308 };
309 (@kind seq) => {
310 fn visit_seq<__A: ::serde::de::SeqAccess<'de>>(
311 self,
312 _: __A,
313 ) -> ::core::result::Result<Self::Value, __A::Error> {
314 ::core::result::Result::Err(<__A::Error as ::serde::de::Error>::invalid_type(
315 ::serde::de::Unexpected::Other("array"),
316 &self,
317 ))
318 }
319 };
320 (@kind map) => {
321 fn visit_map<__A: ::serde::de::MapAccess<'de>>(
322 self,
323 _: __A,
324 ) -> ::core::result::Result<Self::Value, __A::Error> {
325 ::core::result::Result::Err(<__A::Error as ::serde::de::Error>::invalid_type(
326 ::serde::de::Unexpected::Other("object"),
327 &self,
328 ))
329 }
330 };
331}
332#[doc(hidden)]
333pub use crate::__buffa_reject_other_json_kinds as reject_other_json_kinds;
334
335#[doc(hidden)]
337pub fn discard_rejected_text(text: alloc::string::String) {
338 discard_rejected_bytes(text.into_bytes());
339}
340
341#[doc(hidden)]
343pub fn discard_rejected_bytes(bytes: alloc::vec::Vec<u8>) {
344 #[cfg(feature = "zeroize")]
345 {
346 let mut bytes = bytes;
347 zeroize::Zeroize::zeroize(&mut bytes);
348 }
349 #[cfg(not(feature = "zeroize"))]
350 drop(bytes);
351}
352
353#[doc(hidden)]
361pub const SERDE_JSON_NUMBER_KEY: &str = "$serde_json::private::Number";
362
363macro_rules! visit_wide_ints {
367 ($reason:expr) => {
368 fn visit_i128<E: serde::de::Error>(self, v: i128) -> Result<Self::Value, E> {
369 if let Ok(v) = i64::try_from(v) {
370 return serde::de::Visitor::visit_i64(self, v);
371 }
372 match u64::try_from(v) {
373 Ok(v) => serde::de::Visitor::visit_u64(self, v),
374 Err(_) => Err(E::custom($reason)),
375 }
376 }
377 fn visit_u128<E: serde::de::Error>(self, v: u128) -> Result<Self::Value, E> {
378 match u64::try_from(v) {
379 Ok(v) => serde::de::Visitor::visit_u64(self, v),
380 Err(_) => Err(E::custom($reason)),
381 }
382 }
383 };
384}
385
386use base64::alphabet;
394use base64::engine::{
395 general_purpose::STANDARD, DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig,
396};
397
398const LENIENT_CFG: GeneralPurposeConfig = GeneralPurposeConfig::new()
399 .with_decode_allow_trailing_bits(true)
400 .with_decode_padding_mode(DecodePaddingMode::Indifferent);
401
402static STANDARD_LENIENT: GeneralPurpose = GeneralPurpose::new(&alphabet::STANDARD, LENIENT_CFG);
403static URL_SAFE_LENIENT: GeneralPurpose = GeneralPurpose::new(&alphabet::URL_SAFE, LENIENT_CFG);
404
405const MAX_PREALLOC_HINT: usize = 4096;
413
414#[inline]
416fn clamp_size_hint(hint: Option<usize>) -> usize {
417 hint.unwrap_or(0).min(MAX_PREALLOC_HINT)
418}
419
420pub trait ProtoElemJson: Sized {
444 fn serialize_proto_json<S: serde::Serializer>(v: &Self, s: S) -> Result<S::Ok, S::Error>;
446 fn deserialize_proto_json<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error>;
448 fn deserialize_proto_json_null<E: serde::de::Error>() -> Result<Self, E> {
452 Err(E::custom(
453 "null is not a valid repeated-field element or map value",
454 ))
455 }
456}
457
458#[doc(hidden)]
469pub struct ProtoJson<'a, T>(pub &'a T);
470impl<T: ProtoElemJson> serde::Serialize for ProtoJson<'_, T> {
471 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
472 T::serialize_proto_json(self.0, s)
473 }
474}
475
476#[doc(hidden)]
480pub struct BytesJson<'a>(pub &'a [u8]);
481impl serde::Serialize for BytesJson<'_> {
482 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
483 bytes::serialize(self.0, s)
484 }
485}
486
487#[doc(hidden)]
489pub struct ClosedEnumJson<'a, E>(pub &'a E);
490impl<E: crate::Enumeration> serde::Serialize for ClosedEnumJson<'_, E> {
491 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
492 closed_enum::serialize(self.0, s)
493 }
494}
495
496#[doc(hidden)]
499pub struct MapKeyJson<'a, T: ?Sized>(pub &'a T);
500impl<T: ?Sized + core::fmt::Display> serde::Serialize for MapKeyJson<'_, T> {
501 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
502 s.collect_str(self.0)
503 }
504}
505
506#[doc(hidden)]
508pub struct RepeatedJson<'a, T>(pub &'a [T]);
509impl<T: ProtoElemJson> serde::Serialize for RepeatedJson<'_, T> {
510 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
511 proto_seq::serialize(self.0, s)
512 }
513}
514
515#[doc(hidden)]
517pub struct BytesSeqJson<'a>(pub &'a [&'a [u8]]);
518impl serde::Serialize for BytesSeqJson<'_> {
519 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
520 use serde::ser::SerializeSeq;
521 let mut seq = s.serialize_seq(Some(self.0.len()))?;
522 for v in self.0 {
523 seq.serialize_element(&BytesJson(v))?;
524 }
525 seq.end()
526 }
527}
528
529#[doc(hidden)]
531pub struct EnumSeqJson<'a, E: crate::Enumeration>(pub &'a [crate::EnumValue<E>]);
532impl<E: crate::Enumeration> serde::Serialize for EnumSeqJson<'_, E> {
533 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
534 repeated_enum::serialize(self.0, s)
535 }
536}
537
538#[doc(hidden)]
540pub struct ClosedEnumSeqJson<'a, E>(pub &'a [E]);
541impl<E: crate::Enumeration> serde::Serialize for ClosedEnumSeqJson<'_, E> {
542 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
543 repeated_closed_enum::serialize(self.0, s)
544 }
545}
546
547struct ProtoElemSeed<T>(core::marker::PhantomData<T>);
556impl<'de, T: ProtoElemJson> serde::de::DeserializeSeed<'de> for ProtoElemSeed<T> {
557 type Value = T;
558 fn deserialize<D: serde::Deserializer<'de>>(self, d: D) -> Result<T, D::Error> {
559 struct NoNull<T>(core::marker::PhantomData<T>);
562 impl<'de, T: ProtoElemJson> serde::de::Visitor<'de> for NoNull<T> {
563 type Value = T;
564 fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
565 f.write_str("a non-null value")
566 }
567 fn visit_none<E: serde::de::Error>(self) -> Result<T, E> {
568 T::deserialize_proto_json_null()
569 }
570 fn visit_unit<E: serde::de::Error>(self) -> Result<T, E> {
571 T::deserialize_proto_json_null()
572 }
573 fn visit_some<D2: serde::Deserializer<'de>>(self, d: D2) -> Result<T, D2::Error> {
574 T::deserialize_proto_json(d)
575 }
576 crate::reject_other_json_kinds!(
577 bool, i64, u64, i128, u128, f64, str, string, bytes, byte_buf
578 );
579 }
580 d.deserialize_option(NoNull::<T>(core::marker::PhantomData))
581 }
582}
583
584macro_rules! proto_elem_json_delegate {
590 ($ty:ty, $mod:ident, null = $expected:literal) => {
591 impl ProtoElemJson for $ty {
592 fn serialize_proto_json<S: serde::Serializer>(
593 v: &Self,
594 s: S,
595 ) -> Result<S::Ok, S::Error> {
596 $mod::serialize(v, s)
597 }
598 fn deserialize_proto_json<'de, D: serde::Deserializer<'de>>(
599 d: D,
600 ) -> Result<Self, D::Error> {
601 $mod::deserialize(d)
602 }
603 fn deserialize_proto_json_null<E: serde::de::Error>() -> Result<Self, E> {
606 Err(E::invalid_type(serde::de::Unexpected::Unit, &$expected))
607 }
608 }
609 };
610 ($ty:ty, $mod:ident) => {
611 impl ProtoElemJson for $ty {
612 fn serialize_proto_json<S: serde::Serializer>(
613 v: &Self,
614 s: S,
615 ) -> Result<S::Ok, S::Error> {
616 $mod::serialize(v, s)
617 }
618 fn deserialize_proto_json<'de, D: serde::Deserializer<'de>>(
619 d: D,
620 ) -> Result<Self, D::Error> {
621 $mod::deserialize(d)
622 }
623 }
624 };
625}
626
627pub mod proto_seq {
639 use super::{ProtoElemJson, ProtoElemSeed, ProtoJson};
640 use alloc::vec::Vec;
641 use serde::{Deserializer, Serializer};
642
643 pub fn serialize<T: ProtoElemJson, S: Serializer>(v: &[T], s: S) -> Result<S::Ok, S::Error> {
644 use serde::ser::SerializeSeq;
645 let mut seq = s.serialize_seq(Some(v.len()))?;
646 for elem in v {
647 seq.serialize_element(&ProtoJson(elem))?;
648 }
649 seq.end()
650 }
651
652 pub fn deserialize<'de, T, C, D>(d: D) -> Result<C, D::Error>
653 where
654 T: ProtoElemJson,
655 C: From<Vec<T>>,
656 D: Deserializer<'de>,
657 {
658 struct V<T>(core::marker::PhantomData<T>);
659 impl<'de, T: ProtoElemJson> serde::de::Visitor<'de> for V<T> {
660 type Value = Vec<T>;
661 fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
662 f.write_str("an array or null")
663 }
664 fn visit_enum<A: serde::de::EnumAccess<'de>>(
665 self,
666 tagged: A,
667 ) -> Result<Self::Value, A::Error> {
668 super::deserialize_tagged(self, tagged)
669 }
670 fn visit_unit<E>(self) -> Result<Vec<T>, E> {
671 Ok(Vec::new())
672 }
673 crate::reject_other_json_kinds!(
674 bool, i64, u64, i128, u128, f64, str, string, bytes, byte_buf
675 );
676 fn visit_seq<A: serde::de::SeqAccess<'de>>(
677 self,
678 mut seq: A,
679 ) -> Result<Vec<T>, A::Error> {
680 let mut out = Vec::with_capacity(super::clamp_size_hint(seq.size_hint()));
681 while let Some(elem) =
682 seq.next_element_seed(ProtoElemSeed::<T>(core::marker::PhantomData))?
683 {
684 out.push(elem);
685 }
686 Ok(out)
687 }
688 }
689 d.deserialize_any(V::<T>(core::marker::PhantomData))
690 .map(C::from)
691 }
692}
693
694struct DisplayKey<'a, K: ?Sized>(&'a K);
701impl<K: core::fmt::Display + ?Sized> serde::Serialize for DisplayKey<'_, K> {
702 #[inline]
703 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
704 s.collect_str(self.0)
705 }
706}
707
708#[doc(hidden)]
712pub mod native_seq {
713 pub fn serialize<C: serde::Serialize, S: serde::Serializer>(
716 v: &C,
717 s: S,
718 ) -> Result<S::Ok, S::Error> {
719 serde::Serialize::serialize(v, s)
720 }
721
722 pub fn deserialize<'de, T, C, D>(d: D) -> Result<C, D::Error>
723 where
724 T: super::ProtoElemJson,
725 C: From<alloc::vec::Vec<T>> + serde::Deserialize<'de> + Default,
726 D: serde::Deserializer<'de>,
727 {
728 if d.is_human_readable() {
729 super::proto_seq::deserialize(d)
730 } else {
731 super::null_as_default(d)
732 }
733 }
734}
735
736#[doc(hidden)]
738pub mod native_str_key_map {
739 pub fn serialize<C: serde::Serialize, S: serde::Serializer>(
740 v: &C,
741 s: S,
742 ) -> Result<S::Ok, S::Error> {
743 serde::Serialize::serialize(v, s)
744 }
745
746 pub fn deserialize<'de, C, D>(d: D) -> Result<C, D::Error>
747 where
748 C: crate::map_codec::MapStorage + serde::Deserialize<'de> + Default,
749 C::Key: serde::Deserialize<'de>,
750 C::Value: super::ProtoElemJson,
751 D: serde::Deserializer<'de>,
752 {
753 if d.is_human_readable() {
754 super::proto_str_key_map::deserialize(d)
755 } else {
756 super::null_as_default(d)
757 }
758 }
759}
760
761pub mod proto_map {
773 use super::{ProtoElemJson, ProtoElemSeed, ProtoJson};
774 use crate::map_codec::MapStorage;
775 use alloc::string::String;
776 use core::fmt::Display;
777 use core::str::FromStr;
778 use serde::{Deserializer, Serializer};
779
780 pub fn serialize<C, S>(m: &C, s: S) -> Result<S::Ok, S::Error>
781 where
782 C: MapStorage,
783 C::Key: Display,
784 C::Value: ProtoElemJson,
785 S: Serializer,
786 {
787 use serde::ser::SerializeMap;
788 let mut map = s.serialize_map(Some(m.storage_len()))?;
789 for (k, v) in m.storage_iter() {
790 map.serialize_entry(&super::DisplayKey(k), &ProtoJson(v))?;
791 }
792 map.end()
793 }
794
795 pub fn deserialize<'de, C, D>(d: D) -> Result<C, D::Error>
796 where
797 C: MapStorage + Default,
798 C::Key: FromStr,
799 C::Value: ProtoElemJson,
800 D: Deserializer<'de>,
801 {
802 struct Vis<C>(core::marker::PhantomData<C>);
803 impl<'de, C> serde::de::Visitor<'de> for Vis<C>
804 where
805 C: MapStorage + Default,
806 C::Key: FromStr,
807 C::Value: ProtoElemJson,
808 {
809 type Value = C;
810 fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
811 f.write_str("a JSON object with string keys, or null")
812 }
813 fn visit_unit<E>(self) -> Result<Self::Value, E> {
814 Ok(C::default())
815 }
816 crate::reject_other_json_kinds!(
817 bool, i64, u64, i128, u128, f64, str, string, bytes, byte_buf
818 );
819 fn visit_map<A: serde::de::MapAccess<'de>>(
820 self,
821 mut map: A,
822 ) -> Result<Self::Value, A::Error> {
823 let mut out = C::default();
824 while let Some(key) = map.next_key::<String>()? {
825 let k = <C::Key as FromStr>::from_str(&key)
826 .map_err(|_| serde::de::Error::custom(super::JsonValueError::MapKey))?;
827 let k = crate::erasing::Erasing::new(k, C::storage_erase_key);
828 let v =
829 map.next_value_seed(ProtoElemSeed::<C::Value>(core::marker::PhantomData))?;
830 out.storage_insert(k.into_inner(), v);
831 }
832 Ok(out)
833 }
834 }
835 d.deserialize_any(Vis::<C>(core::marker::PhantomData))
836 }
837}
838
839pub mod proto_str_key_map {
853 use super::{ProtoElemJson, ProtoElemSeed, ProtoJson};
854 use crate::map_codec::MapStorage;
855 use serde::{Deserializer, Serializer};
856
857 pub fn serialize<C, S>(m: &C, s: S) -> Result<S::Ok, S::Error>
858 where
859 C: MapStorage,
860 C::Key: serde::Serialize,
861 C::Value: ProtoElemJson,
862 S: Serializer,
863 {
864 use serde::ser::SerializeMap;
865 let mut map = s.serialize_map(Some(m.storage_len()))?;
866 for (k, v) in m.storage_iter() {
867 map.serialize_entry(k, &ProtoJson(v))?;
868 }
869 map.end()
870 }
871
872 pub fn deserialize<'de, C, D>(d: D) -> Result<C, D::Error>
873 where
874 C: MapStorage + Default,
875 C::Key: serde::Deserialize<'de>,
876 C::Value: ProtoElemJson,
877 D: Deserializer<'de>,
878 {
879 struct Vis<C>(core::marker::PhantomData<C>);
880 impl<'de, C> serde::de::Visitor<'de> for Vis<C>
881 where
882 C: MapStorage + Default,
883 C::Key: serde::Deserialize<'de>,
884 C::Value: ProtoElemJson,
885 {
886 type Value = C;
887 fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
888 f.write_str("a JSON object with string keys, or null")
889 }
890 fn visit_enum<A: serde::de::EnumAccess<'de>>(
891 self,
892 tagged: A,
893 ) -> Result<Self::Value, A::Error> {
894 super::deserialize_tagged(self, tagged)
895 }
896 fn visit_unit<E>(self) -> Result<Self::Value, E> {
897 Ok(C::default())
898 }
899 crate::reject_other_json_kinds!(
900 bool, i64, u64, i128, u128, f64, str, string, bytes, byte_buf
901 );
902 fn visit_map<A: serde::de::MapAccess<'de>>(
903 self,
904 mut map: A,
905 ) -> Result<Self::Value, A::Error> {
906 let mut out = C::default();
907 while let Some(k) = map.next_key::<C::Key>()? {
908 let k = crate::erasing::Erasing::new(k, C::storage_erase_key);
909 let v =
910 map.next_value_seed(ProtoElemSeed::<C::Value>(core::marker::PhantomData))?;
911 out.storage_insert(k.into_inner(), v);
912 }
913 Ok(out)
914 }
915 }
916 d.deserialize_any(Vis::<C>(core::marker::PhantomData))
917 }
918}
919
920pub mod proto_bool {
926 use serde::{Deserializer, Serializer};
927
928 pub fn serialize<S: Serializer>(value: &bool, s: S) -> Result<S::Ok, S::Error> {
929 s.serialize_bool(*value)
930 }
931
932 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<bool, D::Error> {
933 struct V;
934 impl<'de> serde::de::Visitor<'de> for V {
935 type Value = bool;
936 fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
937 f.write_str("a boolean or null")
938 }
939 fn visit_unit<E>(self) -> Result<bool, E> {
940 Ok(false)
941 }
942 fn visit_bool<E>(self, v: bool) -> Result<bool, E> {
943 Ok(v)
944 }
945 crate::reject_other_json_kinds!(
946 i64, u64, i128, u128, f64, str, string, bytes, byte_buf
947 );
948 }
949 d.deserialize_any(V)
950 }
951}
952
953pub mod proto_string {
959 use serde::{Deserializer, Serializer};
960
961 pub fn serialize<T: AsRef<str> + ?Sized, S: Serializer>(
968 value: &T,
969 s: S,
970 ) -> Result<S::Ok, S::Error> {
971 s.serialize_str(value.as_ref())
972 }
973
974 pub fn deserialize<'de, T, D>(d: D) -> Result<T, D::Error>
985 where
986 T: crate::ProtoString,
987 D: Deserializer<'de>,
988 {
989 struct V<T>(core::marker::PhantomData<T>);
990 impl<'de, T> serde::de::Visitor<'de> for V<T>
991 where
992 T: crate::ProtoString,
993 {
994 type Value = T;
995 fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
996 f.write_str("a string or null")
997 }
998 fn visit_unit<E>(self) -> Result<T, E> {
999 Ok(T::copy_from_str(""))
1000 }
1001 fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<T, E> {
1002 Ok(T::copy_from_str(v))
1003 }
1004 fn visit_string<E>(self, v: alloc::string::String) -> Result<T, E> {
1005 Ok(T::from(v))
1006 }
1007 crate::reject_other_json_kinds!(bool, i64, u64, i128, u128, f64, bytes, byte_buf);
1008 }
1009 d.deserialize_any(V::<T>(core::marker::PhantomData))
1010 }
1011}
1012
1013#[doc(hidden)]
1019#[derive(Clone, Copy, Debug, thiserror::Error)]
1020#[non_exhaustive]
1021pub enum EnumJsonErrorReason {
1022 #[error("unknown enum name")]
1023 UnknownName,
1024 #[error("unknown enum number")]
1025 UnknownNumber,
1026 #[error("enum number out of i32 range")]
1027 OutOfRange,
1028 #[error("expected a protobuf enum name or integer")]
1029 InvalidType,
1030 #[error("expected a protobuf list or null")]
1031 InvalidListType,
1032 #[error("expected a protobuf map or null")]
1033 InvalidMapType,
1034}
1035
1036macro_rules! reject_container_scalar_values {
1038 ($reason:ident) => {
1039 fn visit_string<Err: serde::de::Error>(
1040 self,
1041 value: alloc::string::String,
1042 ) -> Result<Self::Value, Err> {
1043 crate::json_helpers::discard_rejected_text(value);
1044 Err(Err::custom(
1045 crate::json_helpers::EnumJsonErrorReason::$reason,
1046 ))
1047 }
1048 fn visit_str<Err: serde::de::Error>(self, _: &str) -> Result<Self::Value, Err> {
1049 Err(Err::custom(
1050 crate::json_helpers::EnumJsonErrorReason::$reason,
1051 ))
1052 }
1053 fn visit_i64<Err: serde::de::Error>(self, _: i64) -> Result<Self::Value, Err> {
1054 Err(Err::custom(
1055 crate::json_helpers::EnumJsonErrorReason::$reason,
1056 ))
1057 }
1058 fn visit_u64<Err: serde::de::Error>(self, _: u64) -> Result<Self::Value, Err> {
1059 Err(Err::custom(
1060 crate::json_helpers::EnumJsonErrorReason::$reason,
1061 ))
1062 }
1063 fn visit_i128<Err: serde::de::Error>(self, _: i128) -> Result<Self::Value, Err> {
1064 Err(Err::custom(
1065 crate::json_helpers::EnumJsonErrorReason::$reason,
1066 ))
1067 }
1068 fn visit_u128<Err: serde::de::Error>(self, _: u128) -> Result<Self::Value, Err> {
1069 Err(Err::custom(
1070 crate::json_helpers::EnumJsonErrorReason::$reason,
1071 ))
1072 }
1073 fn visit_f64<Err: serde::de::Error>(self, _: f64) -> Result<Self::Value, Err> {
1074 Err(Err::custom(
1075 crate::json_helpers::EnumJsonErrorReason::$reason,
1076 ))
1077 }
1078 fn visit_bool<Err: serde::de::Error>(self, _: bool) -> Result<Self::Value, Err> {
1079 Err(Err::custom(
1080 crate::json_helpers::EnumJsonErrorReason::$reason,
1081 ))
1082 }
1083 };
1084}
1085
1086pub mod proto_enum {
1090 use super::EnumJsonErrorReason;
1091 use serde::{Deserializer, Serializer};
1092
1093 pub fn serialize<E: crate::Enumeration, S: Serializer>(
1094 value: &crate::EnumValue<E>,
1095 s: S,
1096 ) -> Result<S::Ok, S::Error> {
1097 serde::Serialize::serialize(value, s)
1098 }
1099
1100 pub fn deserialize<'de, E: crate::Enumeration, D: Deserializer<'de>>(
1101 d: D,
1102 ) -> Result<crate::EnumValue<E>, D::Error> {
1103 struct V<E>(core::marker::PhantomData<E>);
1104 impl<'de, E: crate::Enumeration> serde::de::Visitor<'de> for V<E> {
1105 type Value = crate::EnumValue<E>;
1106 fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1107 f.write_str("a protobuf enum name string, integer value, or null")
1108 }
1109 fn visit_unit<Err>(self) -> Result<crate::EnumValue<E>, Err> {
1110 Ok(crate::EnumValue::from(0))
1111 }
1112 fn visit_i64<Err: serde::de::Error>(self, v: i64) -> Result<crate::EnumValue<E>, Err> {
1113 let i =
1114 i32::try_from(v).map_err(|_| Err::custom(EnumJsonErrorReason::OutOfRange))?;
1115 Ok(crate::EnumValue::from(i))
1116 }
1117 fn visit_u64<Err: serde::de::Error>(self, v: u64) -> Result<crate::EnumValue<E>, Err> {
1118 let i =
1119 i32::try_from(v).map_err(|_| Err::custom(EnumJsonErrorReason::OutOfRange))?;
1120 Ok(crate::EnumValue::from(i))
1121 }
1122 fn visit_i128<Err: serde::de::Error>(self, v: i128) -> Result<Self::Value, Err> {
1125 let v =
1126 i64::try_from(v).map_err(|_| Err::custom(EnumJsonErrorReason::OutOfRange))?;
1127 self.visit_i64(v)
1128 }
1129 fn visit_u128<Err: serde::de::Error>(self, v: u128) -> Result<Self::Value, Err> {
1130 let v =
1131 u64::try_from(v).map_err(|_| Err::custom(EnumJsonErrorReason::OutOfRange))?;
1132 self.visit_u64(v)
1133 }
1134 fn visit_f64<Err: serde::de::Error>(self, _: f64) -> Result<Self::Value, Err> {
1135 Err(Err::custom(EnumJsonErrorReason::InvalidType))
1136 }
1137 fn visit_bool<Err: serde::de::Error>(self, _: bool) -> Result<Self::Value, Err> {
1138 Err(Err::custom(EnumJsonErrorReason::InvalidType))
1139 }
1140 #[cfg(feature = "zeroize")]
1141 fn visit_string<Err: serde::de::Error>(
1142 self,
1143 value: alloc::string::String,
1144 ) -> Result<Self::Value, Err> {
1145 let value = zeroize::Zeroizing::new(value);
1148 self.visit_str(&value)
1149 }
1150 #[cfg(feature = "zeroize")]
1151 fn visit_byte_buf<Err: serde::de::Error>(
1152 self,
1153 value: alloc::vec::Vec<u8>,
1154 ) -> Result<Self::Value, Err> {
1155 let value = zeroize::Zeroizing::new(value);
1158 self.visit_bytes(&value)
1159 }
1160 fn visit_str<Err: serde::de::Error>(self, v: &str) -> Result<crate::EnumValue<E>, Err> {
1161 match E::from_proto_name(v) {
1162 Some(e) => Ok(crate::EnumValue::from(e)),
1163 None => {
1164 if crate::json::ignore_unknown_enum_values() {
1165 return Ok(crate::EnumValue::from(0));
1166 }
1167 Err(Err::custom(EnumJsonErrorReason::UnknownName))
1168 }
1169 }
1170 }
1171 }
1172 d.deserialize_any(V(core::marker::PhantomData))
1173 }
1174}
1175
1176#[inline]
1204fn try_deserialize_closed_enum<E: crate::Enumeration + Default>(
1205 raw: &serde_json::Value,
1206) -> Result<Option<E>, EnumJsonErrorReason> {
1207 match decode_closed_enum::<E>(raw) {
1208 Ok(e) => Ok(Some(e)),
1209 Err(ClosedEnumError::Unknown(_)) if crate::json::ignore_unknown_enum_values() => Ok(None),
1210 Err(ClosedEnumError::Unknown(reason) | ClosedEnumError::Malformed(reason)) => Err(reason),
1211 }
1212}
1213
1214enum ClosedEnumError {
1216 Unknown(EnumJsonErrorReason),
1219 Malformed(EnumJsonErrorReason),
1222}
1223
1224fn decode_closed_enum<E: crate::Enumeration + Default>(
1233 raw: &serde_json::Value,
1234) -> Result<E, ClosedEnumError> {
1235 use serde_json::Value;
1236
1237 match raw {
1238 Value::String(s) => {
1239 E::from_proto_name(s).ok_or(ClosedEnumError::Unknown(EnumJsonErrorReason::UnknownName))
1240 }
1241 Value::Number(n) if n.is_f64() => {
1242 Err(ClosedEnumError::Malformed(EnumJsonErrorReason::InvalidType))
1243 }
1244 Value::Number(n) => {
1245 let v32 = n
1249 .as_i64()
1250 .and_then(|v| i32::try_from(v).ok())
1251 .or_else(|| n.as_u64().and_then(|v| i32::try_from(v).ok()))
1252 .ok_or(ClosedEnumError::Malformed(EnumJsonErrorReason::OutOfRange))?;
1253 E::from_i32(v32).ok_or(ClosedEnumError::Unknown(EnumJsonErrorReason::UnknownNumber))
1254 }
1255 Value::Null | Value::Bool(_) | Value::Array(_) | Value::Object(_) => {
1256 Err(ClosedEnumError::Malformed(EnumJsonErrorReason::InvalidType))
1257 }
1258 }
1259}
1260
1261#[inline]
1276fn try_deserialize_enum<T: serde::de::DeserializeOwned>(
1277 raw: serde_json::Value,
1278) -> Result<Option<T>, serde_json::Error> {
1279 let raw_is_string = raw.is_string();
1281 let ignore = crate::json::ignore_unknown_enum_values();
1282 #[cfg(feature = "std")]
1285 let result = {
1286 let strict = crate::json::JsonParseOptions {
1287 ignore_unknown_enum_values: false,
1288 ..Default::default()
1289 };
1290 crate::json::with_json_parse_options(&strict, || serde_json::from_value::<T>(raw))
1291 };
1292 #[cfg(not(feature = "std"))]
1295 let result = serde_json::from_value::<T>(raw);
1296 match result {
1297 Ok(v) => Ok(Some(v)),
1298 Err(_) if ignore && raw_is_string => Ok(None),
1299 Err(e) => Err(e),
1300 }
1301}
1302
1303pub mod repeated_enum {
1313 use alloc::vec::Vec;
1314 use serde::{Deserializer, Serializer};
1315
1316 pub fn serialize<E: crate::Enumeration, S: Serializer>(
1317 value: &[crate::EnumValue<E>],
1318 s: S,
1319 ) -> Result<S::Ok, S::Error> {
1320 if !E::IS_NULL_VALUE || !s.is_human_readable() {
1321 return serde::Serialize::serialize(value, s);
1322 }
1323 use serde::ser::SerializeSeq as _;
1324 let mut sequence = s.serialize_seq(Some(value.len()))?;
1325 for element in value {
1326 if element.to_i32() == 0 {
1327 sequence.serialize_element(&())?;
1328 } else {
1329 sequence.serialize_element(element)?;
1330 }
1331 }
1332 sequence.end()
1333 }
1334
1335 pub fn deserialize<'de, E, C, D>(d: D) -> Result<C, D::Error>
1336 where
1337 E: crate::Enumeration,
1338 C: From<Vec<crate::EnumValue<E>>>,
1339 D: Deserializer<'de>,
1340 {
1341 struct V<E>(core::marker::PhantomData<E>);
1342 impl<'de, E: crate::Enumeration> serde::de::Visitor<'de> for V<E> {
1343 type Value = Vec<crate::EnumValue<E>>;
1344
1345 fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1346 f.write_str("a list of enum values or null")
1347 }
1348
1349 fn visit_unit<Err>(self) -> Result<Vec<crate::EnumValue<E>>, Err> {
1350 Ok(Vec::new())
1351 }
1352
1353 reject_container_scalar_values!(InvalidListType);
1354 crate::__buffa_reject_other_json_kinds!(bytes, byte_buf);
1355 fn visit_seq<A: serde::de::SeqAccess<'de>>(
1356 self,
1357 mut seq: A,
1358 ) -> Result<Vec<crate::EnumValue<E>>, A::Error> {
1359 let mut out = Vec::with_capacity(super::clamp_size_hint(seq.size_hint()));
1360 while let Some(super::BufferedValue(raw)) = seq.next_element()? {
1361 if raw.is_null() && !E::IS_NULL_VALUE {
1362 return Err(serde::de::Error::custom(
1363 super::enum_list::ErrorReason::Null,
1364 ));
1365 }
1366 match super::try_deserialize_enum::<crate::EnumValue<E>>(raw) {
1367 Ok(Some(v)) => out.push(v),
1368 Ok(None) => continue,
1369 Err(e) => return Err(serde::de::Error::custom(e)),
1370 }
1371 }
1372 Ok(out)
1373 }
1374 }
1375 d.deserialize_any(V::<E>(core::marker::PhantomData))
1376 .map(C::from)
1377 }
1378}
1379
1380pub mod map_enum {
1392 use crate::map_codec::MapStorage;
1393 use serde::{Deserializer, Serializer};
1394
1395 pub fn serialize<C, S>(value: &C, s: S) -> Result<S::Ok, S::Error>
1396 where
1397 C: MapStorage,
1398 C::Key: serde::Serialize,
1399 C::Value: serde::Serialize,
1400 S: Serializer,
1401 {
1402 use serde::ser::SerializeMap;
1403 let mut map = s.serialize_map(Some(value.storage_len()))?;
1404 for (k, v) in value.storage_iter() {
1405 map.serialize_entry(k, v)?;
1406 }
1407 map.end()
1408 }
1409
1410 pub fn deserialize<'de, C, D>(d: D) -> Result<C, D::Error>
1411 where
1412 C: MapStorage + Default,
1413 C::Key: serde::Deserialize<'de>,
1414 C::Value: serde::de::DeserializeOwned,
1415 D: Deserializer<'de>,
1416 {
1417 struct V<C>(core::marker::PhantomData<C>);
1418 impl<'de, C> serde::de::Visitor<'de> for V<C>
1419 where
1420 C: MapStorage + Default,
1421 C::Key: serde::Deserialize<'de>,
1422 C::Value: serde::de::DeserializeOwned,
1423 {
1424 type Value = C;
1425
1426 fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1427 f.write_str("a map with enum values or null")
1428 }
1429
1430 fn visit_unit<Err>(self) -> Result<Self::Value, Err> {
1431 Ok(C::default())
1432 }
1433
1434 reject_container_scalar_values!(InvalidMapType);
1435 crate::__buffa_reject_other_json_kinds!(bytes, byte_buf);
1436 fn visit_map<A: serde::de::MapAccess<'de>>(
1437 self,
1438 mut map: A,
1439 ) -> Result<Self::Value, A::Error> {
1440 let mut out = C::default();
1441 while let Some(key) = map.next_key_seed(super::map_key::KeySeed::<C::Key>::new())? {
1442 let key = crate::erasing::Erasing::new(key, C::storage_erase_key);
1443 let super::BufferedValue(raw) = map.next_value()?;
1444 match super::try_deserialize_enum::<C::Value>(raw) {
1445 Ok(Some(v)) => {
1446 out.storage_insert(key.into_inner(), v);
1447 }
1448 Ok(None) => continue,
1449 Err(e) => return Err(serde::de::Error::custom(e)),
1450 }
1451 }
1452 Ok(out)
1453 }
1454 }
1455 d.deserialize_any(V::<C>(core::marker::PhantomData))
1456 }
1457}
1458
1459pub fn null_as_default<'de, D, T>(d: D) -> Result<T, D::Error>
1467where
1468 D: serde::Deserializer<'de>,
1469 T: Default + serde::Deserialize<'de>,
1470{
1471 <Option<T> as serde::Deserialize>::deserialize(d).map(|opt| opt.unwrap_or_default())
1472}
1473
1474fn is_exact_integer(f: f64) -> bool {
1483 f.is_finite() && f == (f as i128 as f64)
1484}
1485
1486const MAX_SAFE_JSON_INTEGER_F64: f64 = 4_503_599_627_370_495.0;
1500
1501fn parse_int_from_str<I: TryFrom<i128>>(v: &str) -> Option<I> {
1504 if let Ok(n) = v.parse::<i128>() {
1506 return I::try_from(n).ok();
1507 }
1508 let n = parse_exact_decimal_int(v)?;
1509 I::try_from(n).ok()
1510}
1511
1512fn parse_exact_decimal_int(v: &str) -> Option<i128> {
1519 let (mantissa, exp) = match v.split_once(['e', 'E']) {
1520 Some((m, e)) => (m, e.parse::<i64>().ok()?),
1523 None => (v, 0),
1524 };
1525 let (negative, mantissa) = match mantissa.strip_prefix('-') {
1526 Some(rest) => (true, rest),
1527 None => (false, mantissa.strip_prefix('+').unwrap_or(mantissa)),
1528 };
1529 let (int_part, frac_part) = mantissa
1530 .split_once('.')
1531 .map_or((mantissa, ""), |(i, f)| (i, f));
1532 if int_part.is_empty() && frac_part.is_empty() {
1533 return None;
1534 }
1535 let frac_part = frac_part.trim_end_matches('0');
1538 let (int_part, trailing_zeros) = if frac_part.is_empty() {
1539 let trimmed = int_part.trim_end_matches('0');
1540 (trimmed, int_part.len() - trimmed.len())
1541 } else {
1542 (int_part, 0)
1543 };
1544
1545 let mut significand = 0i128;
1546 for digit in int_part.bytes().chain(frac_part.bytes()) {
1547 if !digit.is_ascii_digit() {
1548 return None;
1549 }
1550 significand = significand
1551 .checked_mul(10)?
1552 .checked_add(i128::from(digit - b'0'))?;
1553 }
1554 if significand == 0 {
1555 return Some(0);
1558 }
1559
1560 let scale = exp
1562 .checked_add(trailing_zeros as i64)?
1563 .checked_sub(frac_part.len() as i64)?;
1564 if scale >= 0 {
1565 let pow10 = 10i128.checked_pow(u32::try_from(scale).ok()?)?;
1566 significand = significand.checked_mul(pow10)?;
1567 } else {
1568 let divisor = 10i128.checked_pow(u32::try_from(scale.unsigned_abs()).ok()?)?;
1569 if significand % divisor != 0 {
1570 return None;
1571 }
1572 significand /= divisor;
1573 }
1574
1575 if negative {
1576 significand.checked_neg()
1577 } else {
1578 Some(significand)
1579 }
1580}
1581
1582fn f64_to_int<I: TryFrom<i128>>(v: f64) -> Option<I> {
1586 if !(-MAX_SAFE_JSON_INTEGER_F64..=MAX_SAFE_JSON_INTEGER_F64).contains(&v) {
1587 return None;
1588 }
1589 if !is_exact_integer(v) {
1590 return None;
1591 }
1592 I::try_from(v as i128).ok()
1593}
1594
1595macro_rules! int_serde_module {
1613 (
1614 $mod_name:ident, $int_type:ty,
1615 doc = $doc:expr,
1616 serialize_body = |$val:ident, $ser:ident| $ser_body:expr,
1617 expecting = $expecting:expr,
1618 reason = $reason:ident,
1619 parse_str = $parse_str:ident $(,)?
1620 ) => {
1621 #[doc = $doc]
1622 pub mod $mod_name {
1623 use super::*;
1624 use serde::{Deserializer, Serializer};
1625
1626 pub fn serialize<S: Serializer>(value: &$int_type, s: S) -> Result<S::Ok, S::Error> {
1627 let $val = value;
1628 let $ser = s;
1629 $ser_body
1630 }
1631
1632 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<$int_type, D::Error> {
1633 struct Vis;
1634 impl<'de> serde::de::Visitor<'de> for Vis {
1635 type Value = $int_type;
1636 fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1637 f.write_str($expecting)
1638 }
1639 fn visit_unit<E>(self) -> Result<$int_type, E> {
1640 Ok(0)
1641 }
1642 fn visit_bool<E: serde::de::Error>(self, _: bool) -> Result<$int_type, E> {
1643 Err(E::custom(JsonValueError::$reason))
1644 }
1645 fn visit_i64<E: serde::de::Error>(self, v: i64) -> Result<$int_type, E> {
1646 <$int_type>::try_from(v).map_err(|_| E::custom(JsonValueError::$reason))
1647 }
1648 fn visit_u64<E: serde::de::Error>(self, v: u64) -> Result<$int_type, E> {
1649 <$int_type>::try_from(v).map_err(|_| E::custom(JsonValueError::$reason))
1650 }
1651 fn visit_f64<E: serde::de::Error>(self, v: f64) -> Result<$int_type, E> {
1652 f64_to_int::<$int_type>(v).ok_or_else(|| E::custom(JsonValueError::$reason))
1653 }
1654 fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<$int_type, E> {
1655 $parse_str(v).ok_or_else(|| E::custom(JsonValueError::$reason))
1656 }
1657 fn visit_string<E: serde::de::Error>(
1658 self,
1659 value: alloc::string::String,
1660 ) -> Result<$int_type, E> {
1661 #[cfg(feature = "zeroize")]
1663 let value = zeroize::Zeroizing::new(value);
1664 self.visit_str(&value)
1665 }
1666 visit_wide_ints!(JsonValueError::$reason);
1667 crate::reject_other_json_kinds!(bytes, byte_buf);
1668 }
1669 d.deserialize_any(Vis)
1670 }
1671 }
1672 };
1673}
1674
1675int_serde_module!(
1676 int32,
1677 i32,
1678 doc = "Serde with-module for `i32` fields.\n\n\
1679 Proto JSON accepts integers as numbers, quoted decimal strings, or\n\
1680 float notation (e.g. `1.0`, `1e5`). Serializes as a JSON number.\n\n\
1681 Use with `#[serde(with = \"::buffa::json_helpers::int32\")]`.",
1682 serialize_body = |v, s| s.serialize_i32(*v),
1683 expecting = "an i32 as integer, string, float, or null",
1684 reason = Int32,
1685 parse_str = parse_int_from_str,
1686);
1687
1688int_serde_module!(
1689 uint32,
1690 u32,
1691 doc = "Serde with-module for `u32` fields.\n\n\
1692 Proto JSON accepts integers as numbers, quoted decimal strings, or\n\
1693 float notation (e.g. `1.0`, `1e5`). Serializes as a JSON number.\n\n\
1694 Use with `#[serde(with = \"::buffa::json_helpers::uint32\")]`.",
1695 serialize_body = |v, s| s.serialize_u32(*v),
1696 expecting = "a u32 as integer, string, float, or null",
1697 reason = Uint32,
1698 parse_str = parse_int_from_str,
1699);
1700
1701int_serde_module!(
1702 int64,
1703 i64,
1704 doc = "Serde with-module for `i64` fields encoded as a quoted decimal string.\n\n\
1705 Proto JSON also accepts unquoted integers and float notation.\n\n\
1706 Use with `#[serde(with = \"::buffa::json_helpers::int64\")]`.",
1707 serialize_body = |v, s| {
1708 #[cfg(feature = "zeroize")]
1709 {
1710 crate::sensitive::serialize_decimal(v, s)
1711 }
1712 #[cfg(not(feature = "zeroize"))]
1713 {
1714 s.collect_str(v)
1715 }
1716 },
1717 expecting = "an i64 as a quoted decimal string, integer, float, or null",
1718 reason = Int64,
1719 parse_str = parse_int_from_str,
1720);
1721
1722fn parse_u64(value: &str) -> Option<u64> {
1724 value.parse().ok().or_else(|| parse_int_from_str(value))
1725}
1726
1727int_serde_module!(
1728 uint64,
1729 u64,
1730 doc = "Serde with-module for `u64` fields encoded as a quoted decimal string.\n\n\
1731 Proto JSON also accepts unquoted integers and float notation.\n\n\
1732 Use with `#[serde(with = \"::buffa::json_helpers::uint64\")]`.",
1733 serialize_body = |v, s| {
1734 #[cfg(feature = "zeroize")]
1735 {
1736 crate::sensitive::serialize_decimal(v, s)
1737 }
1738 #[cfg(not(feature = "zeroize"))]
1739 {
1740 s.collect_str(v)
1741 }
1742 },
1743 expecting = "a u64 as a quoted decimal string, integer, float, or null",
1744 reason = Uint64,
1745 parse_str = parse_u64,
1746);
1747
1748pub mod float {
1777 use serde::{Deserializer, Serializer};
1778
1779 pub fn serialize<S: Serializer>(value: &f32, s: S) -> Result<S::Ok, S::Error> {
1780 if value.is_nan() {
1781 s.serialize_str("NaN")
1782 } else if *value == f32::INFINITY {
1783 s.serialize_str("Infinity")
1784 } else if *value == f32::NEG_INFINITY {
1785 s.serialize_str("-Infinity")
1786 } else {
1787 s.serialize_f32(*value)
1788 }
1789 }
1790
1791 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<f32, D::Error> {
1792 struct V;
1793 impl<'de> serde::de::Visitor<'de> for V {
1794 type Value = f32;
1795
1796 fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1797 f.write_str(r#"a float, "NaN", "Infinity", "-Infinity", or null"#)
1798 }
1799
1800 fn visit_unit<E>(self) -> Result<f32, E> {
1801 Ok(0.0)
1802 }
1803
1804 fn visit_bool<E: serde::de::Error>(self, _: bool) -> Result<f32, E> {
1805 Err(E::custom(super::JsonValueError::Float))
1806 }
1807
1808 fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<f32, E> {
1809 match v {
1810 "NaN" => Ok(f32::NAN),
1811 "Infinity" => Ok(f32::INFINITY),
1812 "-Infinity" => Ok(f32::NEG_INFINITY),
1813 _ => match v.parse::<f32>() {
1821 Ok(f) if f.is_finite() => Ok(f),
1822 _ => Err(E::custom(super::JsonValueError::Float)),
1823 },
1824 }
1825 }
1826
1827 fn visit_string<E: serde::de::Error>(
1828 self,
1829 value: alloc::string::String,
1830 ) -> Result<f32, E> {
1831 #[cfg(feature = "zeroize")]
1832 let value = zeroize::Zeroizing::new(value);
1833 self.visit_str(&value)
1834 }
1835
1836 fn visit_f32<E: serde::de::Error>(self, v: f32) -> Result<f32, E> {
1837 Ok(v)
1838 }
1839
1840 fn visit_f64<E: serde::de::Error>(self, v: f64) -> Result<f32, E> {
1841 let f = v as f32;
1845 if v.is_finite() && !f.is_finite() {
1846 return Err(E::custom(super::JsonValueError::Float));
1847 }
1848 Ok(f)
1849 }
1850
1851 fn visit_i64<E: serde::de::Error>(self, v: i64) -> Result<f32, E> {
1852 Ok(v as f32)
1853 }
1854
1855 visit_wide_ints!(super::JsonValueError::Float);
1856 crate::reject_other_json_kinds!(bytes, byte_buf);
1857
1858 fn visit_u64<E: serde::de::Error>(self, v: u64) -> Result<f32, E> {
1859 Ok(v as f32)
1860 }
1861 }
1862 d.deserialize_any(V)
1863 }
1864}
1865
1866pub mod double {
1878 use serde::{Deserializer, Serializer};
1879
1880 pub fn serialize<S: Serializer>(value: &f64, s: S) -> Result<S::Ok, S::Error> {
1881 if value.is_nan() {
1882 s.serialize_str("NaN")
1883 } else if *value == f64::INFINITY {
1884 s.serialize_str("Infinity")
1885 } else if *value == f64::NEG_INFINITY {
1886 s.serialize_str("-Infinity")
1887 } else {
1888 s.serialize_f64(*value)
1889 }
1890 }
1891
1892 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<f64, D::Error> {
1893 struct V;
1894 impl<'de> serde::de::Visitor<'de> for V {
1895 type Value = f64;
1896
1897 fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1898 f.write_str(r#"a double, "NaN", "Infinity", "-Infinity", or null"#)
1899 }
1900
1901 fn visit_unit<E>(self) -> Result<f64, E> {
1902 Ok(0.0)
1903 }
1904
1905 fn visit_bool<E: serde::de::Error>(self, _: bool) -> Result<f64, E> {
1906 Err(E::custom(super::JsonValueError::Double))
1907 }
1908
1909 fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<f64, E> {
1910 match v {
1911 "NaN" => Ok(f64::NAN),
1912 "Infinity" => Ok(f64::INFINITY),
1913 "-Infinity" => Ok(f64::NEG_INFINITY),
1914 _ => match v.parse::<f64>() {
1917 Ok(f) if f.is_finite() => Ok(f),
1918 _ => Err(E::custom(super::JsonValueError::Double)),
1919 },
1920 }
1921 }
1922
1923 fn visit_string<E: serde::de::Error>(
1924 self,
1925 value: alloc::string::String,
1926 ) -> Result<f64, E> {
1927 #[cfg(feature = "zeroize")]
1928 let value = zeroize::Zeroizing::new(value);
1929 self.visit_str(&value)
1930 }
1931
1932 fn visit_f64<E: serde::de::Error>(self, v: f64) -> Result<f64, E> {
1933 Ok(v)
1934 }
1935
1936 fn visit_f32<E: serde::de::Error>(self, v: f32) -> Result<f64, E> {
1937 Ok(v as f64)
1938 }
1939
1940 fn visit_i64<E: serde::de::Error>(self, v: i64) -> Result<f64, E> {
1941 Ok(v as f64)
1942 }
1943
1944 visit_wide_ints!(super::JsonValueError::Double);
1945 crate::reject_other_json_kinds!(bytes, byte_buf);
1946
1947 fn visit_u64<E: serde::de::Error>(self, v: u64) -> Result<f64, E> {
1948 Ok(v as f64)
1949 }
1950 }
1951 d.deserialize_any(V)
1952 }
1953}
1954
1955pub mod bytes {
1967 use super::STANDARD;
1968 use base64::Engine as _;
1969 use serde::{Deserializer, Serializer};
1970
1971 pub fn serialize<S: Serializer>(value: &[u8], s: S) -> Result<S::Ok, S::Error> {
1983 s.collect_str(&base64::display::Base64Display::new(value, &STANDARD))
1984 }
1985
1986 #[must_use]
1993 pub fn max_decoded_len(text: &str) -> usize {
1994 base64::decoded_len_estimate(text.len())
1995 }
1996
1997 pub fn decode_into<E: serde::de::Error>(text: &str, out: &mut [u8]) -> Result<usize, E> {
2057 super::lenient_engine(text)
2058 .decode_slice(text, out)
2059 .map_err(|error| {
2060 E::custom(match error {
2061 base64::DecodeSliceError::OutputSliceTooSmall => {
2062 Base64ErrorReason::BufferTooSmall
2063 }
2064 base64::DecodeSliceError::DecodeError(_) => Base64ErrorReason::Invalid,
2065 })
2066 })
2067 }
2068
2069 #[derive(Debug, thiserror::Error)]
2072 enum Base64ErrorReason {
2073 #[error("invalid base64")]
2074 Invalid,
2075 #[error("base64 output buffer too small")]
2076 BufferTooSmall,
2077 }
2078
2079 pub fn deserialize<'de, T, D>(d: D) -> Result<T, D::Error>
2091 where
2092 T: From<alloc::vec::Vec<u8>>,
2093 D: Deserializer<'de>,
2094 {
2095 struct V;
2096 impl<'de> serde::de::Visitor<'de> for V {
2097 type Value = alloc::vec::Vec<u8>;
2098
2099 fn visit_unit<E>(self) -> Result<alloc::vec::Vec<u8>, E> {
2100 Ok(alloc::vec::Vec::new())
2101 }
2102
2103 fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2104 f.write_str("a base64-encoded string, or null")
2105 }
2106
2107 fn visit_bool<E: serde::de::Error>(self, _: bool) -> Result<alloc::vec::Vec<u8>, E> {
2108 Err(E::custom(super::JsonValueError::Base64))
2109 }
2110
2111 fn visit_i64<E: serde::de::Error>(self, _: i64) -> Result<alloc::vec::Vec<u8>, E> {
2112 Err(E::custom(super::JsonValueError::Base64))
2113 }
2114
2115 fn visit_u64<E: serde::de::Error>(self, _: u64) -> Result<alloc::vec::Vec<u8>, E> {
2116 Err(E::custom(super::JsonValueError::Base64))
2117 }
2118
2119 fn visit_f64<E: serde::de::Error>(self, _: f64) -> Result<alloc::vec::Vec<u8>, E> {
2120 Err(E::custom(super::JsonValueError::Base64))
2121 }
2122
2123 visit_wide_ints!(super::JsonValueError::Base64);
2124 crate::reject_other_json_kinds!(bytes, byte_buf);
2125
2126 fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<alloc::vec::Vec<u8>, E> {
2127 super::decode_base64(v).map_err(serde::de::Error::custom)
2128 }
2129 }
2130 d.deserialize_any(V).map(T::from)
2132 }
2133}
2134
2135proto_elem_json_delegate!(i32, int32);
2141proto_elem_json_delegate!(u32, uint32);
2142proto_elem_json_delegate!(i64, int64);
2143proto_elem_json_delegate!(u64, uint64);
2144proto_elem_json_delegate!(f32, float);
2145proto_elem_json_delegate!(f64, double);
2146proto_elem_json_delegate!(bool, proto_bool, null = "a boolean");
2147proto_elem_json_delegate!(alloc::string::String, proto_string, null = "a string");
2148proto_elem_json_delegate!(alloc::vec::Vec<u8>, bytes);
2149
2150impl ProtoElemJson for ::bytes::Bytes {
2168 fn serialize_proto_json<S: serde::Serializer>(v: &Self, s: S) -> Result<S::Ok, S::Error> {
2169 bytes::serialize(v, s)
2170 }
2171 fn deserialize_proto_json<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
2172 bytes::deserialize(d)
2173 }
2174}
2175
2176impl<E: crate::Enumeration> ProtoElemJson for crate::EnumValue<E>
2180where
2181 Self: serde::Serialize + serde::de::DeserializeOwned,
2182{
2183 fn serialize_proto_json<S: serde::Serializer>(v: &Self, s: S) -> Result<S::Ok, S::Error> {
2184 serde::Serialize::serialize(v, s)
2185 }
2186 fn deserialize_proto_json<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
2187 <Self as serde::Deserialize>::deserialize(d)
2188 }
2189}
2190
2191pub mod bytes_key_map {
2200 use super::{ProtoElemJson, ProtoElemSeed, ProtoJson};
2201 use crate::map_codec::MapStorage;
2202 use serde::{Deserializer, Serializer};
2203
2204 pub fn serialize<C, S>(value: &C, s: S) -> Result<S::Ok, S::Error>
2205 where
2206 C: MapStorage<Key = alloc::vec::Vec<u8>>,
2207 C::Value: ProtoElemJson,
2208 S: Serializer,
2209 {
2210 use serde::ser::SerializeMap;
2211 let mut map = s.serialize_map(Some(value.storage_len()))?;
2212 for (k, v) in value.storage_iter() {
2213 map.serialize_entry(&super::Base64Wrapper(k), &ProtoJson(v))?;
2214 }
2215 map.end()
2216 }
2217
2218 pub fn deserialize<'de, C, D>(d: D) -> Result<C, D::Error>
2219 where
2220 C: MapStorage<Key = alloc::vec::Vec<u8>> + Default,
2221 C::Value: ProtoElemJson,
2222 D: Deserializer<'de>,
2223 {
2224 struct Vis<C>(core::marker::PhantomData<C>);
2225 impl<'de, C> serde::de::Visitor<'de> for Vis<C>
2226 where
2227 C: MapStorage<Key = alloc::vec::Vec<u8>> + Default,
2228 C::Value: ProtoElemJson,
2229 {
2230 type Value = C;
2231 fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2232 f.write_str("a map with base64-encoded keys, or null")
2233 }
2234 fn visit_unit<E>(self) -> Result<Self::Value, E> {
2235 Ok(C::default())
2236 }
2237 crate::reject_other_json_kinds!(
2238 bool, i64, u64, i128, u128, f64, str, string, bytes, byte_buf
2239 );
2240 fn visit_map<A: serde::de::MapAccess<'de>>(
2241 self,
2242 mut map: A,
2243 ) -> Result<Self::Value, A::Error> {
2244 let mut out = C::default();
2245 while let Some(key_str) = map.next_key::<alloc::string::String>()? {
2246 #[cfg(feature = "zeroize")]
2247 let key_str = zeroize::Zeroizing::new(key_str);
2248 let k = super::decode_base64(&key_str).map_err(serde::de::Error::custom)?;
2249 let k = crate::erasing::Erasing::new(k, C::storage_erase_key);
2250 let v =
2251 map.next_value_seed(ProtoElemSeed::<C::Value>(core::marker::PhantomData))?;
2252 out.storage_insert(k.into_inner(), v);
2253 }
2254 Ok(out)
2255 }
2256 }
2257 d.deserialize_any(Vis::<C>(core::marker::PhantomData))
2258 }
2259}
2260
2261pub mod bytes_key_bytes_val_map {
2268 use crate::map_codec::MapStorage;
2269 use serde::{Deserializer, Serializer};
2270
2271 pub fn serialize<C, S>(value: &C, s: S) -> Result<S::Ok, S::Error>
2272 where
2273 C: MapStorage<Key = alloc::vec::Vec<u8>, Value = alloc::vec::Vec<u8>>,
2274 S: Serializer,
2275 {
2276 use serde::ser::SerializeMap;
2277 let mut map = s.serialize_map(Some(value.storage_len()))?;
2278 for (k, v) in value.storage_iter() {
2279 map.serialize_entry(&super::Base64Wrapper(k), &super::Base64Wrapper(v))?;
2280 }
2281 map.end()
2282 }
2283
2284 pub fn deserialize<'de, C, D>(d: D) -> Result<C, D::Error>
2285 where
2286 C: MapStorage<Key = alloc::vec::Vec<u8>, Value = alloc::vec::Vec<u8>> + Default,
2287 D: Deserializer<'de>,
2288 {
2289 struct V<C>(core::marker::PhantomData<C>);
2290 impl<'de, C> serde::de::Visitor<'de> for V<C>
2291 where
2292 C: MapStorage<Key = alloc::vec::Vec<u8>, Value = alloc::vec::Vec<u8>> + Default,
2293 {
2294 type Value = C;
2295 fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2296 f.write_str("a map with base64-encoded keys and values, or null")
2297 }
2298 fn visit_unit<E>(self) -> Result<Self::Value, E> {
2299 Ok(C::default())
2300 }
2301 crate::reject_other_json_kinds!(
2302 bool, i64, u64, i128, u128, f64, str, string, bytes, byte_buf
2303 );
2304 fn visit_map<A: serde::de::MapAccess<'de>>(
2305 self,
2306 mut map: A,
2307 ) -> Result<Self::Value, A::Error> {
2308 let mut out = C::default();
2309 while let Some(ks) = map.next_key::<alloc::string::String>()? {
2310 #[cfg(feature = "zeroize")]
2311 let ks = zeroize::Zeroizing::new(ks);
2312 let k = super::decode_base64(&ks).map_err(serde::de::Error::custom)?;
2313 let k = crate::erasing::Erasing::new(k, C::storage_erase_key);
2314 let vs = map.next_value::<alloc::string::String>()?;
2315 #[cfg(feature = "zeroize")]
2316 let vs = zeroize::Zeroizing::new(vs);
2317 let v = super::decode_base64(&vs).map_err(serde::de::Error::custom)?;
2318 out.storage_insert(k.into_inner(), v);
2319 }
2320 Ok(out)
2321 }
2322 }
2323 d.deserialize_any(V::<C>(core::marker::PhantomData))
2324 }
2325}
2326
2327pub mod string_key_map {
2338 use crate::map_codec::MapStorage;
2339 use core::fmt::Display;
2340 use core::str::FromStr;
2341 use serde::{Deserializer, Serializer};
2342
2343 pub fn serialize<C, S>(value: &C, s: S) -> Result<S::Ok, S::Error>
2344 where
2345 C: MapStorage,
2346 C::Key: Display,
2347 C::Value: serde::Serialize,
2348 S: Serializer,
2349 {
2350 use serde::ser::SerializeMap;
2351 let mut map = s.serialize_map(Some(value.storage_len()))?;
2352 for (k, v) in value.storage_iter() {
2353 map.serialize_entry(&super::DisplayKey(k), v)?;
2354 }
2355 map.end()
2356 }
2357
2358 pub fn deserialize<'de, C, D>(d: D) -> Result<C, D::Error>
2359 where
2360 C: MapStorage + Default,
2361 C::Key: FromStr,
2362 C::Value: serde::Deserialize<'de>,
2363 D: Deserializer<'de>,
2364 {
2365 struct MapVisitor<C>(core::marker::PhantomData<C>);
2366 impl<'de, C> serde::de::Visitor<'de> for MapVisitor<C>
2367 where
2368 C: MapStorage + Default,
2369 C::Key: FromStr,
2370 C::Value: serde::Deserialize<'de>,
2371 {
2372 type Value = C;
2373 fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2374 f.write_str("a JSON object with string keys, or null")
2375 }
2376 fn visit_unit<E>(self) -> Result<Self::Value, E> {
2377 Ok(C::default())
2378 }
2379 crate::reject_other_json_kinds!(
2380 bool, i64, u64, i128, u128, f64, str, string, bytes, byte_buf
2381 );
2382 fn visit_map<A: serde::de::MapAccess<'de>>(
2383 self,
2384 mut map: A,
2385 ) -> Result<Self::Value, A::Error> {
2386 let mut out = C::default();
2387 while let Some(key_str) = map.next_key::<alloc::string::String>()? {
2388 let key = key_str
2389 .parse::<C::Key>()
2390 .map_err(|_| serde::de::Error::custom(super::JsonValueError::MapKey))?;
2391 let key = crate::erasing::Erasing::new(key, C::storage_erase_key);
2392 let value = map.next_value()?;
2393 out.storage_insert(key.into_inner(), value);
2394 }
2395 Ok(out)
2396 }
2397 }
2398 d.deserialize_any(MapVisitor::<C>(core::marker::PhantomData))
2399 }
2400}
2401
2402struct Base64Wrapper<'a>(&'a [u8]);
2404
2405impl serde::Serialize for Base64Wrapper<'_> {
2406 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
2407 bytes::serialize(self.0, s)
2408 }
2409}
2410
2411fn lenient_engine(v: &str) -> &'static GeneralPurpose {
2421 match v.bytes().find(|b| matches!(b, b'+' | b'/' | b'-' | b'_')) {
2422 Some(b'-' | b'_') => &URL_SAFE_LENIENT,
2423 _ => &STANDARD_LENIENT,
2424 }
2425}
2426
2427pub(crate) fn decode_base64(v: &str) -> Result<alloc::vec::Vec<u8>, JsonValueError> {
2430 use base64::Engine as _;
2431 lenient_engine(v)
2432 .decode(v)
2433 .map_err(|_| JsonValueError::Base64)
2434}
2435
2436macro_rules! opt_serde_module {
2443 ($(#[$attr:meta])* $mod_name:ident, $inner:ident, $ty:ty) => {
2444 $(#[$attr])*
2445 pub mod $mod_name {
2446 use serde::{Deserializer, Serializer};
2447
2448 pub fn serialize<S: Serializer>(value: &Option<$ty>, s: S) -> Result<S::Ok, S::Error> {
2449 match value {
2450 Some(v) => super::$inner::serialize(v, s),
2451 None => s.serialize_none(),
2452 }
2453 }
2454
2455 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<$ty>, D::Error> {
2456 serde::de::DeserializeSeed::deserialize(super::NullableDeserializeSeed(Inner), d)
2459 }
2460
2461 struct Inner;
2463
2464 impl<'de> serde::de::DeserializeSeed<'de> for Inner {
2465 type Value = $ty;
2466 fn deserialize<D: Deserializer<'de>>(self, d: D) -> Result<$ty, D::Error> {
2467 super::$inner::deserialize(d)
2468 }
2469 }
2470 }
2471 };
2472}
2473
2474opt_serde_module!(opt_int32, int32, i32);
2475opt_serde_module!(opt_uint32, uint32, u32);
2476opt_serde_module!(opt_int64, int64, i64);
2477opt_serde_module!(opt_uint64, uint64, u64);
2478opt_serde_module!(opt_float, float, f32);
2479opt_serde_module!(opt_double, double, f64);
2480pub mod opt_bool {
2484 pub fn serialize<S: serde::Serializer>(value: &Option<bool>, s: S) -> Result<S::Ok, S::Error> {
2489 if s.is_human_readable() {
2490 match value {
2491 Some(value) => super::proto_bool::serialize(value, s),
2492 None => s.serialize_none(),
2493 }
2494 } else {
2495 serde::Serialize::serialize(value, s)
2496 }
2497 }
2498 pub fn deserialize<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<bool>, D::Error> {
2503 if !d.is_human_readable() {
2504 return serde::Deserialize::deserialize(d);
2505 }
2506 struct Inner;
2507 impl<'de> serde::de::DeserializeSeed<'de> for Inner {
2508 type Value = bool;
2509 fn deserialize<D: serde::Deserializer<'de>>(self, d: D) -> Result<bool, D::Error> {
2510 super::proto_bool::deserialize(d)
2511 }
2512 }
2513 serde::de::DeserializeSeed::deserialize(super::NullableDeserializeSeed(Inner), d)
2514 }
2515}
2516
2517pub mod opt_string {
2528 use serde::{Deserializer, Serializer};
2529
2530 pub fn serialize<T, S>(value: &Option<T>, s: S) -> Result<S::Ok, S::Error>
2532 where
2533 T: AsRef<str>,
2534 S: Serializer,
2535 {
2536 match value {
2537 Some(v) if s.is_human_readable() => super::proto_string::serialize(v.as_ref(), s),
2538 Some(v) => s.serialize_some(v.as_ref()),
2539 None => s.serialize_none(),
2540 }
2541 }
2542
2543 pub fn deserialize<'de, T, D>(d: D) -> Result<Option<T>, D::Error>
2550 where
2551 T: crate::ProtoString,
2552 D: Deserializer<'de>,
2553 {
2554 if !d.is_human_readable() {
2555 return <Option<alloc::string::String> as serde::Deserialize>::deserialize(d)
2556 .map(|value| value.map(T::from));
2557 }
2558 struct Inner<T>(core::marker::PhantomData<T>);
2559 impl<'de, T: crate::ProtoString> serde::de::DeserializeSeed<'de> for Inner<T> {
2560 type Value = T;
2561 fn deserialize<D2: Deserializer<'de>>(self, d: D2) -> Result<T, D2::Error> {
2562 super::proto_string::deserialize(d)
2563 }
2564 }
2565 serde::de::DeserializeSeed::deserialize(
2566 super::NullableDeserializeSeed(Inner(core::marker::PhantomData)),
2567 d,
2568 )
2569 }
2570}
2571
2572pub mod opt_bytes {
2580 use serde::{Deserializer, Serializer};
2581
2582 pub fn serialize<T, S>(value: &Option<T>, s: S) -> Result<S::Ok, S::Error>
2583 where
2584 T: AsRef<[u8]>,
2585 S: Serializer,
2586 {
2587 match value {
2588 Some(v) => super::bytes::serialize(v.as_ref(), s),
2589 None => s.serialize_none(),
2590 }
2591 }
2592
2593 pub fn deserialize<'de, T, D>(d: D) -> Result<Option<T>, D::Error>
2594 where
2595 T: From<alloc::vec::Vec<u8>>,
2596 D: Deserializer<'de>,
2597 {
2598 struct Inner;
2601 impl<'de> serde::de::DeserializeSeed<'de> for Inner {
2602 type Value = alloc::vec::Vec<u8>;
2603 fn deserialize<D2: Deserializer<'de>>(
2604 self,
2605 d: D2,
2606 ) -> Result<alloc::vec::Vec<u8>, D2::Error> {
2607 super::bytes::deserialize(d)
2608 }
2609 }
2610 serde::de::DeserializeSeed::deserialize(super::NullableDeserializeSeed(Inner), d)
2611 .map(|opt| opt.map(T::from))
2612 }
2613}
2614
2615pub mod opt_enum {
2623 use serde::{Deserializer, Serializer};
2624
2625 pub fn serialize<E: crate::Enumeration, S: Serializer>(
2626 value: &Option<crate::EnumValue<E>>,
2627 s: S,
2628 ) -> Result<S::Ok, S::Error> {
2629 match value {
2630 Some(v) => serde::Serialize::serialize(v, s),
2631 None => s.serialize_none(),
2632 }
2633 }
2634
2635 pub fn deserialize<'de, E: crate::Enumeration, D: Deserializer<'de>>(
2636 d: D,
2637 ) -> Result<Option<crate::EnumValue<E>>, D::Error> {
2638 let raw: Option<super::BufferedValue> = serde::Deserialize::deserialize(d)?;
2640 let raw = match raw {
2641 Some(super::BufferedValue(v)) => v,
2642 None => return Ok(None),
2643 };
2644
2645 super::try_deserialize_enum::<crate::EnumValue<E>>(raw).map_err(serde::de::Error::custom)
2646 }
2647}
2648
2649pub struct NullableDeserializeSeed<S>(pub S);
2656
2657impl<'de, S> serde::de::DeserializeSeed<'de> for NullableDeserializeSeed<S>
2658where
2659 S: serde::de::DeserializeSeed<'de>,
2660{
2661 type Value = Option<S::Value>;
2662
2663 fn deserialize<D: serde::Deserializer<'de>>(self, d: D) -> Result<Self::Value, D::Error> {
2664 d.deserialize_option(NullableVisitor(self.0))
2665 }
2666}
2667
2668struct NullableVisitor<S>(S);
2669
2670impl<'de, S> serde::de::Visitor<'de> for NullableVisitor<S>
2671where
2672 S: serde::de::DeserializeSeed<'de>,
2673{
2674 type Value = Option<S::Value>;
2675
2676 fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2677 f.write_str("a value or null")
2678 }
2679
2680 fn visit_none<E>(self) -> Result<Self::Value, E> {
2681 Ok(None)
2682 }
2683
2684 crate::reject_other_json_kinds!(bool, i64, u64, i128, u128, f64, str, string, bytes, byte_buf);
2685
2686 fn visit_unit<E>(self) -> Result<Self::Value, E> {
2687 Ok(None)
2688 }
2689
2690 fn visit_some<D: serde::Deserializer<'de>>(self, d: D) -> Result<Self::Value, D::Error> {
2691 self.0.deserialize(d).map(Some)
2692 }
2693}
2694
2695pub struct DefaultDeserializeSeed<T>(core::marker::PhantomData<T>);
2701
2702impl<T> DefaultDeserializeSeed<T> {
2703 pub fn new() -> Self {
2704 Self(core::marker::PhantomData)
2705 }
2706}
2707
2708impl<T> Default for DefaultDeserializeSeed<T> {
2709 fn default() -> Self {
2710 Self::new()
2711 }
2712}
2713
2714impl<'de, T: serde::Deserialize<'de>> serde::de::DeserializeSeed<'de>
2715 for DefaultDeserializeSeed<T>
2716{
2717 type Value = T;
2718 fn deserialize<D: serde::Deserializer<'de>>(self, d: D) -> Result<T, D::Error> {
2719 T::deserialize(d)
2720 }
2721}
2722
2723pub fn message_field_always_present<'de, T, P, D>(
2733 d: D,
2734) -> Result<crate::MessageField<T, P>, D::Error>
2735where
2736 T: Default + serde::Deserialize<'de>,
2737 P: crate::ProtoBox<T>,
2738 D: serde::Deserializer<'de>,
2739{
2740 T::deserialize(d).map(crate::MessageField::some)
2741}
2742
2743pub(crate) struct EnumProtoNameRef<'a, E: crate::Enumeration>(pub &'a E);
2750
2751impl<E: crate::Enumeration> serde::Serialize for EnumProtoNameRef<'_, E> {
2752 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
2753 s.serialize_str(self.0.proto_name())
2754 }
2755}
2756
2757pub mod skip_if {
2765 pub fn is_zero_i32(v: &i32) -> bool {
2766 *v == 0
2767 }
2768 pub fn is_zero_i64(v: &i64) -> bool {
2769 *v == 0
2770 }
2771 pub fn is_zero_u32(v: &u32) -> bool {
2772 *v == 0
2773 }
2774 pub fn is_zero_u64(v: &u64) -> bool {
2775 *v == 0
2776 }
2777 pub fn is_false(v: &bool) -> bool {
2778 !*v
2779 }
2780 pub fn is_zero_f32(v: &f32) -> bool {
2784 v.to_bits() == 0
2785 }
2786 pub fn is_zero_f64(v: &f64) -> bool {
2789 v.to_bits() == 0
2790 }
2791 pub fn is_empty_str(v: &str) -> bool {
2792 v.is_empty()
2793 }
2794 pub fn is_empty_bytes(v: &[u8]) -> bool {
2795 v.is_empty()
2796 }
2797 pub fn is_empty_vec<T>(v: &[T]) -> bool {
2798 v.is_empty()
2799 }
2800 pub fn is_empty_map<C>(m: &C) -> bool
2806 where
2807 C: crate::map_codec::MapStorage,
2808 {
2809 m.storage_len() == 0
2810 }
2811 pub fn is_unset_message_field<T: Default, P: crate::ProtoBox<T>>(
2812 v: &crate::MessageField<T, P>,
2813 ) -> bool {
2814 v.is_unset()
2815 }
2816 pub fn is_default_enum_value<E: crate::Enumeration>(v: &crate::EnumValue<E>) -> bool {
2817 v.to_i32() == 0
2818 }
2819 pub fn is_default_closed_enum<E: crate::Enumeration>(v: &E) -> bool {
2820 v.to_i32() == 0
2821 }
2822}
2823
2824pub mod closed_enum {
2832 use super::EnumJsonErrorReason;
2833 use serde::{Deserializer, Serializer};
2834
2835 pub fn serialize<E: crate::Enumeration, S: Serializer>(
2836 value: &E,
2837 s: S,
2838 ) -> Result<S::Ok, S::Error> {
2839 s.serialize_str(value.proto_name())
2840 }
2841
2842 pub fn deserialize<'de, E: crate::Enumeration + Default, D: Deserializer<'de>>(
2843 d: D,
2844 ) -> Result<E, D::Error> {
2845 deserialize_with_unknown_names(d, true)
2846 }
2847
2848 #[doc(hidden)]
2850 pub fn deserialize_strict<'de, E: crate::Enumeration + Default, D: Deserializer<'de>>(
2851 d: D,
2852 ) -> Result<E, D::Error> {
2853 deserialize_with_unknown_names(d, false)
2854 }
2855
2856 fn deserialize_with_unknown_names<
2857 'de,
2858 E: crate::Enumeration + Default,
2859 D: Deserializer<'de>,
2860 >(
2861 d: D,
2862 allow_lenient: bool,
2863 ) -> Result<E, D::Error> {
2864 struct V<E> {
2865 allow_lenient: bool,
2866 marker: core::marker::PhantomData<E>,
2867 }
2868 impl<'de, E: crate::Enumeration + Default> serde::de::Visitor<'de> for V<E> {
2869 type Value = E;
2870 fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2871 f.write_str("a protobuf enum name string, integer value, or null")
2872 }
2873 fn visit_unit<Err>(self) -> Result<E, Err> {
2874 Ok(E::default())
2875 }
2876 fn visit_i64<Err: serde::de::Error>(self, v: i64) -> Result<E, Err> {
2877 let v32 =
2878 i32::try_from(v).map_err(|_| Err::custom(EnumJsonErrorReason::OutOfRange))?;
2879 E::from_i32(v32).ok_or_else(|| Err::custom(EnumJsonErrorReason::UnknownNumber))
2880 }
2881 fn visit_u64<Err: serde::de::Error>(self, v: u64) -> Result<E, Err> {
2882 let v32 =
2883 i32::try_from(v).map_err(|_| Err::custom(EnumJsonErrorReason::OutOfRange))?;
2884 E::from_i32(v32).ok_or_else(|| Err::custom(EnumJsonErrorReason::UnknownNumber))
2885 }
2886 fn visit_i128<Err: serde::de::Error>(self, v: i128) -> Result<E, Err> {
2889 let v =
2890 i64::try_from(v).map_err(|_| Err::custom(EnumJsonErrorReason::OutOfRange))?;
2891 self.visit_i64(v)
2892 }
2893 fn visit_u128<Err: serde::de::Error>(self, v: u128) -> Result<E, Err> {
2894 let v =
2895 u64::try_from(v).map_err(|_| Err::custom(EnumJsonErrorReason::OutOfRange))?;
2896 self.visit_u64(v)
2897 }
2898 fn visit_f64<Err: serde::de::Error>(self, _: f64) -> Result<E, Err> {
2899 Err(Err::custom(EnumJsonErrorReason::InvalidType))
2900 }
2901 fn visit_bool<Err: serde::de::Error>(self, _: bool) -> Result<E, Err> {
2902 Err(Err::custom(EnumJsonErrorReason::InvalidType))
2903 }
2904 #[cfg(feature = "zeroize")]
2905 fn visit_string<Err: serde::de::Error>(
2906 self,
2907 value: alloc::string::String,
2908 ) -> Result<E, Err> {
2909 let value = zeroize::Zeroizing::new(value);
2912 self.visit_str(&value)
2913 }
2914 #[cfg(feature = "zeroize")]
2915 fn visit_byte_buf<Err: serde::de::Error>(
2916 self,
2917 value: alloc::vec::Vec<u8>,
2918 ) -> Result<Self::Value, Err> {
2919 let value = zeroize::Zeroizing::new(value);
2922 self.visit_bytes(&value)
2923 }
2924 fn visit_str<Err: serde::de::Error>(self, v: &str) -> Result<E, Err> {
2925 match E::from_proto_name(v) {
2926 Some(e) => Ok(e),
2927 None => {
2928 if self.allow_lenient && crate::json::ignore_unknown_enum_values() {
2929 return Ok(E::default());
2930 }
2931 Err(Err::custom(EnumJsonErrorReason::UnknownName))
2932 }
2933 }
2934 }
2935 }
2936 d.deserialize_any(V {
2937 allow_lenient,
2938 marker: core::marker::PhantomData,
2939 })
2940 }
2941}
2942
2943pub mod opt_closed_enum {
2951 use serde::{Deserializer, Serializer};
2952
2953 pub fn serialize<E: crate::Enumeration, S: Serializer>(
2954 value: &Option<E>,
2955 s: S,
2956 ) -> Result<S::Ok, S::Error> {
2957 match value {
2958 Some(v) => s.serialize_str(v.proto_name()),
2959 None => s.serialize_none(),
2960 }
2961 }
2962
2963 pub fn deserialize<'de, E: crate::Enumeration + Default, D: Deserializer<'de>>(
2964 d: D,
2965 ) -> Result<Option<E>, D::Error> {
2966 let raw: Option<super::BufferedValue> = serde::Deserialize::deserialize(d)?;
2967 let raw = match raw {
2968 Some(super::BufferedValue(v)) => v,
2969 None => return Ok(None),
2970 };
2971
2972 super::try_deserialize_closed_enum::<E>(&raw).map_err(serde::de::Error::custom)
2973 }
2974}
2975
2976pub mod repeated_closed_enum {
2986 use alloc::vec::Vec;
2987 use serde::{Deserializer, Serializer};
2988
2989 pub fn serialize<E: crate::Enumeration, S: Serializer>(
2990 value: &[E],
2991 s: S,
2992 ) -> Result<S::Ok, S::Error> {
2993 use serde::ser::SerializeSeq;
2994 let null_sentinel = E::IS_NULL_VALUE && s.is_human_readable();
2995 let mut seq = s.serialize_seq(Some(value.len()))?;
2996 for v in value {
2997 if null_sentinel && v.to_i32() == 0 {
2998 seq.serialize_element(&())?;
2999 } else {
3000 seq.serialize_element(&crate::json_helpers::EnumProtoNameRef(v))?;
3001 }
3002 }
3003 seq.end()
3004 }
3005
3006 pub fn deserialize<'de, E, C, D>(d: D) -> Result<C, D::Error>
3007 where
3008 E: crate::Enumeration + Default,
3009 C: From<Vec<E>>,
3010 D: Deserializer<'de>,
3011 {
3012 struct V<E>(core::marker::PhantomData<E>);
3013 impl<'de, E: crate::Enumeration + Default> serde::de::Visitor<'de> for V<E> {
3014 type Value = Vec<E>;
3015
3016 fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
3017 f.write_str("a list of enum values or null")
3018 }
3019
3020 fn visit_unit<Err>(self) -> Result<Vec<E>, Err> {
3021 Ok(Vec::new())
3022 }
3023
3024 reject_container_scalar_values!(InvalidListType);
3025 crate::__buffa_reject_other_json_kinds!(bytes, byte_buf);
3026 fn visit_seq<A: serde::de::SeqAccess<'de>>(
3027 self,
3028 mut seq: A,
3029 ) -> Result<Vec<E>, A::Error> {
3030 let mut out = Vec::with_capacity(super::clamp_size_hint(seq.size_hint()));
3031 while let Some(super::BufferedValue(raw)) = seq.next_element()? {
3032 if raw.is_null() && E::IS_NULL_VALUE {
3033 let value = E::from_i32(0).ok_or_else(|| {
3034 <A::Error as serde::de::Error>::custom(
3035 super::enum_list::ErrorReason::Unknown,
3036 )
3037 })?;
3038 out.push(value);
3039 continue;
3040 }
3041 match super::try_deserialize_closed_enum::<E>(&raw) {
3042 Ok(Some(v)) => out.push(v),
3043 Ok(None) => continue,
3044 Err(e) => return Err(serde::de::Error::custom(e)),
3045 }
3046 }
3047 Ok(out)
3048 }
3049 }
3050 d.deserialize_any(V::<E>(core::marker::PhantomData))
3051 .map(C::from)
3052 }
3053}
3054
3055pub mod map_closed_enum {
3065 use crate::map_codec::MapStorage;
3066 use serde::{Deserializer, Serializer};
3067
3068 pub fn serialize<C, S>(value: &C, s: S) -> Result<S::Ok, S::Error>
3069 where
3070 C: MapStorage,
3071 C::Key: serde::Serialize,
3072 C::Value: crate::Enumeration,
3073 S: Serializer,
3074 {
3075 use serde::ser::SerializeMap;
3076 let mut map = s.serialize_map(Some(value.storage_len()))?;
3077 for (k, v) in value.storage_iter() {
3078 map.serialize_entry(k, &crate::json_helpers::EnumProtoNameRef(v))?;
3079 }
3080 map.end()
3081 }
3082
3083 pub fn deserialize<'de, C, D>(d: D) -> Result<C, D::Error>
3084 where
3085 C: MapStorage + Default,
3086 C::Key: serde::Deserialize<'de>,
3087 C::Value: crate::Enumeration + Default,
3088 D: Deserializer<'de>,
3089 {
3090 struct V<C>(core::marker::PhantomData<C>);
3091 impl<'de, C> serde::de::Visitor<'de> for V<C>
3092 where
3093 C: MapStorage + Default,
3094 C::Key: serde::Deserialize<'de>,
3095 C::Value: crate::Enumeration + Default,
3096 {
3097 type Value = C;
3098
3099 fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
3100 f.write_str("a map with enum values or null")
3101 }
3102
3103 fn visit_unit<Err>(self) -> Result<Self::Value, Err> {
3104 Ok(C::default())
3105 }
3106
3107 reject_container_scalar_values!(InvalidMapType);
3108 crate::__buffa_reject_other_json_kinds!(bytes, byte_buf);
3109 fn visit_map<A: serde::de::MapAccess<'de>>(
3110 self,
3111 mut map: A,
3112 ) -> Result<Self::Value, A::Error> {
3113 let mut out = C::default();
3114 while let Some(key) = map.next_key_seed(super::map_key::KeySeed::<C::Key>::new())? {
3115 let key = crate::erasing::Erasing::new(key, C::storage_erase_key);
3116 let super::BufferedValue(raw) = map.next_value()?;
3117 match super::try_deserialize_closed_enum::<C::Value>(&raw) {
3118 Ok(Some(v)) => {
3119 out.storage_insert(key.into_inner(), v);
3120 }
3121 Ok(None) => continue,
3122 Err(e) => return Err(serde::de::Error::custom(e)),
3123 }
3124 }
3125 Ok(out)
3126 }
3127 }
3128 d.deserialize_any(V::<C>(core::marker::PhantomData))
3129 }
3130}
3131
3132#[cfg(test)]
3135mod tests;
3136
3137pub mod enum_list;
3139#[doc(hidden)]
3141#[cfg(feature = "zeroize")]
3142pub mod guarded_enum;
3143mod guarded_key;
3144#[doc(hidden)]
3146#[cfg(feature = "zeroize")]
3147pub mod guarded_map;