Files
opaque-vx/src/impls.rs
T

73 lines
2.7 KiB
Rust
Raw Normal View History

// Copyright (c) Facebook, Inc. and its affiliates.
//
2021-12-03 14:38:11 -08:00
// This source code is licensed under both the MIT license found in the
// LICENSE-MIT file in the root directory of this source tree and the Apache
// License, Version 2.0 found in the LICENSE-APACHE file in the root directory
// of this source tree.
2022-01-04 00:50:40 +01:00
/// Macro used for deriving `serde`'s `Serialize` and `Deserialize` traits.
macro_rules! impl_serialize_and_deserialize_for {
2022-01-04 00:50:40 +01:00
($item:ident$( where $($path:ty: $bound1:path $(| $bound2:path)*),+$(,)?)?$(; $error:expr)?) => {
#[cfg(feature = "serde")]
impl<CS: CipherSuite> serde_::Serialize for $item<CS>
$(where
$($path: $bound1 $(+ $bound2)*),+
)?
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
2022-01-04 00:50:40 +01:00
S: serde_::Serializer,
{
2022-01-04 00:50:40 +01:00
serializer.serialize_bytes(&self.serialize()$(.map_err($error)?)?)
}
}
2022-01-04 00:50:40 +01:00
#[cfg(feature = "serde")]
impl<'de, CS: CipherSuite> serde_::Deserialize<'de> for $item<CS>
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
2022-01-04 00:50:40 +01:00
D: serde_::Deserializer<'de>,
{
2022-01-04 00:50:40 +01:00
use serde_::de::Error;
struct ByteVisitor<CS: CipherSuite>(core::marker::PhantomData<CS>);
impl<'de, CS: CipherSuite> serde_::de::Visitor<'de> for ByteVisitor<CS>
{
type Value = $item<CS>;
2021-10-25 02:54:32 -07:00
2022-01-04 00:50:40 +01:00
fn expecting(
&self,
formatter: &mut core::fmt::Formatter,
) -> core::fmt::Result {
formatter.write_str(core::concat!(
"the byte representation of a ",
core::stringify!($t)
))
}
fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E>
where
E: Error,
{
$item::<CS>::deserialize(value).map_err(|_| {
Error::invalid_value(
serde_::de::Unexpected::Bytes(value),
&core::concat!(
"invalid byte sequence for ",
core::stringify!($t)
),
)
})
}
}
2022-01-04 00:50:40 +01:00
deserializer
.deserialize_bytes(ByteVisitor::<CS>(core::marker::PhantomData))
.map_err(Error::custom)
}
}
};
}