pub mod buffered;
mod ignored_key;
mod map_key;
mod policy;
pub mod proto_list;
#[doc(hidden)]
pub use ignored_key::IgnoredObjectKey;
#[doc(hidden)]
pub mod wkt;
#[doc(hidden)]
pub use policy::{
bytes_policy, list_bytes_policy, list_string_policy, map_bytes_policy,
map_bytes_policy_bytes_key, map_bytes_policy_policy_key, map_bytes_policy_serde_key,
map_string_policy, map_string_policy_bytes_key, map_string_policy_policy_key,
map_string_policy_serde_key, opt_bytes_policy, opt_string_policy, policy_str_key_map,
repeated_bytes_policy, repeated_string_policy, string_policy, BytesPolicyJson, BytesPolicySeed,
BytesPolicySeqJson, StringPolicyJson, StringPolicySeed, StringPolicySeqJson,
ViewJsonErrorReason,
};
pub use policy::{ProtoBytesJson, ProtoStringJson};
use buffered::BufferedValue;
#[doc(hidden)]
pub fn deserialize_tagged<'de, V, A>(visitor: V, tagged: A) -> Result<V::Value, A::Error>
where
V: serde::de::Visitor<'de>,
A: serde::de::EnumAccess<'de>,
{
struct Seed<V>(V);
impl<'de, V: serde::de::Visitor<'de>> serde::de::DeserializeSeed<'de> for Seed<V> {
type Value = V::Value;
fn deserialize<D: serde::Deserializer<'de>>(self, d: D) -> Result<V::Value, D::Error> {
d.deserialize_any(self.0)
}
}
let (_, variant) = tagged.variant::<serde::de::IgnoredAny>()?;
serde::de::VariantAccess::newtype_variant_seed(variant, Seed(visitor))
}
#[doc(hidden)]
#[derive(Clone, Copy, Debug, thiserror::Error)]
#[non_exhaustive]
pub enum JsonValueError {
#[error("invalid protobuf map key")]
MapKey,
#[error("invalid i32 value")]
Int32,
#[error("invalid u32 value")]
Uint32,
#[error("invalid i64 value")]
Int64,
#[error("invalid u64 value")]
Uint64,
#[error("invalid float value, expected a finite f32 or a protobuf special value")]
Float,
#[error("invalid double value, expected a finite f64 or a protobuf special value")]
Double,
#[error("invalid base64 string")]
Base64,
#[error("invalid Duration string")]
Duration,
#[error("invalid RFC 3339 timestamp")]
Timestamp,
#[error("invalid FieldMask path, expected comma-separated lowerCamelCase paths")]
FieldMask,
#[error("invalid FieldMask path, it has no proto3 JSON representation")]
FieldMaskEncode,
#[error("invalid JSON payload for a registered Any message")]
AnyMessage,
#[error("invalid JSON value for a registered Any well-known type")]
AnyWellKnownType,
#[error("@type is not a valid type URL: it names no type")]
AnyEmptyType,
#[error("@type must contain a '/' (e.g. type.googleapis.com/pkg.Type)")]
AnyBareType,
#[error("Any with a well-known type requires a \"value\" key")]
AnyMissingValue,
#[error("Any with a well-known type has an unexpected field")]
AnyUnexpectedField,
#[error("Any type is not registered in the descriptor pool")]
AnyUnregisteredType,
#[error("Any: no type registry is installed to resolve a bare @type; install one with `set_type_registry`, or send a type URL")]
AnyBareTypeWithoutRegistry,
#[error("Any: bare @type has no JSON entry in the type registry; register the message or send a type URL")]
AnyBareTypeWithoutEntry,
#[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`")]
AnyOpaqueWithoutRegistry,
#[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`")]
AnyOpaqueWithoutEntry,
#[error("Any opaque payload field cannot be parsed")]
AnyOpaqueField,
}
#[doc(hidden)]
#[macro_export]
macro_rules! __buffa_reject_other_json_kinds {
($($kind:ident),* $(,)?) => {
$($crate::__buffa_reject_other_json_kinds!(@kind $kind);)*
};
(@kind bool) => {
fn visit_bool<__E: ::serde::de::Error>(
self,
_: ::core::primitive::bool,
) -> ::core::result::Result<Self::Value, __E> {
::core::result::Result::Err(__E::invalid_type(
::serde::de::Unexpected::Other("boolean"),
&self,
))
}
};
(@kind i64) => {
fn visit_i64<__E: ::serde::de::Error>(
self,
_: ::core::primitive::i64,
) -> ::core::result::Result<Self::Value, __E> {
::core::result::Result::Err(__E::invalid_type(
::serde::de::Unexpected::Other("integer"),
&self,
))
}
};
(@kind u64) => {
fn visit_u64<__E: ::serde::de::Error>(
self,
_: ::core::primitive::u64,
) -> ::core::result::Result<Self::Value, __E> {
::core::result::Result::Err(__E::invalid_type(
::serde::de::Unexpected::Other("integer"),
&self,
))
}
};
(@kind i128) => {
fn visit_i128<__E: ::serde::de::Error>(
self,
value: ::core::primitive::i128,
) -> ::core::result::Result<Self::Value, __E> {
if let ::core::result::Result::Ok(value) = <::core::primitive::i64 as ::core::convert::TryFrom<::core::primitive::i128>>::try_from(value) {
return ::serde::de::Visitor::visit_i64(self, value);
}
if let ::core::result::Result::Ok(value) = <::core::primitive::u64 as ::core::convert::TryFrom<::core::primitive::i128>>::try_from(value) {
return ::serde::de::Visitor::visit_u64(self, value);
}
::core::result::Result::Err(__E::invalid_type(
::serde::de::Unexpected::Other("integer"),
&self,
))
}
};
(@kind u128) => {
fn visit_u128<__E: ::serde::de::Error>(
self,
value: ::core::primitive::u128,
) -> ::core::result::Result<Self::Value, __E> {
if let ::core::result::Result::Ok(value) = <::core::primitive::u64 as ::core::convert::TryFrom<::core::primitive::u128>>::try_from(value) {
return ::serde::de::Visitor::visit_u64(self, value);
}
::core::result::Result::Err(__E::invalid_type(
::serde::de::Unexpected::Other("integer"),
&self,
))
}
};
(@kind f64) => {
fn visit_f64<__E: ::serde::de::Error>(
self,
_: ::core::primitive::f64,
) -> ::core::result::Result<Self::Value, __E> {
::core::result::Result::Err(__E::invalid_type(
::serde::de::Unexpected::Other("floating-point number"),
&self,
))
}
};
(@kind str) => {
fn visit_str<__E: ::serde::de::Error>(
self,
_: &::core::primitive::str,
) -> ::core::result::Result<Self::Value, __E> {
::core::result::Result::Err(__E::invalid_type(
::serde::de::Unexpected::Other("string"),
&self,
))
}
};
(@kind string) => {
fn visit_string<__E: ::serde::de::Error>(
self,
value: $crate::alloc::string::String,
) -> ::core::result::Result<Self::Value, __E> {
$crate::json_helpers::discard_rejected_text(value);
::core::result::Result::Err(__E::invalid_type(
::serde::de::Unexpected::Other("string"),
&self,
))
}
};
(@kind bytes) => {
fn visit_bytes<__E: ::serde::de::Error>(
self,
_: &[::core::primitive::u8],
) -> ::core::result::Result<Self::Value, __E> {
::core::result::Result::Err(__E::invalid_type(
::serde::de::Unexpected::Other("bytes"),
&self,
))
}
};
(@kind byte_buf) => {
fn visit_byte_buf<__E: ::serde::de::Error>(
self,
value: $crate::alloc::vec::Vec<::core::primitive::u8>,
) -> ::core::result::Result<Self::Value, __E> {
$crate::json_helpers::discard_rejected_bytes(value);
::core::result::Result::Err(__E::invalid_type(
::serde::de::Unexpected::Other("bytes"),
&self,
))
}
};
(@kind unit) => {
fn visit_unit<__E: ::serde::de::Error>(self) -> ::core::result::Result<Self::Value, __E> {
::core::result::Result::Err(__E::invalid_type(
::serde::de::Unexpected::Other("null"),
&self,
))
}
};
(@kind seq) => {
fn visit_seq<__A: ::serde::de::SeqAccess<'de>>(
self,
_: __A,
) -> ::core::result::Result<Self::Value, __A::Error> {
::core::result::Result::Err(<__A::Error as ::serde::de::Error>::invalid_type(
::serde::de::Unexpected::Other("array"),
&self,
))
}
};
(@kind map) => {
fn visit_map<__A: ::serde::de::MapAccess<'de>>(
self,
_: __A,
) -> ::core::result::Result<Self::Value, __A::Error> {
::core::result::Result::Err(<__A::Error as ::serde::de::Error>::invalid_type(
::serde::de::Unexpected::Other("object"),
&self,
))
}
};
}
#[doc(hidden)]
pub use crate::__buffa_reject_other_json_kinds as reject_other_json_kinds;
#[doc(hidden)]
pub fn discard_rejected_text(text: alloc::string::String) {
discard_rejected_bytes(text.into_bytes());
}
#[doc(hidden)]
pub fn discard_rejected_bytes(bytes: alloc::vec::Vec<u8>) {
#[cfg(feature = "zeroize")]
{
let mut bytes = bytes;
zeroize::Zeroize::zeroize(&mut bytes);
}
#[cfg(not(feature = "zeroize"))]
drop(bytes);
}
#[doc(hidden)]
pub const SERDE_JSON_NUMBER_KEY: &str = "$serde_json::private::Number";
macro_rules! visit_wide_ints {
($reason:expr) => {
fn visit_i128<E: serde::de::Error>(self, v: i128) -> Result<Self::Value, E> {
if let Ok(v) = i64::try_from(v) {
return serde::de::Visitor::visit_i64(self, v);
}
match u64::try_from(v) {
Ok(v) => serde::de::Visitor::visit_u64(self, v),
Err(_) => Err(E::custom($reason)),
}
}
fn visit_u128<E: serde::de::Error>(self, v: u128) -> Result<Self::Value, E> {
match u64::try_from(v) {
Ok(v) => serde::de::Visitor::visit_u64(self, v),
Err(_) => Err(E::custom($reason)),
}
}
};
}
use base64::alphabet;
use base64::engine::{
general_purpose::STANDARD, DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig,
};
const LENIENT_CFG: GeneralPurposeConfig = GeneralPurposeConfig::new()
.with_decode_allow_trailing_bits(true)
.with_decode_padding_mode(DecodePaddingMode::Indifferent);
static STANDARD_LENIENT: GeneralPurpose = GeneralPurpose::new(&alphabet::STANDARD, LENIENT_CFG);
static URL_SAFE_LENIENT: GeneralPurpose = GeneralPurpose::new(&alphabet::URL_SAFE, LENIENT_CFG);
const MAX_PREALLOC_HINT: usize = 4096;
#[inline]
fn clamp_size_hint(hint: Option<usize>) -> usize {
hint.unwrap_or(0).min(MAX_PREALLOC_HINT)
}
pub trait ProtoElemJson: Sized {
fn serialize_proto_json<S: serde::Serializer>(v: &Self, s: S) -> Result<S::Ok, S::Error>;
fn deserialize_proto_json<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error>;
fn deserialize_proto_json_null<E: serde::de::Error>() -> Result<Self, E> {
Err(E::custom(
"null is not a valid repeated-field element or map value",
))
}
}
#[doc(hidden)]
pub struct ProtoJson<'a, T>(pub &'a T);
impl<T: ProtoElemJson> serde::Serialize for ProtoJson<'_, T> {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
T::serialize_proto_json(self.0, s)
}
}
#[doc(hidden)]
pub struct BytesJson<'a>(pub &'a [u8]);
impl serde::Serialize for BytesJson<'_> {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
bytes::serialize(self.0, s)
}
}
#[doc(hidden)]
pub struct ClosedEnumJson<'a, E>(pub &'a E);
impl<E: crate::Enumeration> serde::Serialize for ClosedEnumJson<'_, E> {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
closed_enum::serialize(self.0, s)
}
}
#[doc(hidden)]
pub struct MapKeyJson<'a, T: ?Sized>(pub &'a T);
impl<T: ?Sized + core::fmt::Display> serde::Serialize for MapKeyJson<'_, T> {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.collect_str(self.0)
}
}
#[doc(hidden)]
pub struct RepeatedJson<'a, T>(pub &'a [T]);
impl<T: ProtoElemJson> serde::Serialize for RepeatedJson<'_, T> {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
proto_seq::serialize(self.0, s)
}
}
#[doc(hidden)]
pub struct BytesSeqJson<'a>(pub &'a [&'a [u8]]);
impl serde::Serialize for BytesSeqJson<'_> {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
use serde::ser::SerializeSeq;
let mut seq = s.serialize_seq(Some(self.0.len()))?;
for v in self.0 {
seq.serialize_element(&BytesJson(v))?;
}
seq.end()
}
}
#[doc(hidden)]
pub struct EnumSeqJson<'a, E: crate::Enumeration>(pub &'a [crate::EnumValue<E>]);
impl<E: crate::Enumeration> serde::Serialize for EnumSeqJson<'_, E> {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
repeated_enum::serialize(self.0, s)
}
}
#[doc(hidden)]
pub struct ClosedEnumSeqJson<'a, E>(pub &'a [E]);
impl<E: crate::Enumeration> serde::Serialize for ClosedEnumSeqJson<'_, E> {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
repeated_closed_enum::serialize(self.0, s)
}
}
struct ProtoElemSeed<T>(core::marker::PhantomData<T>);
impl<'de, T: ProtoElemJson> serde::de::DeserializeSeed<'de> for ProtoElemSeed<T> {
type Value = T;
fn deserialize<D: serde::Deserializer<'de>>(self, d: D) -> Result<T, D::Error> {
struct NoNull<T>(core::marker::PhantomData<T>);
impl<'de, T: ProtoElemJson> serde::de::Visitor<'de> for NoNull<T> {
type Value = T;
fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("a non-null value")
}
fn visit_none<E: serde::de::Error>(self) -> Result<T, E> {
T::deserialize_proto_json_null()
}
fn visit_unit<E: serde::de::Error>(self) -> Result<T, E> {
T::deserialize_proto_json_null()
}
fn visit_some<D2: serde::Deserializer<'de>>(self, d: D2) -> Result<T, D2::Error> {
T::deserialize_proto_json(d)
}
crate::reject_other_json_kinds!(
bool, i64, u64, i128, u128, f64, str, string, bytes, byte_buf
);
}
d.deserialize_option(NoNull::<T>(core::marker::PhantomData))
}
}
macro_rules! proto_elem_json_delegate {
($ty:ty, $mod:ident, null = $expected:literal) => {
impl ProtoElemJson for $ty {
fn serialize_proto_json<S: serde::Serializer>(
v: &Self,
s: S,
) -> Result<S::Ok, S::Error> {
$mod::serialize(v, s)
}
fn deserialize_proto_json<'de, D: serde::Deserializer<'de>>(
d: D,
) -> Result<Self, D::Error> {
$mod::deserialize(d)
}
fn deserialize_proto_json_null<E: serde::de::Error>() -> Result<Self, E> {
Err(E::invalid_type(serde::de::Unexpected::Unit, &$expected))
}
}
};
($ty:ty, $mod:ident) => {
impl ProtoElemJson for $ty {
fn serialize_proto_json<S: serde::Serializer>(
v: &Self,
s: S,
) -> Result<S::Ok, S::Error> {
$mod::serialize(v, s)
}
fn deserialize_proto_json<'de, D: serde::Deserializer<'de>>(
d: D,
) -> Result<Self, D::Error> {
$mod::deserialize(d)
}
}
};
}
pub mod proto_seq {
use super::{ProtoElemJson, ProtoElemSeed, ProtoJson};
use alloc::vec::Vec;
use serde::{Deserializer, Serializer};
pub fn serialize<T: ProtoElemJson, S: Serializer>(v: &[T], s: S) -> Result<S::Ok, S::Error> {
use serde::ser::SerializeSeq;
let mut seq = s.serialize_seq(Some(v.len()))?;
for elem in v {
seq.serialize_element(&ProtoJson(elem))?;
}
seq.end()
}
pub fn deserialize<'de, T, C, D>(d: D) -> Result<C, D::Error>
where
T: ProtoElemJson,
C: From<Vec<T>>,
D: Deserializer<'de>,
{
struct V<T>(core::marker::PhantomData<T>);
impl<'de, T: ProtoElemJson> serde::de::Visitor<'de> for V<T> {
type Value = Vec<T>;
fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("an array or null")
}
fn visit_enum<A: serde::de::EnumAccess<'de>>(
self,
tagged: A,
) -> Result<Self::Value, A::Error> {
super::deserialize_tagged(self, tagged)
}
fn visit_unit<E>(self) -> Result<Vec<T>, E> {
Ok(Vec::new())
}
crate::reject_other_json_kinds!(
bool, i64, u64, i128, u128, f64, str, string, bytes, byte_buf
);
fn visit_seq<A: serde::de::SeqAccess<'de>>(
self,
mut seq: A,
) -> Result<Vec<T>, A::Error> {
let mut out = Vec::with_capacity(super::clamp_size_hint(seq.size_hint()));
while let Some(elem) =
seq.next_element_seed(ProtoElemSeed::<T>(core::marker::PhantomData))?
{
out.push(elem);
}
Ok(out)
}
}
d.deserialize_any(V::<T>(core::marker::PhantomData))
.map(C::from)
}
}
struct DisplayKey<'a, K: ?Sized>(&'a K);
impl<K: core::fmt::Display + ?Sized> serde::Serialize for DisplayKey<'_, K> {
#[inline]
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.collect_str(self.0)
}
}
#[doc(hidden)]
pub mod native_seq {
pub fn serialize<C: serde::Serialize, S: serde::Serializer>(
v: &C,
s: S,
) -> Result<S::Ok, S::Error> {
serde::Serialize::serialize(v, s)
}
pub fn deserialize<'de, T, C, D>(d: D) -> Result<C, D::Error>
where
T: super::ProtoElemJson,
C: From<alloc::vec::Vec<T>> + serde::Deserialize<'de> + Default,
D: serde::Deserializer<'de>,
{
if d.is_human_readable() {
super::proto_seq::deserialize(d)
} else {
super::null_as_default(d)
}
}
}
#[doc(hidden)]
pub mod native_str_key_map {
pub fn serialize<C: serde::Serialize, S: serde::Serializer>(
v: &C,
s: S,
) -> Result<S::Ok, S::Error> {
serde::Serialize::serialize(v, s)
}
pub fn deserialize<'de, C, D>(d: D) -> Result<C, D::Error>
where
C: crate::map_codec::MapStorage + serde::Deserialize<'de> + Default,
C::Key: serde::Deserialize<'de>,
C::Value: super::ProtoElemJson,
D: serde::Deserializer<'de>,
{
if d.is_human_readable() {
super::proto_str_key_map::deserialize(d)
} else {
super::null_as_default(d)
}
}
}
pub mod proto_map {
use super::{ProtoElemJson, ProtoElemSeed, ProtoJson};
use crate::map_codec::MapStorage;
use alloc::string::String;
use core::fmt::Display;
use core::str::FromStr;
use serde::{Deserializer, Serializer};
pub fn serialize<C, S>(m: &C, s: S) -> Result<S::Ok, S::Error>
where
C: MapStorage,
C::Key: Display,
C::Value: ProtoElemJson,
S: Serializer,
{
use serde::ser::SerializeMap;
let mut map = s.serialize_map(Some(m.storage_len()))?;
for (k, v) in m.storage_iter() {
map.serialize_entry(&super::DisplayKey(k), &ProtoJson(v))?;
}
map.end()
}
pub fn deserialize<'de, C, D>(d: D) -> Result<C, D::Error>
where
C: MapStorage + Default,
C::Key: FromStr,
C::Value: ProtoElemJson,
D: Deserializer<'de>,
{
struct Vis<C>(core::marker::PhantomData<C>);
impl<'de, C> serde::de::Visitor<'de> for Vis<C>
where
C: MapStorage + Default,
C::Key: FromStr,
C::Value: ProtoElemJson,
{
type Value = C;
fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("a JSON object with string keys, or null")
}
fn visit_unit<E>(self) -> Result<Self::Value, E> {
Ok(C::default())
}
crate::reject_other_json_kinds!(
bool, i64, u64, i128, u128, f64, str, string, bytes, byte_buf
);
fn visit_map<A: serde::de::MapAccess<'de>>(
self,
mut map: A,
) -> Result<Self::Value, A::Error> {
let mut out = C::default();
while let Some(key) = map.next_key::<String>()? {
let k = <C::Key as FromStr>::from_str(&key)
.map_err(|_| serde::de::Error::custom(super::JsonValueError::MapKey))?;
let k = crate::erasing::Erasing::new(k, C::storage_erase_key);
let v =
map.next_value_seed(ProtoElemSeed::<C::Value>(core::marker::PhantomData))?;
out.storage_insert(k.into_inner(), v);
}
Ok(out)
}
}
d.deserialize_any(Vis::<C>(core::marker::PhantomData))
}
}
pub mod proto_str_key_map {
use super::{ProtoElemJson, ProtoElemSeed, ProtoJson};
use crate::map_codec::MapStorage;
use serde::{Deserializer, Serializer};
pub fn serialize<C, S>(m: &C, s: S) -> Result<S::Ok, S::Error>
where
C: MapStorage,
C::Key: serde::Serialize,
C::Value: ProtoElemJson,
S: Serializer,
{
use serde::ser::SerializeMap;
let mut map = s.serialize_map(Some(m.storage_len()))?;
for (k, v) in m.storage_iter() {
map.serialize_entry(k, &ProtoJson(v))?;
}
map.end()
}
pub fn deserialize<'de, C, D>(d: D) -> Result<C, D::Error>
where
C: MapStorage + Default,
C::Key: serde::Deserialize<'de>,
C::Value: ProtoElemJson,
D: Deserializer<'de>,
{
struct Vis<C>(core::marker::PhantomData<C>);
impl<'de, C> serde::de::Visitor<'de> for Vis<C>
where
C: MapStorage + Default,
C::Key: serde::Deserialize<'de>,
C::Value: ProtoElemJson,
{
type Value = C;
fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("a JSON object with string keys, or null")
}
fn visit_enum<A: serde::de::EnumAccess<'de>>(
self,
tagged: A,
) -> Result<Self::Value, A::Error> {
super::deserialize_tagged(self, tagged)
}
fn visit_unit<E>(self) -> Result<Self::Value, E> {
Ok(C::default())
}
crate::reject_other_json_kinds!(
bool, i64, u64, i128, u128, f64, str, string, bytes, byte_buf
);
fn visit_map<A: serde::de::MapAccess<'de>>(
self,
mut map: A,
) -> Result<Self::Value, A::Error> {
let mut out = C::default();
while let Some(k) = map.next_key::<C::Key>()? {
let k = crate::erasing::Erasing::new(k, C::storage_erase_key);
let v =
map.next_value_seed(ProtoElemSeed::<C::Value>(core::marker::PhantomData))?;
out.storage_insert(k.into_inner(), v);
}
Ok(out)
}
}
d.deserialize_any(Vis::<C>(core::marker::PhantomData))
}
}
pub mod proto_bool {
use serde::{Deserializer, Serializer};
pub fn serialize<S: Serializer>(value: &bool, s: S) -> Result<S::Ok, S::Error> {
s.serialize_bool(*value)
}
pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<bool, D::Error> {
struct V;
impl<'de> serde::de::Visitor<'de> for V {
type Value = bool;
fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("a boolean or null")
}
fn visit_unit<E>(self) -> Result<bool, E> {
Ok(false)
}
fn visit_bool<E>(self, v: bool) -> Result<bool, E> {
Ok(v)
}
crate::reject_other_json_kinds!(
i64, u64, i128, u128, f64, str, string, bytes, byte_buf
);
}
d.deserialize_any(V)
}
}
pub mod proto_string {
use serde::{Deserializer, Serializer};
pub fn serialize<T: AsRef<str> + ?Sized, S: Serializer>(
value: &T,
s: S,
) -> Result<S::Ok, S::Error> {
s.serialize_str(value.as_ref())
}
pub fn deserialize<'de, T, D>(d: D) -> Result<T, D::Error>
where
T: crate::ProtoString,
D: Deserializer<'de>,
{
struct V<T>(core::marker::PhantomData<T>);
impl<'de, T> serde::de::Visitor<'de> for V<T>
where
T: crate::ProtoString,
{
type Value = T;
fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("a string or null")
}
fn visit_unit<E>(self) -> Result<T, E> {
Ok(T::copy_from_str(""))
}
fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<T, E> {
Ok(T::copy_from_str(v))
}
fn visit_string<E>(self, v: alloc::string::String) -> Result<T, E> {
Ok(T::from(v))
}
crate::reject_other_json_kinds!(bool, i64, u64, i128, u128, f64, bytes, byte_buf);
}
d.deserialize_any(V::<T>(core::marker::PhantomData))
}
}
#[doc(hidden)]
#[derive(Clone, Copy, Debug, thiserror::Error)]
#[non_exhaustive]
pub enum EnumJsonErrorReason {
#[error("unknown enum name")]
UnknownName,
#[error("unknown enum number")]
UnknownNumber,
#[error("enum number out of i32 range")]
OutOfRange,
#[error("expected a protobuf enum name or integer")]
InvalidType,
#[error("expected a protobuf list or null")]
InvalidListType,
#[error("expected a protobuf map or null")]
InvalidMapType,
}
macro_rules! reject_container_scalar_values {
($reason:ident) => {
fn visit_string<Err: serde::de::Error>(
self,
value: alloc::string::String,
) -> Result<Self::Value, Err> {
crate::json_helpers::discard_rejected_text(value);
Err(Err::custom(
crate::json_helpers::EnumJsonErrorReason::$reason,
))
}
fn visit_str<Err: serde::de::Error>(self, _: &str) -> Result<Self::Value, Err> {
Err(Err::custom(
crate::json_helpers::EnumJsonErrorReason::$reason,
))
}
fn visit_i64<Err: serde::de::Error>(self, _: i64) -> Result<Self::Value, Err> {
Err(Err::custom(
crate::json_helpers::EnumJsonErrorReason::$reason,
))
}
fn visit_u64<Err: serde::de::Error>(self, _: u64) -> Result<Self::Value, Err> {
Err(Err::custom(
crate::json_helpers::EnumJsonErrorReason::$reason,
))
}
fn visit_i128<Err: serde::de::Error>(self, _: i128) -> Result<Self::Value, Err> {
Err(Err::custom(
crate::json_helpers::EnumJsonErrorReason::$reason,
))
}
fn visit_u128<Err: serde::de::Error>(self, _: u128) -> Result<Self::Value, Err> {
Err(Err::custom(
crate::json_helpers::EnumJsonErrorReason::$reason,
))
}
fn visit_f64<Err: serde::de::Error>(self, _: f64) -> Result<Self::Value, Err> {
Err(Err::custom(
crate::json_helpers::EnumJsonErrorReason::$reason,
))
}
fn visit_bool<Err: serde::de::Error>(self, _: bool) -> Result<Self::Value, Err> {
Err(Err::custom(
crate::json_helpers::EnumJsonErrorReason::$reason,
))
}
};
}
pub mod proto_enum {
use super::EnumJsonErrorReason;
use serde::{Deserializer, Serializer};
pub fn serialize<E: crate::Enumeration, S: Serializer>(
value: &crate::EnumValue<E>,
s: S,
) -> Result<S::Ok, S::Error> {
serde::Serialize::serialize(value, s)
}
pub fn deserialize<'de, E: crate::Enumeration, D: Deserializer<'de>>(
d: D,
) -> Result<crate::EnumValue<E>, D::Error> {
struct V<E>(core::marker::PhantomData<E>);
impl<'de, E: crate::Enumeration> serde::de::Visitor<'de> for V<E> {
type Value = crate::EnumValue<E>;
fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("a protobuf enum name string, integer value, or null")
}
fn visit_unit<Err>(self) -> Result<crate::EnumValue<E>, Err> {
Ok(crate::EnumValue::from(0))
}
fn visit_i64<Err: serde::de::Error>(self, v: i64) -> Result<crate::EnumValue<E>, Err> {
let i =
i32::try_from(v).map_err(|_| Err::custom(EnumJsonErrorReason::OutOfRange))?;
Ok(crate::EnumValue::from(i))
}
fn visit_u64<Err: serde::de::Error>(self, v: u64) -> Result<crate::EnumValue<E>, Err> {
let i =
i32::try_from(v).map_err(|_| Err::custom(EnumJsonErrorReason::OutOfRange))?;
Ok(crate::EnumValue::from(i))
}
fn visit_i128<Err: serde::de::Error>(self, v: i128) -> Result<Self::Value, Err> {
let v =
i64::try_from(v).map_err(|_| Err::custom(EnumJsonErrorReason::OutOfRange))?;
self.visit_i64(v)
}
fn visit_u128<Err: serde::de::Error>(self, v: u128) -> Result<Self::Value, Err> {
let v =
u64::try_from(v).map_err(|_| Err::custom(EnumJsonErrorReason::OutOfRange))?;
self.visit_u64(v)
}
fn visit_f64<Err: serde::de::Error>(self, _: f64) -> Result<Self::Value, Err> {
Err(Err::custom(EnumJsonErrorReason::InvalidType))
}
fn visit_bool<Err: serde::de::Error>(self, _: bool) -> Result<Self::Value, Err> {
Err(Err::custom(EnumJsonErrorReason::InvalidType))
}
#[cfg(feature = "zeroize")]
fn visit_string<Err: serde::de::Error>(
self,
value: alloc::string::String,
) -> Result<Self::Value, Err> {
let value = zeroize::Zeroizing::new(value);
self.visit_str(&value)
}
#[cfg(feature = "zeroize")]
fn visit_byte_buf<Err: serde::de::Error>(
self,
value: alloc::vec::Vec<u8>,
) -> Result<Self::Value, Err> {
let value = zeroize::Zeroizing::new(value);
self.visit_bytes(&value)
}
fn visit_str<Err: serde::de::Error>(self, v: &str) -> Result<crate::EnumValue<E>, Err> {
match E::from_proto_name(v) {
Some(e) => Ok(crate::EnumValue::from(e)),
None => {
if crate::json::ignore_unknown_enum_values() {
return Ok(crate::EnumValue::from(0));
}
Err(Err::custom(EnumJsonErrorReason::UnknownName))
}
}
}
}
d.deserialize_any(V(core::marker::PhantomData))
}
}
#[inline]
fn try_deserialize_closed_enum<E: crate::Enumeration + Default>(
raw: &serde_json::Value,
) -> Result<Option<E>, EnumJsonErrorReason> {
match decode_closed_enum::<E>(raw) {
Ok(e) => Ok(Some(e)),
Err(ClosedEnumError::Unknown(_)) if crate::json::ignore_unknown_enum_values() => Ok(None),
Err(ClosedEnumError::Unknown(reason) | ClosedEnumError::Malformed(reason)) => Err(reason),
}
}
enum ClosedEnumError {
Unknown(EnumJsonErrorReason),
Malformed(EnumJsonErrorReason),
}
fn decode_closed_enum<E: crate::Enumeration + Default>(
raw: &serde_json::Value,
) -> Result<E, ClosedEnumError> {
use serde_json::Value;
match raw {
Value::String(s) => {
E::from_proto_name(s).ok_or(ClosedEnumError::Unknown(EnumJsonErrorReason::UnknownName))
}
Value::Number(n) if n.is_f64() => {
Err(ClosedEnumError::Malformed(EnumJsonErrorReason::InvalidType))
}
Value::Number(n) => {
let v32 = n
.as_i64()
.and_then(|v| i32::try_from(v).ok())
.or_else(|| n.as_u64().and_then(|v| i32::try_from(v).ok()))
.ok_or(ClosedEnumError::Malformed(EnumJsonErrorReason::OutOfRange))?;
E::from_i32(v32).ok_or(ClosedEnumError::Unknown(EnumJsonErrorReason::UnknownNumber))
}
Value::Null | Value::Bool(_) | Value::Array(_) | Value::Object(_) => {
Err(ClosedEnumError::Malformed(EnumJsonErrorReason::InvalidType))
}
}
}
#[inline]
fn try_deserialize_enum<T: serde::de::DeserializeOwned>(
raw: serde_json::Value,
) -> Result<Option<T>, serde_json::Error> {
let raw_is_string = raw.is_string();
let ignore = crate::json::ignore_unknown_enum_values();
#[cfg(feature = "std")]
let result = {
let strict = crate::json::JsonParseOptions {
ignore_unknown_enum_values: false,
..Default::default()
};
crate::json::with_json_parse_options(&strict, || serde_json::from_value::<T>(raw))
};
#[cfg(not(feature = "std"))]
let result = serde_json::from_value::<T>(raw);
match result {
Ok(v) => Ok(Some(v)),
Err(_) if ignore && raw_is_string => Ok(None),
Err(e) => Err(e),
}
}
pub mod repeated_enum {
use alloc::vec::Vec;
use serde::{Deserializer, Serializer};
pub fn serialize<E: crate::Enumeration, S: Serializer>(
value: &[crate::EnumValue<E>],
s: S,
) -> Result<S::Ok, S::Error> {
if !E::IS_NULL_VALUE || !s.is_human_readable() {
return serde::Serialize::serialize(value, s);
}
use serde::ser::SerializeSeq as _;
let mut sequence = s.serialize_seq(Some(value.len()))?;
for element in value {
if element.to_i32() == 0 {
sequence.serialize_element(&())?;
} else {
sequence.serialize_element(element)?;
}
}
sequence.end()
}
pub fn deserialize<'de, E, C, D>(d: D) -> Result<C, D::Error>
where
E: crate::Enumeration,
C: From<Vec<crate::EnumValue<E>>>,
D: Deserializer<'de>,
{
struct V<E>(core::marker::PhantomData<E>);
impl<'de, E: crate::Enumeration> serde::de::Visitor<'de> for V<E> {
type Value = Vec<crate::EnumValue<E>>;
fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("a list of enum values or null")
}
fn visit_unit<Err>(self) -> Result<Vec<crate::EnumValue<E>>, Err> {
Ok(Vec::new())
}
reject_container_scalar_values!(InvalidListType);
crate::__buffa_reject_other_json_kinds!(bytes, byte_buf);
fn visit_seq<A: serde::de::SeqAccess<'de>>(
self,
mut seq: A,
) -> Result<Vec<crate::EnumValue<E>>, A::Error> {
let mut out = Vec::with_capacity(super::clamp_size_hint(seq.size_hint()));
while let Some(super::BufferedValue(raw)) = seq.next_element()? {
if raw.is_null() && !E::IS_NULL_VALUE {
return Err(serde::de::Error::custom(
super::enum_list::ErrorReason::Null,
));
}
match super::try_deserialize_enum::<crate::EnumValue<E>>(raw) {
Ok(Some(v)) => out.push(v),
Ok(None) => continue,
Err(e) => return Err(serde::de::Error::custom(e)),
}
}
Ok(out)
}
}
d.deserialize_any(V::<E>(core::marker::PhantomData))
.map(C::from)
}
}
pub mod map_enum {
use crate::map_codec::MapStorage;
use serde::{Deserializer, Serializer};
pub fn serialize<C, S>(value: &C, s: S) -> Result<S::Ok, S::Error>
where
C: MapStorage,
C::Key: serde::Serialize,
C::Value: serde::Serialize,
S: Serializer,
{
use serde::ser::SerializeMap;
let mut map = s.serialize_map(Some(value.storage_len()))?;
for (k, v) in value.storage_iter() {
map.serialize_entry(k, v)?;
}
map.end()
}
pub fn deserialize<'de, C, D>(d: D) -> Result<C, D::Error>
where
C: MapStorage + Default,
C::Key: serde::Deserialize<'de>,
C::Value: serde::de::DeserializeOwned,
D: Deserializer<'de>,
{
struct V<C>(core::marker::PhantomData<C>);
impl<'de, C> serde::de::Visitor<'de> for V<C>
where
C: MapStorage + Default,
C::Key: serde::Deserialize<'de>,
C::Value: serde::de::DeserializeOwned,
{
type Value = C;
fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("a map with enum values or null")
}
fn visit_unit<Err>(self) -> Result<Self::Value, Err> {
Ok(C::default())
}
reject_container_scalar_values!(InvalidMapType);
crate::__buffa_reject_other_json_kinds!(bytes, byte_buf);
fn visit_map<A: serde::de::MapAccess<'de>>(
self,
mut map: A,
) -> Result<Self::Value, A::Error> {
let mut out = C::default();
while let Some(key) = map.next_key_seed(super::map_key::KeySeed::<C::Key>::new())? {
let key = crate::erasing::Erasing::new(key, C::storage_erase_key);
let super::BufferedValue(raw) = map.next_value()?;
match super::try_deserialize_enum::<C::Value>(raw) {
Ok(Some(v)) => {
out.storage_insert(key.into_inner(), v);
}
Ok(None) => continue,
Err(e) => return Err(serde::de::Error::custom(e)),
}
}
Ok(out)
}
}
d.deserialize_any(V::<C>(core::marker::PhantomData))
}
}
pub fn null_as_default<'de, D, T>(d: D) -> Result<T, D::Error>
where
D: serde::Deserializer<'de>,
T: Default + serde::Deserialize<'de>,
{
<Option<T> as serde::Deserialize>::deserialize(d).map(|opt| opt.unwrap_or_default())
}
fn is_exact_integer(f: f64) -> bool {
f.is_finite() && f == (f as i128 as f64)
}
const MAX_SAFE_JSON_INTEGER_F64: f64 = 4_503_599_627_370_495.0;
fn parse_int_from_str<I: TryFrom<i128>>(v: &str) -> Option<I> {
if let Ok(n) = v.parse::<i128>() {
return I::try_from(n).ok();
}
let n = parse_exact_decimal_int(v)?;
I::try_from(n).ok()
}
fn parse_exact_decimal_int(v: &str) -> Option<i128> {
let (mantissa, exp) = match v.split_once(['e', 'E']) {
Some((m, e)) => (m, e.parse::<i64>().ok()?),
None => (v, 0),
};
let (negative, mantissa) = match mantissa.strip_prefix('-') {
Some(rest) => (true, rest),
None => (false, mantissa.strip_prefix('+').unwrap_or(mantissa)),
};
let (int_part, frac_part) = mantissa
.split_once('.')
.map_or((mantissa, ""), |(i, f)| (i, f));
if int_part.is_empty() && frac_part.is_empty() {
return None;
}
let frac_part = frac_part.trim_end_matches('0');
let (int_part, trailing_zeros) = if frac_part.is_empty() {
let trimmed = int_part.trim_end_matches('0');
(trimmed, int_part.len() - trimmed.len())
} else {
(int_part, 0)
};
let mut significand = 0i128;
for digit in int_part.bytes().chain(frac_part.bytes()) {
if !digit.is_ascii_digit() {
return None;
}
significand = significand
.checked_mul(10)?
.checked_add(i128::from(digit - b'0'))?;
}
if significand == 0 {
return Some(0);
}
let scale = exp
.checked_add(trailing_zeros as i64)?
.checked_sub(frac_part.len() as i64)?;
if scale >= 0 {
let pow10 = 10i128.checked_pow(u32::try_from(scale).ok()?)?;
significand = significand.checked_mul(pow10)?;
} else {
let divisor = 10i128.checked_pow(u32::try_from(scale.unsigned_abs()).ok()?)?;
if significand % divisor != 0 {
return None;
}
significand /= divisor;
}
if negative {
significand.checked_neg()
} else {
Some(significand)
}
}
fn f64_to_int<I: TryFrom<i128>>(v: f64) -> Option<I> {
if !(-MAX_SAFE_JSON_INTEGER_F64..=MAX_SAFE_JSON_INTEGER_F64).contains(&v) {
return None;
}
if !is_exact_integer(v) {
return None;
}
I::try_from(v as i128).ok()
}
macro_rules! int_serde_module {
(
$mod_name:ident, $int_type:ty,
doc = $doc:expr,
serialize_body = |$val:ident, $ser:ident| $ser_body:expr,
expecting = $expecting:expr,
reason = $reason:ident,
parse_str = $parse_str:ident $(,)?
) => {
#[doc = $doc]
pub mod $mod_name {
use super::*;
use serde::{Deserializer, Serializer};
pub fn serialize<S: Serializer>(value: &$int_type, s: S) -> Result<S::Ok, S::Error> {
let $val = value;
let $ser = s;
$ser_body
}
pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<$int_type, D::Error> {
struct Vis;
impl<'de> serde::de::Visitor<'de> for Vis {
type Value = $int_type;
fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str($expecting)
}
fn visit_unit<E>(self) -> Result<$int_type, E> {
Ok(0)
}
fn visit_bool<E: serde::de::Error>(self, _: bool) -> Result<$int_type, E> {
Err(E::custom(JsonValueError::$reason))
}
fn visit_i64<E: serde::de::Error>(self, v: i64) -> Result<$int_type, E> {
<$int_type>::try_from(v).map_err(|_| E::custom(JsonValueError::$reason))
}
fn visit_u64<E: serde::de::Error>(self, v: u64) -> Result<$int_type, E> {
<$int_type>::try_from(v).map_err(|_| E::custom(JsonValueError::$reason))
}
fn visit_f64<E: serde::de::Error>(self, v: f64) -> Result<$int_type, E> {
f64_to_int::<$int_type>(v).ok_or_else(|| E::custom(JsonValueError::$reason))
}
fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<$int_type, E> {
$parse_str(v).ok_or_else(|| E::custom(JsonValueError::$reason))
}
fn visit_string<E: serde::de::Error>(
self,
value: alloc::string::String,
) -> Result<$int_type, E> {
#[cfg(feature = "zeroize")]
let value = zeroize::Zeroizing::new(value);
self.visit_str(&value)
}
visit_wide_ints!(JsonValueError::$reason);
crate::reject_other_json_kinds!(bytes, byte_buf);
}
d.deserialize_any(Vis)
}
}
};
}
int_serde_module!(
int32,
i32,
doc = "Serde with-module for `i32` fields.\n\n\
Proto JSON accepts integers as numbers, quoted decimal strings, or\n\
float notation (e.g. `1.0`, `1e5`). Serializes as a JSON number.\n\n\
Use with `#[serde(with = \"::buffa::json_helpers::int32\")]`.",
serialize_body = |v, s| s.serialize_i32(*v),
expecting = "an i32 as integer, string, float, or null",
reason = Int32,
parse_str = parse_int_from_str,
);
int_serde_module!(
uint32,
u32,
doc = "Serde with-module for `u32` fields.\n\n\
Proto JSON accepts integers as numbers, quoted decimal strings, or\n\
float notation (e.g. `1.0`, `1e5`). Serializes as a JSON number.\n\n\
Use with `#[serde(with = \"::buffa::json_helpers::uint32\")]`.",
serialize_body = |v, s| s.serialize_u32(*v),
expecting = "a u32 as integer, string, float, or null",
reason = Uint32,
parse_str = parse_int_from_str,
);
int_serde_module!(
int64,
i64,
doc = "Serde with-module for `i64` fields encoded as a quoted decimal string.\n\n\
Proto JSON also accepts unquoted integers and float notation.\n\n\
Use with `#[serde(with = \"::buffa::json_helpers::int64\")]`.",
serialize_body = |v, s| {
#[cfg(feature = "zeroize")]
{
crate::sensitive::serialize_decimal(v, s)
}
#[cfg(not(feature = "zeroize"))]
{
s.collect_str(v)
}
},
expecting = "an i64 as a quoted decimal string, integer, float, or null",
reason = Int64,
parse_str = parse_int_from_str,
);
fn parse_u64(value: &str) -> Option<u64> {
value.parse().ok().or_else(|| parse_int_from_str(value))
}
int_serde_module!(
uint64,
u64,
doc = "Serde with-module for `u64` fields encoded as a quoted decimal string.\n\n\
Proto JSON also accepts unquoted integers and float notation.\n\n\
Use with `#[serde(with = \"::buffa::json_helpers::uint64\")]`.",
serialize_body = |v, s| {
#[cfg(feature = "zeroize")]
{
crate::sensitive::serialize_decimal(v, s)
}
#[cfg(not(feature = "zeroize"))]
{
s.collect_str(v)
}
},
expecting = "a u64 as a quoted decimal string, integer, float, or null",
reason = Uint64,
parse_str = parse_u64,
);
pub mod float {
use serde::{Deserializer, Serializer};
pub fn serialize<S: Serializer>(value: &f32, s: S) -> Result<S::Ok, S::Error> {
if value.is_nan() {
s.serialize_str("NaN")
} else if *value == f32::INFINITY {
s.serialize_str("Infinity")
} else if *value == f32::NEG_INFINITY {
s.serialize_str("-Infinity")
} else {
s.serialize_f32(*value)
}
}
pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<f32, D::Error> {
struct V;
impl<'de> serde::de::Visitor<'de> for V {
type Value = f32;
fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(r#"a float, "NaN", "Infinity", "-Infinity", or null"#)
}
fn visit_unit<E>(self) -> Result<f32, E> {
Ok(0.0)
}
fn visit_bool<E: serde::de::Error>(self, _: bool) -> Result<f32, E> {
Err(E::custom(super::JsonValueError::Float))
}
fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<f32, E> {
match v {
"NaN" => Ok(f32::NAN),
"Infinity" => Ok(f32::INFINITY),
"-Infinity" => Ok(f32::NEG_INFINITY),
_ => match v.parse::<f32>() {
Ok(f) if f.is_finite() => Ok(f),
_ => Err(E::custom(super::JsonValueError::Float)),
},
}
}
fn visit_string<E: serde::de::Error>(
self,
value: alloc::string::String,
) -> Result<f32, E> {
#[cfg(feature = "zeroize")]
let value = zeroize::Zeroizing::new(value);
self.visit_str(&value)
}
fn visit_f32<E: serde::de::Error>(self, v: f32) -> Result<f32, E> {
Ok(v)
}
fn visit_f64<E: serde::de::Error>(self, v: f64) -> Result<f32, E> {
let f = v as f32;
if v.is_finite() && !f.is_finite() {
return Err(E::custom(super::JsonValueError::Float));
}
Ok(f)
}
fn visit_i64<E: serde::de::Error>(self, v: i64) -> Result<f32, E> {
Ok(v as f32)
}
visit_wide_ints!(super::JsonValueError::Float);
crate::reject_other_json_kinds!(bytes, byte_buf);
fn visit_u64<E: serde::de::Error>(self, v: u64) -> Result<f32, E> {
Ok(v as f32)
}
}
d.deserialize_any(V)
}
}
pub mod double {
use serde::{Deserializer, Serializer};
pub fn serialize<S: Serializer>(value: &f64, s: S) -> Result<S::Ok, S::Error> {
if value.is_nan() {
s.serialize_str("NaN")
} else if *value == f64::INFINITY {
s.serialize_str("Infinity")
} else if *value == f64::NEG_INFINITY {
s.serialize_str("-Infinity")
} else {
s.serialize_f64(*value)
}
}
pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<f64, D::Error> {
struct V;
impl<'de> serde::de::Visitor<'de> for V {
type Value = f64;
fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(r#"a double, "NaN", "Infinity", "-Infinity", or null"#)
}
fn visit_unit<E>(self) -> Result<f64, E> {
Ok(0.0)
}
fn visit_bool<E: serde::de::Error>(self, _: bool) -> Result<f64, E> {
Err(E::custom(super::JsonValueError::Double))
}
fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<f64, E> {
match v {
"NaN" => Ok(f64::NAN),
"Infinity" => Ok(f64::INFINITY),
"-Infinity" => Ok(f64::NEG_INFINITY),
_ => match v.parse::<f64>() {
Ok(f) if f.is_finite() => Ok(f),
_ => Err(E::custom(super::JsonValueError::Double)),
},
}
}
fn visit_string<E: serde::de::Error>(
self,
value: alloc::string::String,
) -> Result<f64, E> {
#[cfg(feature = "zeroize")]
let value = zeroize::Zeroizing::new(value);
self.visit_str(&value)
}
fn visit_f64<E: serde::de::Error>(self, v: f64) -> Result<f64, E> {
Ok(v)
}
fn visit_f32<E: serde::de::Error>(self, v: f32) -> Result<f64, E> {
Ok(v as f64)
}
fn visit_i64<E: serde::de::Error>(self, v: i64) -> Result<f64, E> {
Ok(v as f64)
}
visit_wide_ints!(super::JsonValueError::Double);
crate::reject_other_json_kinds!(bytes, byte_buf);
fn visit_u64<E: serde::de::Error>(self, v: u64) -> Result<f64, E> {
Ok(v as f64)
}
}
d.deserialize_any(V)
}
}
pub mod bytes {
use super::STANDARD;
use base64::Engine as _;
use serde::{Deserializer, Serializer};
pub fn serialize<S: Serializer>(value: &[u8], s: S) -> Result<S::Ok, S::Error> {
s.collect_str(&base64::display::Base64Display::new(value, &STANDARD))
}
#[must_use]
pub fn max_decoded_len(text: &str) -> usize {
base64::decoded_len_estimate(text.len())
}
pub fn decode_into<E: serde::de::Error>(text: &str, out: &mut [u8]) -> Result<usize, E> {
super::lenient_engine(text)
.decode_slice(text, out)
.map_err(|error| {
E::custom(match error {
base64::DecodeSliceError::OutputSliceTooSmall => {
Base64ErrorReason::BufferTooSmall
}
base64::DecodeSliceError::DecodeError(_) => Base64ErrorReason::Invalid,
})
})
}
#[derive(Debug, thiserror::Error)]
enum Base64ErrorReason {
#[error("invalid base64")]
Invalid,
#[error("base64 output buffer too small")]
BufferTooSmall,
}
pub fn deserialize<'de, T, D>(d: D) -> Result<T, D::Error>
where
T: From<alloc::vec::Vec<u8>>,
D: Deserializer<'de>,
{
struct V;
impl<'de> serde::de::Visitor<'de> for V {
type Value = alloc::vec::Vec<u8>;
fn visit_unit<E>(self) -> Result<alloc::vec::Vec<u8>, E> {
Ok(alloc::vec::Vec::new())
}
fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("a base64-encoded string, or null")
}
fn visit_bool<E: serde::de::Error>(self, _: bool) -> Result<alloc::vec::Vec<u8>, E> {
Err(E::custom(super::JsonValueError::Base64))
}
fn visit_i64<E: serde::de::Error>(self, _: i64) -> Result<alloc::vec::Vec<u8>, E> {
Err(E::custom(super::JsonValueError::Base64))
}
fn visit_u64<E: serde::de::Error>(self, _: u64) -> Result<alloc::vec::Vec<u8>, E> {
Err(E::custom(super::JsonValueError::Base64))
}
fn visit_f64<E: serde::de::Error>(self, _: f64) -> Result<alloc::vec::Vec<u8>, E> {
Err(E::custom(super::JsonValueError::Base64))
}
visit_wide_ints!(super::JsonValueError::Base64);
crate::reject_other_json_kinds!(bytes, byte_buf);
fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<alloc::vec::Vec<u8>, E> {
super::decode_base64(v).map_err(serde::de::Error::custom)
}
}
d.deserialize_any(V).map(T::from)
}
}
proto_elem_json_delegate!(i32, int32);
proto_elem_json_delegate!(u32, uint32);
proto_elem_json_delegate!(i64, int64);
proto_elem_json_delegate!(u64, uint64);
proto_elem_json_delegate!(f32, float);
proto_elem_json_delegate!(f64, double);
proto_elem_json_delegate!(bool, proto_bool, null = "a boolean");
proto_elem_json_delegate!(alloc::string::String, proto_string, null = "a string");
proto_elem_json_delegate!(alloc::vec::Vec<u8>, bytes);
impl ProtoElemJson for ::bytes::Bytes {
fn serialize_proto_json<S: serde::Serializer>(v: &Self, s: S) -> Result<S::Ok, S::Error> {
bytes::serialize(v, s)
}
fn deserialize_proto_json<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
bytes::deserialize(d)
}
}
impl<E: crate::Enumeration> ProtoElemJson for crate::EnumValue<E>
where
Self: serde::Serialize + serde::de::DeserializeOwned,
{
fn serialize_proto_json<S: serde::Serializer>(v: &Self, s: S) -> Result<S::Ok, S::Error> {
serde::Serialize::serialize(v, s)
}
fn deserialize_proto_json<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
<Self as serde::Deserialize>::deserialize(d)
}
}
pub mod bytes_key_map {
use super::{ProtoElemJson, ProtoElemSeed, ProtoJson};
use crate::map_codec::MapStorage;
use serde::{Deserializer, Serializer};
pub fn serialize<C, S>(value: &C, s: S) -> Result<S::Ok, S::Error>
where
C: MapStorage<Key = alloc::vec::Vec<u8>>,
C::Value: ProtoElemJson,
S: Serializer,
{
use serde::ser::SerializeMap;
let mut map = s.serialize_map(Some(value.storage_len()))?;
for (k, v) in value.storage_iter() {
map.serialize_entry(&super::Base64Wrapper(k), &ProtoJson(v))?;
}
map.end()
}
pub fn deserialize<'de, C, D>(d: D) -> Result<C, D::Error>
where
C: MapStorage<Key = alloc::vec::Vec<u8>> + Default,
C::Value: ProtoElemJson,
D: Deserializer<'de>,
{
struct Vis<C>(core::marker::PhantomData<C>);
impl<'de, C> serde::de::Visitor<'de> for Vis<C>
where
C: MapStorage<Key = alloc::vec::Vec<u8>> + Default,
C::Value: ProtoElemJson,
{
type Value = C;
fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("a map with base64-encoded keys, or null")
}
fn visit_unit<E>(self) -> Result<Self::Value, E> {
Ok(C::default())
}
crate::reject_other_json_kinds!(
bool, i64, u64, i128, u128, f64, str, string, bytes, byte_buf
);
fn visit_map<A: serde::de::MapAccess<'de>>(
self,
mut map: A,
) -> Result<Self::Value, A::Error> {
let mut out = C::default();
while let Some(key_str) = map.next_key::<alloc::string::String>()? {
#[cfg(feature = "zeroize")]
let key_str = zeroize::Zeroizing::new(key_str);
let k = super::decode_base64(&key_str).map_err(serde::de::Error::custom)?;
let k = crate::erasing::Erasing::new(k, C::storage_erase_key);
let v =
map.next_value_seed(ProtoElemSeed::<C::Value>(core::marker::PhantomData))?;
out.storage_insert(k.into_inner(), v);
}
Ok(out)
}
}
d.deserialize_any(Vis::<C>(core::marker::PhantomData))
}
}
pub mod bytes_key_bytes_val_map {
use crate::map_codec::MapStorage;
use serde::{Deserializer, Serializer};
pub fn serialize<C, S>(value: &C, s: S) -> Result<S::Ok, S::Error>
where
C: MapStorage<Key = alloc::vec::Vec<u8>, Value = alloc::vec::Vec<u8>>,
S: Serializer,
{
use serde::ser::SerializeMap;
let mut map = s.serialize_map(Some(value.storage_len()))?;
for (k, v) in value.storage_iter() {
map.serialize_entry(&super::Base64Wrapper(k), &super::Base64Wrapper(v))?;
}
map.end()
}
pub fn deserialize<'de, C, D>(d: D) -> Result<C, D::Error>
where
C: MapStorage<Key = alloc::vec::Vec<u8>, Value = alloc::vec::Vec<u8>> + Default,
D: Deserializer<'de>,
{
struct V<C>(core::marker::PhantomData<C>);
impl<'de, C> serde::de::Visitor<'de> for V<C>
where
C: MapStorage<Key = alloc::vec::Vec<u8>, Value = alloc::vec::Vec<u8>> + Default,
{
type Value = C;
fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("a map with base64-encoded keys and values, or null")
}
fn visit_unit<E>(self) -> Result<Self::Value, E> {
Ok(C::default())
}
crate::reject_other_json_kinds!(
bool, i64, u64, i128, u128, f64, str, string, bytes, byte_buf
);
fn visit_map<A: serde::de::MapAccess<'de>>(
self,
mut map: A,
) -> Result<Self::Value, A::Error> {
let mut out = C::default();
while let Some(ks) = map.next_key::<alloc::string::String>()? {
#[cfg(feature = "zeroize")]
let ks = zeroize::Zeroizing::new(ks);
let k = super::decode_base64(&ks).map_err(serde::de::Error::custom)?;
let k = crate::erasing::Erasing::new(k, C::storage_erase_key);
let vs = map.next_value::<alloc::string::String>()?;
#[cfg(feature = "zeroize")]
let vs = zeroize::Zeroizing::new(vs);
let v = super::decode_base64(&vs).map_err(serde::de::Error::custom)?;
out.storage_insert(k.into_inner(), v);
}
Ok(out)
}
}
d.deserialize_any(V::<C>(core::marker::PhantomData))
}
}
pub mod string_key_map {
use crate::map_codec::MapStorage;
use core::fmt::Display;
use core::str::FromStr;
use serde::{Deserializer, Serializer};
pub fn serialize<C, S>(value: &C, s: S) -> Result<S::Ok, S::Error>
where
C: MapStorage,
C::Key: Display,
C::Value: serde::Serialize,
S: Serializer,
{
use serde::ser::SerializeMap;
let mut map = s.serialize_map(Some(value.storage_len()))?;
for (k, v) in value.storage_iter() {
map.serialize_entry(&super::DisplayKey(k), v)?;
}
map.end()
}
pub fn deserialize<'de, C, D>(d: D) -> Result<C, D::Error>
where
C: MapStorage + Default,
C::Key: FromStr,
C::Value: serde::Deserialize<'de>,
D: Deserializer<'de>,
{
struct MapVisitor<C>(core::marker::PhantomData<C>);
impl<'de, C> serde::de::Visitor<'de> for MapVisitor<C>
where
C: MapStorage + Default,
C::Key: FromStr,
C::Value: serde::Deserialize<'de>,
{
type Value = C;
fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("a JSON object with string keys, or null")
}
fn visit_unit<E>(self) -> Result<Self::Value, E> {
Ok(C::default())
}
crate::reject_other_json_kinds!(
bool, i64, u64, i128, u128, f64, str, string, bytes, byte_buf
);
fn visit_map<A: serde::de::MapAccess<'de>>(
self,
mut map: A,
) -> Result<Self::Value, A::Error> {
let mut out = C::default();
while let Some(key_str) = map.next_key::<alloc::string::String>()? {
let key = key_str
.parse::<C::Key>()
.map_err(|_| serde::de::Error::custom(super::JsonValueError::MapKey))?;
let key = crate::erasing::Erasing::new(key, C::storage_erase_key);
let value = map.next_value()?;
out.storage_insert(key.into_inner(), value);
}
Ok(out)
}
}
d.deserialize_any(MapVisitor::<C>(core::marker::PhantomData))
}
}
struct Base64Wrapper<'a>(&'a [u8]);
impl serde::Serialize for Base64Wrapper<'_> {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
bytes::serialize(self.0, s)
}
}
fn lenient_engine(v: &str) -> &'static GeneralPurpose {
match v.bytes().find(|b| matches!(b, b'+' | b'/' | b'-' | b'_')) {
Some(b'-' | b'_') => &URL_SAFE_LENIENT,
_ => &STANDARD_LENIENT,
}
}
pub(crate) fn decode_base64(v: &str) -> Result<alloc::vec::Vec<u8>, JsonValueError> {
use base64::Engine as _;
lenient_engine(v)
.decode(v)
.map_err(|_| JsonValueError::Base64)
}
macro_rules! opt_serde_module {
($(#[$attr:meta])* $mod_name:ident, $inner:ident, $ty:ty) => {
$(#[$attr])*
pub mod $mod_name {
use serde::{Deserializer, Serializer};
pub fn serialize<S: Serializer>(value: &Option<$ty>, s: S) -> Result<S::Ok, S::Error> {
match value {
Some(v) => super::$inner::serialize(v, s),
None => s.serialize_none(),
}
}
pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<$ty>, D::Error> {
serde::de::DeserializeSeed::deserialize(super::NullableDeserializeSeed(Inner), d)
}
struct Inner;
impl<'de> serde::de::DeserializeSeed<'de> for Inner {
type Value = $ty;
fn deserialize<D: Deserializer<'de>>(self, d: D) -> Result<$ty, D::Error> {
super::$inner::deserialize(d)
}
}
}
};
}
opt_serde_module!(opt_int32, int32, i32);
opt_serde_module!(opt_uint32, uint32, u32);
opt_serde_module!(opt_int64, int64, i64);
opt_serde_module!(opt_uint64, uint64, u64);
opt_serde_module!(opt_float, float, f32);
opt_serde_module!(opt_double, double, f64);
pub mod opt_bool {
pub fn serialize<S: serde::Serializer>(value: &Option<bool>, s: S) -> Result<S::Ok, S::Error> {
if s.is_human_readable() {
match value {
Some(value) => super::proto_bool::serialize(value, s),
None => s.serialize_none(),
}
} else {
serde::Serialize::serialize(value, s)
}
}
pub fn deserialize<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<bool>, D::Error> {
if !d.is_human_readable() {
return serde::Deserialize::deserialize(d);
}
struct Inner;
impl<'de> serde::de::DeserializeSeed<'de> for Inner {
type Value = bool;
fn deserialize<D: serde::Deserializer<'de>>(self, d: D) -> Result<bool, D::Error> {
super::proto_bool::deserialize(d)
}
}
serde::de::DeserializeSeed::deserialize(super::NullableDeserializeSeed(Inner), d)
}
}
pub mod opt_string {
use serde::{Deserializer, Serializer};
pub fn serialize<T, S>(value: &Option<T>, s: S) -> Result<S::Ok, S::Error>
where
T: AsRef<str>,
S: Serializer,
{
match value {
Some(v) if s.is_human_readable() => super::proto_string::serialize(v.as_ref(), s),
Some(v) => s.serialize_some(v.as_ref()),
None => s.serialize_none(),
}
}
pub fn deserialize<'de, T, D>(d: D) -> Result<Option<T>, D::Error>
where
T: crate::ProtoString,
D: Deserializer<'de>,
{
if !d.is_human_readable() {
return <Option<alloc::string::String> as serde::Deserialize>::deserialize(d)
.map(|value| value.map(T::from));
}
struct Inner<T>(core::marker::PhantomData<T>);
impl<'de, T: crate::ProtoString> serde::de::DeserializeSeed<'de> for Inner<T> {
type Value = T;
fn deserialize<D2: Deserializer<'de>>(self, d: D2) -> Result<T, D2::Error> {
super::proto_string::deserialize(d)
}
}
serde::de::DeserializeSeed::deserialize(
super::NullableDeserializeSeed(Inner(core::marker::PhantomData)),
d,
)
}
}
pub mod opt_bytes {
use serde::{Deserializer, Serializer};
pub fn serialize<T, S>(value: &Option<T>, s: S) -> Result<S::Ok, S::Error>
where
T: AsRef<[u8]>,
S: Serializer,
{
match value {
Some(v) => super::bytes::serialize(v.as_ref(), s),
None => s.serialize_none(),
}
}
pub fn deserialize<'de, T, D>(d: D) -> Result<Option<T>, D::Error>
where
T: From<alloc::vec::Vec<u8>>,
D: Deserializer<'de>,
{
struct Inner;
impl<'de> serde::de::DeserializeSeed<'de> for Inner {
type Value = alloc::vec::Vec<u8>;
fn deserialize<D2: Deserializer<'de>>(
self,
d: D2,
) -> Result<alloc::vec::Vec<u8>, D2::Error> {
super::bytes::deserialize(d)
}
}
serde::de::DeserializeSeed::deserialize(super::NullableDeserializeSeed(Inner), d)
.map(|opt| opt.map(T::from))
}
}
pub mod opt_enum {
use serde::{Deserializer, Serializer};
pub fn serialize<E: crate::Enumeration, S: Serializer>(
value: &Option<crate::EnumValue<E>>,
s: S,
) -> Result<S::Ok, S::Error> {
match value {
Some(v) => serde::Serialize::serialize(v, s),
None => s.serialize_none(),
}
}
pub fn deserialize<'de, E: crate::Enumeration, D: Deserializer<'de>>(
d: D,
) -> Result<Option<crate::EnumValue<E>>, D::Error> {
let raw: Option<super::BufferedValue> = serde::Deserialize::deserialize(d)?;
let raw = match raw {
Some(super::BufferedValue(v)) => v,
None => return Ok(None),
};
super::try_deserialize_enum::<crate::EnumValue<E>>(raw).map_err(serde::de::Error::custom)
}
}
pub struct NullableDeserializeSeed<S>(pub S);
impl<'de, S> serde::de::DeserializeSeed<'de> for NullableDeserializeSeed<S>
where
S: serde::de::DeserializeSeed<'de>,
{
type Value = Option<S::Value>;
fn deserialize<D: serde::Deserializer<'de>>(self, d: D) -> Result<Self::Value, D::Error> {
d.deserialize_option(NullableVisitor(self.0))
}
}
struct NullableVisitor<S>(S);
impl<'de, S> serde::de::Visitor<'de> for NullableVisitor<S>
where
S: serde::de::DeserializeSeed<'de>,
{
type Value = Option<S::Value>;
fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("a value or null")
}
fn visit_none<E>(self) -> Result<Self::Value, E> {
Ok(None)
}
crate::reject_other_json_kinds!(bool, i64, u64, i128, u128, f64, str, string, bytes, byte_buf);
fn visit_unit<E>(self) -> Result<Self::Value, E> {
Ok(None)
}
fn visit_some<D: serde::Deserializer<'de>>(self, d: D) -> Result<Self::Value, D::Error> {
self.0.deserialize(d).map(Some)
}
}
pub struct DefaultDeserializeSeed<T>(core::marker::PhantomData<T>);
impl<T> DefaultDeserializeSeed<T> {
pub fn new() -> Self {
Self(core::marker::PhantomData)
}
}
impl<T> Default for DefaultDeserializeSeed<T> {
fn default() -> Self {
Self::new()
}
}
impl<'de, T: serde::Deserialize<'de>> serde::de::DeserializeSeed<'de>
for DefaultDeserializeSeed<T>
{
type Value = T;
fn deserialize<D: serde::Deserializer<'de>>(self, d: D) -> Result<T, D::Error> {
T::deserialize(d)
}
}
pub fn message_field_always_present<'de, T, P, D>(
d: D,
) -> Result<crate::MessageField<T, P>, D::Error>
where
T: Default + serde::Deserialize<'de>,
P: crate::ProtoBox<T>,
D: serde::Deserializer<'de>,
{
T::deserialize(d).map(crate::MessageField::some)
}
pub(crate) struct EnumProtoNameRef<'a, E: crate::Enumeration>(pub &'a E);
impl<E: crate::Enumeration> serde::Serialize for EnumProtoNameRef<'_, E> {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(self.0.proto_name())
}
}
pub mod skip_if {
pub fn is_zero_i32(v: &i32) -> bool {
*v == 0
}
pub fn is_zero_i64(v: &i64) -> bool {
*v == 0
}
pub fn is_zero_u32(v: &u32) -> bool {
*v == 0
}
pub fn is_zero_u64(v: &u64) -> bool {
*v == 0
}
pub fn is_false(v: &bool) -> bool {
!*v
}
pub fn is_zero_f32(v: &f32) -> bool {
v.to_bits() == 0
}
pub fn is_zero_f64(v: &f64) -> bool {
v.to_bits() == 0
}
pub fn is_empty_str(v: &str) -> bool {
v.is_empty()
}
pub fn is_empty_bytes(v: &[u8]) -> bool {
v.is_empty()
}
pub fn is_empty_vec<T>(v: &[T]) -> bool {
v.is_empty()
}
pub fn is_empty_map<C>(m: &C) -> bool
where
C: crate::map_codec::MapStorage,
{
m.storage_len() == 0
}
pub fn is_unset_message_field<T: Default, P: crate::ProtoBox<T>>(
v: &crate::MessageField<T, P>,
) -> bool {
v.is_unset()
}
pub fn is_default_enum_value<E: crate::Enumeration>(v: &crate::EnumValue<E>) -> bool {
v.to_i32() == 0
}
pub fn is_default_closed_enum<E: crate::Enumeration>(v: &E) -> bool {
v.to_i32() == 0
}
}
pub mod closed_enum {
use super::EnumJsonErrorReason;
use serde::{Deserializer, Serializer};
pub fn serialize<E: crate::Enumeration, S: Serializer>(
value: &E,
s: S,
) -> Result<S::Ok, S::Error> {
s.serialize_str(value.proto_name())
}
pub fn deserialize<'de, E: crate::Enumeration + Default, D: Deserializer<'de>>(
d: D,
) -> Result<E, D::Error> {
deserialize_with_unknown_names(d, true)
}
#[doc(hidden)]
pub fn deserialize_strict<'de, E: crate::Enumeration + Default, D: Deserializer<'de>>(
d: D,
) -> Result<E, D::Error> {
deserialize_with_unknown_names(d, false)
}
fn deserialize_with_unknown_names<
'de,
E: crate::Enumeration + Default,
D: Deserializer<'de>,
>(
d: D,
allow_lenient: bool,
) -> Result<E, D::Error> {
struct V<E> {
allow_lenient: bool,
marker: core::marker::PhantomData<E>,
}
impl<'de, E: crate::Enumeration + Default> serde::de::Visitor<'de> for V<E> {
type Value = E;
fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("a protobuf enum name string, integer value, or null")
}
fn visit_unit<Err>(self) -> Result<E, Err> {
Ok(E::default())
}
fn visit_i64<Err: serde::de::Error>(self, v: i64) -> Result<E, Err> {
let v32 =
i32::try_from(v).map_err(|_| Err::custom(EnumJsonErrorReason::OutOfRange))?;
E::from_i32(v32).ok_or_else(|| Err::custom(EnumJsonErrorReason::UnknownNumber))
}
fn visit_u64<Err: serde::de::Error>(self, v: u64) -> Result<E, Err> {
let v32 =
i32::try_from(v).map_err(|_| Err::custom(EnumJsonErrorReason::OutOfRange))?;
E::from_i32(v32).ok_or_else(|| Err::custom(EnumJsonErrorReason::UnknownNumber))
}
fn visit_i128<Err: serde::de::Error>(self, v: i128) -> Result<E, Err> {
let v =
i64::try_from(v).map_err(|_| Err::custom(EnumJsonErrorReason::OutOfRange))?;
self.visit_i64(v)
}
fn visit_u128<Err: serde::de::Error>(self, v: u128) -> Result<E, Err> {
let v =
u64::try_from(v).map_err(|_| Err::custom(EnumJsonErrorReason::OutOfRange))?;
self.visit_u64(v)
}
fn visit_f64<Err: serde::de::Error>(self, _: f64) -> Result<E, Err> {
Err(Err::custom(EnumJsonErrorReason::InvalidType))
}
fn visit_bool<Err: serde::de::Error>(self, _: bool) -> Result<E, Err> {
Err(Err::custom(EnumJsonErrorReason::InvalidType))
}
#[cfg(feature = "zeroize")]
fn visit_string<Err: serde::de::Error>(
self,
value: alloc::string::String,
) -> Result<E, Err> {
let value = zeroize::Zeroizing::new(value);
self.visit_str(&value)
}
#[cfg(feature = "zeroize")]
fn visit_byte_buf<Err: serde::de::Error>(
self,
value: alloc::vec::Vec<u8>,
) -> Result<Self::Value, Err> {
let value = zeroize::Zeroizing::new(value);
self.visit_bytes(&value)
}
fn visit_str<Err: serde::de::Error>(self, v: &str) -> Result<E, Err> {
match E::from_proto_name(v) {
Some(e) => Ok(e),
None => {
if self.allow_lenient && crate::json::ignore_unknown_enum_values() {
return Ok(E::default());
}
Err(Err::custom(EnumJsonErrorReason::UnknownName))
}
}
}
}
d.deserialize_any(V {
allow_lenient,
marker: core::marker::PhantomData,
})
}
}
pub mod opt_closed_enum {
use serde::{Deserializer, Serializer};
pub fn serialize<E: crate::Enumeration, S: Serializer>(
value: &Option<E>,
s: S,
) -> Result<S::Ok, S::Error> {
match value {
Some(v) => s.serialize_str(v.proto_name()),
None => s.serialize_none(),
}
}
pub fn deserialize<'de, E: crate::Enumeration + Default, D: Deserializer<'de>>(
d: D,
) -> Result<Option<E>, D::Error> {
let raw: Option<super::BufferedValue> = serde::Deserialize::deserialize(d)?;
let raw = match raw {
Some(super::BufferedValue(v)) => v,
None => return Ok(None),
};
super::try_deserialize_closed_enum::<E>(&raw).map_err(serde::de::Error::custom)
}
}
pub mod repeated_closed_enum {
use alloc::vec::Vec;
use serde::{Deserializer, Serializer};
pub fn serialize<E: crate::Enumeration, S: Serializer>(
value: &[E],
s: S,
) -> Result<S::Ok, S::Error> {
use serde::ser::SerializeSeq;
let null_sentinel = E::IS_NULL_VALUE && s.is_human_readable();
let mut seq = s.serialize_seq(Some(value.len()))?;
for v in value {
if null_sentinel && v.to_i32() == 0 {
seq.serialize_element(&())?;
} else {
seq.serialize_element(&crate::json_helpers::EnumProtoNameRef(v))?;
}
}
seq.end()
}
pub fn deserialize<'de, E, C, D>(d: D) -> Result<C, D::Error>
where
E: crate::Enumeration + Default,
C: From<Vec<E>>,
D: Deserializer<'de>,
{
struct V<E>(core::marker::PhantomData<E>);
impl<'de, E: crate::Enumeration + Default> serde::de::Visitor<'de> for V<E> {
type Value = Vec<E>;
fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("a list of enum values or null")
}
fn visit_unit<Err>(self) -> Result<Vec<E>, Err> {
Ok(Vec::new())
}
reject_container_scalar_values!(InvalidListType);
crate::__buffa_reject_other_json_kinds!(bytes, byte_buf);
fn visit_seq<A: serde::de::SeqAccess<'de>>(
self,
mut seq: A,
) -> Result<Vec<E>, A::Error> {
let mut out = Vec::with_capacity(super::clamp_size_hint(seq.size_hint()));
while let Some(super::BufferedValue(raw)) = seq.next_element()? {
if raw.is_null() && E::IS_NULL_VALUE {
let value = E::from_i32(0).ok_or_else(|| {
<A::Error as serde::de::Error>::custom(
super::enum_list::ErrorReason::Unknown,
)
})?;
out.push(value);
continue;
}
match super::try_deserialize_closed_enum::<E>(&raw) {
Ok(Some(v)) => out.push(v),
Ok(None) => continue,
Err(e) => return Err(serde::de::Error::custom(e)),
}
}
Ok(out)
}
}
d.deserialize_any(V::<E>(core::marker::PhantomData))
.map(C::from)
}
}
pub mod map_closed_enum {
use crate::map_codec::MapStorage;
use serde::{Deserializer, Serializer};
pub fn serialize<C, S>(value: &C, s: S) -> Result<S::Ok, S::Error>
where
C: MapStorage,
C::Key: serde::Serialize,
C::Value: crate::Enumeration,
S: Serializer,
{
use serde::ser::SerializeMap;
let mut map = s.serialize_map(Some(value.storage_len()))?;
for (k, v) in value.storage_iter() {
map.serialize_entry(k, &crate::json_helpers::EnumProtoNameRef(v))?;
}
map.end()
}
pub fn deserialize<'de, C, D>(d: D) -> Result<C, D::Error>
where
C: MapStorage + Default,
C::Key: serde::Deserialize<'de>,
C::Value: crate::Enumeration + Default,
D: Deserializer<'de>,
{
struct V<C>(core::marker::PhantomData<C>);
impl<'de, C> serde::de::Visitor<'de> for V<C>
where
C: MapStorage + Default,
C::Key: serde::Deserialize<'de>,
C::Value: crate::Enumeration + Default,
{
type Value = C;
fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("a map with enum values or null")
}
fn visit_unit<Err>(self) -> Result<Self::Value, Err> {
Ok(C::default())
}
reject_container_scalar_values!(InvalidMapType);
crate::__buffa_reject_other_json_kinds!(bytes, byte_buf);
fn visit_map<A: serde::de::MapAccess<'de>>(
self,
mut map: A,
) -> Result<Self::Value, A::Error> {
let mut out = C::default();
while let Some(key) = map.next_key_seed(super::map_key::KeySeed::<C::Key>::new())? {
let key = crate::erasing::Erasing::new(key, C::storage_erase_key);
let super::BufferedValue(raw) = map.next_value()?;
match super::try_deserialize_closed_enum::<C::Value>(&raw) {
Ok(Some(v)) => {
out.storage_insert(key.into_inner(), v);
}
Ok(None) => continue,
Err(e) => return Err(serde::de::Error::custom(e)),
}
}
Ok(out)
}
}
d.deserialize_any(V::<C>(core::marker::PhantomData))
}
}
#[cfg(test)]
mod tests;
pub mod enum_list;
#[doc(hidden)]
#[cfg(feature = "zeroize")]
pub mod guarded_enum;
mod guarded_key;
#[doc(hidden)]
#[cfg(feature = "zeroize")]
pub mod guarded_map;