diff --git a/Cargo.toml b/Cargo.toml index 5f4fd2c..256bff8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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 diff --git a/src/array_string.rs b/src/array_string.rs index de4ac4c..7145427 100644 --- a/src/array_string.rs +++ b/src/array_string.rs @@ -628,6 +628,28 @@ impl<'de, const CAP: usize> Deserialize<'de> for ArrayString } } +#[cfg(feature = "borsh")] +/// Requires crate feature `"borsh"` +impl borsh::BorshSerialize for ArrayString { + fn serialize(&self, writer: &mut W) -> borsh::io::Result<()> { + ::serialize(&*self, writer) + } +} + +#[cfg(feature = "borsh")] +/// Requires crate feature `"borsh"` +impl borsh::BorshDeserialize for ArrayString { + fn deserialize_reader(reader: &mut R) -> borsh::io::Result { + let s = ::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 { type Error = CapacityError<&'a str>; diff --git a/src/arrayvec.rs b/src/arrayvec.rs index 6f64ba5..9734dd2 100644 --- a/src/arrayvec.rs +++ b/src/arrayvec.rs @@ -1301,3 +1301,42 @@ impl<'de, T: Deserialize<'de>, const CAP: usize> Deserialize<'de> for ArrayVec(PhantomData)) } } + +#[cfg(feature = "borsh")] +/// Requires crate feature `"borsh"` +impl borsh::BorshSerialize for ArrayVec +where + T: borsh::BorshSerialize, +{ + fn serialize(&self, writer: &mut W) -> borsh::io::Result<()> { + let vs = self.as_slice(); + ::serialize(&vs.len(), writer)?; + for elem in vs { + ::serialize(elem, writer)?; + } + Ok(()) + } +} + +#[cfg(feature = "borsh")] +/// Requires crate feature `"borsh"` +impl borsh::BorshDeserialize for ArrayVec +where + T: borsh::BorshDeserialize, +{ + fn deserialize_reader(reader: &mut R) -> borsh::io::Result { + let mut values = Self::new(); + let len = ::deserialize_reader(reader)?; + for _ in 0..len { + let elem = ::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) + } +}