From 4772d1f3d81379b253457afcd1e3c47f870f7033 Mon Sep 17 00:00:00 2001 From: Tony Arcieri Date: Mon, 1 Sep 2025 10:53:56 -0600 Subject: [PATCH] Add `alloc` feature with `Box`/`Vec` conversions Adds `TryFrom` impls which convert from `Box`/`Vec`. The main impetus for this is #114 where it's noted such conversions work for `[T; N]` but don't work for the `Array` type, where we are trying to make a type which works as much like core arrays as possible. Closes #114 --- Cargo.toml | 1 + src/lib.rs | 59 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) diff --git a/Cargo.toml b/Cargo.toml index 3c189c8..50e5b48 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -29,6 +29,7 @@ zeroize = { version = "1.8", optional = true, default-features = false } bincode = { version = "2", features = ["serde"] } [features] +alloc = [] extra-sizes = [] [package.metadata.docs.rs] diff --git a/src/lib.rs b/src/lib.rs index 08b8008..7f3f5c4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -105,6 +105,9 @@ //! If you have any questions, please //! [start a discussion](https://github.com/RustCrypto/hybrid-array/discussions). +#[cfg(feature = "alloc")] +extern crate alloc; + pub mod sizes; mod from_fn; @@ -817,6 +820,62 @@ where } } +#[cfg(feature = "alloc")] +impl TryFrom> for Array +where + Self: Clone, + U: ArraySize, +{ + type Error = TryFromSliceError; + + #[inline] + fn try_from(b: alloc::boxed::Box<[T]>) -> Result { + Self::try_from(&*b) + } +} + +#[cfg(feature = "alloc")] +impl<'a, T, U> TryFrom<&'a alloc::boxed::Box<[T]>> for Array +where + Self: Clone, + U: ArraySize, +{ + type Error = TryFromSliceError; + + #[inline] + fn try_from(b: &'a alloc::boxed::Box<[T]>) -> Result { + Self::try_from(&**b) + } +} + +#[cfg(feature = "alloc")] +impl TryFrom> for Array +where + Self: Clone, + U: ArraySize, +{ + type Error = TryFromSliceError; + + #[inline] + fn try_from(v: alloc::vec::Vec) -> Result { + Self::try_from(v.as_slice()) + } +} + +#[cfg(feature = "alloc")] +impl<'a, T, U> TryFrom<&'a alloc::vec::Vec> for Array +where + Self: Clone, + U: ArraySize, +{ + type Error = TryFromSliceError; + + #[inline] + fn try_from(v: &'a alloc::vec::Vec) -> Result { + Self::try_from(v.as_slice()) + } +} + impl<'a, T, U> TryFrom<&'a [T]> for &'a Array where U: ArraySize,