1pub 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#[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
104use 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
123const MAX_PREALLOC_HINT: usize = 4096;
131
132#[inline]
134fn clamp_size_hint(hint: Option<usize>) -> usize {
135 hint.unwrap_or(0).min(MAX_PREALLOC_HINT)
136}
137
138pub trait ProtoElemJson: Sized {
162 fn serialize_proto_json<S: serde::Serializer>(v: &Self, s: S) -> Result<S::Ok, S::Error>;
164 fn deserialize_proto_json<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error>;
166 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#[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#[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#[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#[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#[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#[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#[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#[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
265struct 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 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
299macro_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
322pub 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
378struct 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
392pub 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
466pub 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
537pub 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
567pub mod proto_string {
573 use serde::{Deserializer, Serializer};
574
575 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 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#[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
644pub 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#[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
740enum ClosedEnumError {
742 Unknown(EnumJsonErrorReason),
745 Malformed(EnumJsonErrorReason),
748}
749
750fn 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 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#[inline]
802fn try_deserialize_enum<T: serde::de::DeserializeOwned>(
803 raw: serde_json::Value,
804) -> Result<Option<T>, serde_json::Error> {
805 let raw_is_string = raw.is_string();
807 let ignore = crate::json::ignore_unknown_enum_values();
808 #[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 #[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
829pub 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
887pub 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
964pub 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
979fn is_exact_integer(f: f64) -> bool {
988 f.is_finite() && f == (f as i128 as f64)
989}
990
991const MAX_SAFE_JSON_INTEGER_F64: f64 = 4_503_599_627_370_495.0;
1005
1006fn parse_int_from_str<I: TryFrom<i128>>(v: &str) -> Option<I> {
1009 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
1017fn parse_exact_decimal_int(v: &str) -> Option<i128> {
1024 let (mantissa, exp) = match v.split_once(['e', 'E']) {
1025 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 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 return Some(0);
1063 }
1064
1065 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
1087fn 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
1100macro_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
1216fn 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
1242pub 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 _ => 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 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
1348pub 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 _ => 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
1425pub mod bytes {
1437 use super::STANDARD;
1438 use base64::Engine as _;
1439 use serde::{Deserializer, Serializer};
1440
1441 pub fn serialize<S: Serializer>(value: &[u8], s: S) -> Result<S::Ok, S::Error> {
1446 s.serialize_str(&STANDARD.encode(value))
1447 }
1448
1449 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 d.deserialize_any(V).map(T::from)
1495 }
1496}
1497
1498proto_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
1513impl 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
1537impl<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
1552pub 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
1619pub 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
1682pub 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
1754struct 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
1763pub(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
1773macro_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 <Option<super::$mod_name::Helper> as serde::Deserialize>::deserialize(d)
1796 .map(|opt| opt.map(|h| h.0))
1797 }
1798
1799 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
1818pub 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 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
1856pub 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 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
1890pub 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
1933pub 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
1961pub 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
1981pub(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
1995pub 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 pub fn is_zero_f32(v: &f32) -> bool {
2022 v.to_bits() == 0
2023 }
2024 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 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
2062pub 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 #[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 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
2159pub 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
2192pub 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
2255pub 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#[cfg(test)]
2333mod tests;
2334
2335pub mod enum_list;
2337#[doc(hidden)]
2339#[cfg(feature = "zeroize")]
2340pub mod guarded_enum;
2341#[cfg(feature = "zeroize")]
2342mod guarded_key;
2343#[doc(hidden)]
2345#[cfg(feature = "zeroize")]
2346pub mod guarded_map;