diff --git a/src/lib.rs b/src/lib.rs index 01888bc..08b8008 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -156,6 +156,41 @@ pub type ArrayN = Array::Size>; /// /// let arr: Array = Array([1, 2, 3]); /// ``` +/// +/// ## [`Borrow`] impls +/// +/// The [`Array`] type has impls of the [`Borrow`] trait from `core` for both `[T]` and `[T; N]`, +/// which should make it usable anywhere with e.g. `Borrow<[T]>` bounds. +/// +/// ### `Borrow>` for `[T; N]` +/// +/// This crate provides a `Borrow` impl for `[T; N]` which makes it possible to write APIs in terms +/// of `[T; N]` rather than `Array`, so the caller doesn't need to import `Array` at all: +/// +/// ``` +/// use std::borrow::Borrow; +/// use hybrid_array::{Array, ArraySize, AssocArraySize, ArrayN, sizes::U3}; +/// +/// pub fn getn_hybrid(arr: &Array, n: usize) -> &T { +/// &arr[2] +/// } +/// +/// pub fn getn_generic(arr: &[T; N], n: usize) -> &T +/// where +/// [T; N]: AssocArraySize + Borrow> +/// { +/// getn_hybrid(arr.borrow(), n) +/// } +/// +/// let array = [0u8, 1, 2, 3]; +/// let x = getn_generic(&array, 2); +/// assert_eq!(x, &2); +/// ``` +/// +/// Note that the [`AssocArraySize`] trait can be used to determine the appropriate +/// [`Array`] size for a given `[T; N]`, and the [`ArrayN`] trait (which internally uses +/// [`AssocArraySize`]) can be used to determine the specific [`Array`] type for a given +/// const generic size. #[repr(transparent)] pub struct Array(pub U::ArrayType); @@ -490,6 +525,16 @@ where } } +impl BorrowMut<[T]> for Array +where + U: ArraySize, +{ + #[inline] + fn borrow_mut(&mut self) -> &mut [T] { + self.0.as_mut() + } +} + impl Borrow<[T; N]> for Array where U: ArraySize = [T; N]>, @@ -500,23 +545,33 @@ where } } -impl BorrowMut<[T]> for Array +impl BorrowMut<[T; N]> for Array where - U: ArraySize, + U: ArraySize = [T; N]>, { #[inline] - fn borrow_mut(&mut self) -> &mut [T] { - self.0.as_mut() + fn borrow_mut(&mut self) -> &mut [T; N] { + &mut self.0 } } -impl BorrowMut<[T; N]> for Array +impl Borrow> for [T; N] where U: ArraySize = [T; N]>, { #[inline] - fn borrow_mut(&mut self) -> &mut [T; N] { - &mut self.0 + fn borrow(&self) -> &Array { + self.into() + } +} + +impl BorrowMut> for [T; N] +where + U: ArraySize = [T; N]>, +{ + #[inline] + fn borrow_mut(&mut self) -> &mut Array { + self.into() } }