Optional support for borsh serialization

This commit is contained in:
Mateusz Kowalczyk
2023-12-07 13:14:40 +09:00
committed by bluss
parent 7a1722ed0f
commit 4337b1bdd7
3 changed files with 67 additions and 1 deletions
+6 -1
View File
@@ -14,6 +14,11 @@ categories = ["data-structures", "no-std"]
[build-dependencies]
[dependencies.borsh]
version = "1.2.0"
optional = true
default-features = false
[dependencies.serde]
version = "1.0"
optional = true
@@ -49,7 +54,7 @@ debug = true
debug = true
[package.metadata.docs.rs]
features = ["serde", "zeroize"]
features = ["borsh", "serde", "zeroize"]
[package.metadata.release]
no-dev-version = true
+22
View File
@@ -628,6 +628,28 @@ impl<'de, const CAP: usize> Deserialize<'de> for ArrayString<CAP>
}
}
#[cfg(feature = "borsh")]
/// Requires crate feature `"borsh"`
impl<const CAP: usize> borsh::BorshSerialize for ArrayString<CAP> {
fn serialize<W: borsh::io::Write>(&self, writer: &mut W) -> borsh::io::Result<()> {
<str as borsh::BorshSerialize>::serialize(&*self, writer)
}
}
#[cfg(feature = "borsh")]
/// Requires crate feature `"borsh"`
impl<const CAP: usize> borsh::BorshDeserialize for ArrayString<CAP> {
fn deserialize_reader<R: borsh::io::Read>(reader: &mut R) -> borsh::io::Result<Self> {
let s = <String as borsh::BorshDeserialize>::deserialize_reader(reader)?;
ArrayString::from(&s).map_err(|_| {
borsh::io::Error::new(
borsh::io::ErrorKind::InvalidData,
format!("expected a string no more than {} bytes long", CAP),
)
})
}
}
impl<'a, const CAP: usize> TryFrom<&'a str> for ArrayString<CAP>
{
type Error = CapacityError<&'a str>;
+39
View File
@@ -1301,3 +1301,42 @@ impl<'de, T: Deserialize<'de>, const CAP: usize> Deserialize<'de> for ArrayVec<T
deserializer.deserialize_seq(ArrayVecVisitor::<T, CAP>(PhantomData))
}
}
#[cfg(feature = "borsh")]
/// Requires crate feature `"borsh"`
impl<T, const CAP: usize> borsh::BorshSerialize for ArrayVec<T, CAP>
where
T: borsh::BorshSerialize,
{
fn serialize<W: borsh::io::Write>(&self, writer: &mut W) -> borsh::io::Result<()> {
let vs = self.as_slice();
<usize as borsh::BorshSerialize>::serialize(&vs.len(), writer)?;
for elem in vs {
<T as borsh::BorshSerialize>::serialize(elem, writer)?;
}
Ok(())
}
}
#[cfg(feature = "borsh")]
/// Requires crate feature `"borsh"`
impl<T, const CAP: usize> borsh::BorshDeserialize for ArrayVec<T, CAP>
where
T: borsh::BorshDeserialize,
{
fn deserialize_reader<R: borsh::io::Read>(reader: &mut R) -> borsh::io::Result<Self> {
let mut values = Self::new();
let len = <usize as borsh::BorshDeserialize>::deserialize_reader(reader)?;
for _ in 0..len {
let elem = <T as borsh::BorshDeserialize>::deserialize_reader(reader)?;
if let Err(_) = values.try_push(elem) {
return Err(borsh::io::Error::new(
borsh::io::ErrorKind::InvalidData,
format!("expected an array with no more than {} items", CAP),
));
}
}
Ok(values)
}
}