|
65 | 65 | {
|
66 | 66 | type Size = U;
|
67 | 67 | }
|
| 68 | + |
| 69 | +/// Obtain an `&Array` reference for a given type. |
| 70 | +/// |
| 71 | +/// This provides functionality equivalent to `AsRef<Array>` or `Borrow<Array>`, but is deliberately |
| 72 | +/// implemented as its own trait both so it can leverage [`AssocArraySize`] to determine the |
| 73 | +/// array size, and also to avoid inference problems that occur when third party impls of traits |
| 74 | +/// like [`AsRef`] and [`Borrow`] are added to `[T; N]`. |
| 75 | +/// |
| 76 | +/// # Usage with `[T; N]` |
| 77 | +/// |
| 78 | +/// ``` |
| 79 | +/// use hybrid_array::{Array, ArraySize, AsArrayRef}; |
| 80 | +/// |
| 81 | +/// pub fn getn_hybrid<T, U: ArraySize>(arr: &Array<T, U>, n: usize) -> &T { |
| 82 | +/// &arr[2] |
| 83 | +/// } |
| 84 | +/// |
| 85 | +/// pub fn getn_generic<T, const N: usize>(arr: &[T; N], n: usize) -> &T |
| 86 | +/// where |
| 87 | +/// [T; N]: AsArrayRef<T> |
| 88 | +/// { |
| 89 | +/// getn_hybrid(arr.as_array_ref(), n) |
| 90 | +/// } |
| 91 | +/// |
| 92 | +/// let array = [0u8, 1, 2, 3]; |
| 93 | +/// let x = getn_generic(&array, 2); |
| 94 | +/// assert_eq!(x, &2); |
| 95 | +/// ``` |
| 96 | +pub trait AsArrayRef<T>: AssocArraySize { |
| 97 | + /// Converts this type into an immutable [`Array`] reference. |
| 98 | + fn as_array_ref(&self) -> &Array<T, Self::Size>; |
| 99 | +} |
| 100 | + |
| 101 | +/// Obtain a `&mut Array` reference for a given type. |
| 102 | +/// |
| 103 | +/// Companion trait to [`AsArrayRef`] for mutable references, equivalent to [`AsMut`] or |
| 104 | +/// [`BorrowMut`]. |
| 105 | +pub trait AsArrayMut<T>: AsArrayRef<T> { |
| 106 | + /// Converts this type into a mutable [`Array`] reference. |
| 107 | + fn as_array_mut(&mut self) -> &mut Array<T, Self::Size>; |
| 108 | +} |
| 109 | + |
| 110 | +impl<T, U> AsArrayRef<T> for Array<T, U> |
| 111 | +where |
| 112 | + U: ArraySize, |
| 113 | +{ |
| 114 | + fn as_array_ref(&self) -> &Self { |
| 115 | + self |
| 116 | + } |
| 117 | +} |
| 118 | + |
| 119 | +impl<T, U> AsArrayMut<T> for Array<T, U> |
| 120 | +where |
| 121 | + U: ArraySize, |
| 122 | +{ |
| 123 | + fn as_array_mut(&mut self) -> &mut Self { |
| 124 | + self |
| 125 | + } |
| 126 | +} |
| 127 | + |
| 128 | +impl<T, U, const N: usize> AsArrayRef<T> for [T; N] |
| 129 | +where |
| 130 | + Self: AssocArraySize<Size = U>, |
| 131 | + U: ArraySize<ArrayType<T> = Self>, |
| 132 | +{ |
| 133 | + fn as_array_ref(&self) -> &Array<T, U> { |
| 134 | + self.into() |
| 135 | + } |
| 136 | +} |
| 137 | + |
| 138 | +impl<T, U, const N: usize> AsArrayMut<T> for [T; N] |
| 139 | +where |
| 140 | + Self: AssocArraySize<Size = U>, |
| 141 | + U: ArraySize<ArrayType<T> = Self>, |
| 142 | +{ |
| 143 | + fn as_array_mut(&mut self) -> &mut Array<T, U> { |
| 144 | + self.into() |
| 145 | + } |
| 146 | +} |
0 commit comments