-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathtraits.rs
More file actions
289 lines (253 loc) · 8.57 KB
/
traits.rs
File metadata and controls
289 lines (253 loc) · 8.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
//! Trait definitions.
use crate::Array;
use core::{
borrow::{Borrow, BorrowMut},
fmt::Debug,
ops::{Index, IndexMut, Range},
};
use typenum::Unsigned;
/// Trait which associates a [`usize`] size and `ArrayType` with a
/// `typenum`-provided [`Unsigned`] integer.
///
/// # Safety
///
/// `ArrayType` MUST be an array with a number of elements exactly equal to
/// [`Unsigned::USIZE`]. Breaking this requirement will cause undefined behavior.
///
/// NOTE: This trait is effectively sealed and can not be implemented by third-party crates.
/// It is implemented only for a number of types defined in [`typenum::consts`].
#[diagnostic::on_unimplemented(note = "size may not be supported (see RustCrypto/hybrid-array#66)")]
pub unsafe trait ArraySize: Unsigned + Debug {
/// Array type which corresponds to this size.
///
/// This is always defined to be `[T; N]` where `N` is the same as
/// [`ArraySize::USIZE`][`typenum::Unsigned::USIZE`].
type ArrayType<T>: AssocArraySize<Size = Self>
+ AsRef<[T]>
+ AsMut<[T]>
+ Borrow<[T]>
+ BorrowMut<[T]>
+ From<Array<T, Self>>
+ Index<usize>
+ Index<Range<usize>>
+ IndexMut<usize>
+ IndexMut<Range<usize>>
+ Into<Array<T, Self>>
+ IntoIterator<Item = T>;
}
/// Associates an [`ArraySize`] with a given type. Can be used to accept `[T; N]` const generic
/// arguments and convert to [`Array`] internally.
///
/// This trait is also the magic glue that makes the [`ArrayN`][`crate::ArrayN`] type alias work.
///
/// # Example
///
/// ```
/// use hybrid_array::{ArrayN, AssocArraySize};
///
/// pub fn example<const N: usize>(bytes: &[u8; N])
/// where
/// [u8; N]: AssocArraySize + AsRef<ArrayN<u8, N>>
/// {
/// // _arrayn is ArrayN<u8, N>
/// let _arrayn = bytes.as_ref();
/// }
/// ```
pub trait AssocArraySize: Sized {
/// Size of an array type, expressed as a [`typenum`]-based [`ArraySize`].
type Size: ArraySize;
}
impl<T, U> AssocArraySize for Array<T, U>
where
U: ArraySize,
{
type Size = U;
}
/// Obtain an `&Array` reference for a given type.
///
/// This provides functionality equivalent to `AsRef<Array>` or `Borrow<Array>`, but is deliberately
/// implemented as its own trait both so it can leverage [`AssocArraySize`] to determine the
/// array size, and also to avoid inference problems that occur when third party impls of traits
/// like [`AsRef`] and [`Borrow`] are added to `[T; N]`.
///
/// # Usage with `[T; N]`
///
/// ```
/// use hybrid_array::{Array, ArraySize, AsArrayRef};
///
/// pub fn getn_hybrid<T, U: ArraySize>(arr: &Array<T, U>, n: usize) -> &T {
/// &arr[2]
/// }
///
/// pub fn getn_generic<T, const N: usize>(arr: &[T; N], n: usize) -> &T
/// where
/// [T; N]: AsArrayRef<T>
/// {
/// getn_hybrid(arr.as_array_ref(), n)
/// }
///
/// let array = [0u8, 1, 2, 3];
/// let x = getn_generic(&array, 2);
/// assert_eq!(x, &2);
/// ```
pub trait AsArrayRef<T>: AssocArraySize {
/// Converts this type into an immutable [`Array`] reference.
fn as_array_ref(&self) -> &Array<T, Self::Size>;
}
/// Obtain a `&mut Array` reference for a given type.
///
/// Companion trait to [`AsArrayRef`] for mutable references, equivalent to [`AsMut`] or
/// [`BorrowMut`].
pub trait AsArrayMut<T>: AsArrayRef<T> {
/// Converts this type into a mutable [`Array`] reference.
fn as_array_mut(&mut self) -> &mut Array<T, Self::Size>;
}
impl<T, U> AsArrayRef<T> for Array<T, U>
where
U: ArraySize,
{
fn as_array_ref(&self) -> &Self {
self
}
}
impl<T, U> AsArrayMut<T> for Array<T, U>
where
U: ArraySize,
{
fn as_array_mut(&mut self) -> &mut Self {
self
}
}
impl<T, U, const N: usize> AsArrayRef<T> for [T; N]
where
Self: AssocArraySize<Size = U>,
U: ArraySize<ArrayType<T> = Self>,
{
fn as_array_ref(&self) -> &Array<T, U> {
self.into()
}
}
impl<T, U, const N: usize> AsArrayMut<T> for [T; N]
where
Self: AssocArraySize<Size = U>,
U: ArraySize<ArrayType<T> = Self>,
{
fn as_array_mut(&mut self) -> &mut Array<T, U> {
self.into()
}
}
/// Extension trait for `[T]` providing methods for working with [`Array`].
pub trait SliceExt<T>: sealed::Sealed {
/// Get a reference to an array from a slice, if the slice is exactly the size of the array.
///
/// Returns `None` if the slice's length is not exactly equal to the array size.
fn as_hybrid_array<U: ArraySize>(&self) -> Option<&Array<T, U>>;
/// Get a mutable reference to an array from a slice, if the slice is exactly the size of the
/// array.
///
/// Returns `None` if the slice's length is not exactly equal to the array size.
fn as_mut_hybrid_array<U: ArraySize>(&mut self) -> Option<&mut Array<T, U>>;
/// Splits the shared slice into a slice of `U`-element arrays, starting at the beginning
/// of the slice, and a remainder slice with length strictly less than `U`.
///
/// # Panics
/// If `U` is 0.
fn as_hybrid_chunks<U: ArraySize>(&self) -> (&[Array<T, U>], &[T]);
/// Splits the exclusive slice into a slice of `U`-element arrays, starting at the beginning
/// of the slice, and a remainder slice with length strictly less than `U`.
///
/// # Panics
/// If `U` is 0.
fn as_hybrid_chunks_mut<U: ArraySize>(&mut self) -> (&mut [Array<T, U>], &mut [T]);
}
impl<T> SliceExt<T> for [T] {
fn as_hybrid_array<U: ArraySize>(&self) -> Option<&Array<T, U>> {
Array::slice_as_array(self)
}
fn as_mut_hybrid_array<U: ArraySize>(&mut self) -> Option<&mut Array<T, U>> {
Array::slice_as_mut_array(self)
}
fn as_hybrid_chunks<U: ArraySize>(&self) -> (&[Array<T, U>], &[T]) {
Array::slice_as_chunks(self)
}
fn as_hybrid_chunks_mut<U: ArraySize>(&mut self) -> (&mut [Array<T, U>], &mut [T]) {
Array::slice_as_chunks_mut(self)
}
}
impl<T> sealed::Sealed for [T] {}
mod sealed {
pub trait Sealed {}
}
#[cfg(test)]
mod tests {
use super::{AsArrayMut, AsArrayRef, SliceExt};
use crate::{
Array,
sizes::{U2, U3},
};
type A = Array<u8, U2>;
#[test]
fn core_as_array_ref() {
assert_eq!([1, 2, 3].as_array_ref(), &Array([1, 2, 3]));
}
#[test]
fn core_as_array_mut() {
assert_eq!([1, 2, 3].as_array_mut(), &Array([1, 2, 3]));
}
#[test]
fn hybrid_as_array_ref() {
assert_eq!(A::from([1, 2]).as_array_ref(), &Array([1, 2]));
}
#[test]
fn hybrid_as_array_mut() {
assert_eq!(A::from([1, 2]).as_array_mut(), &Array([1, 2]));
}
#[test]
fn slice_as_hybrid_array() {
assert_eq!([1, 2].as_hybrid_array::<U3>(), None);
assert_eq!([1, 2, 3].as_hybrid_array::<U3>(), Some(&Array([1, 2, 3])));
assert_eq!([1, 2, 3, 4].as_hybrid_array::<U3>(), None);
}
#[test]
fn slice_as_mut_hybrid_array() {
assert_eq!([1, 2].as_mut_hybrid_array::<U3>(), None);
assert_eq!(
[1, 2, 3].as_mut_hybrid_array::<U3>(),
Some(&mut Array([1, 2, 3]))
);
assert_eq!([1, 2, 3, 4].as_mut_hybrid_array::<U3>(), None);
}
#[test]
fn slice_as_hybrid_chunks() {
let (slice_empty, rem_empty): (&[A], &[u8]) = [].as_hybrid_chunks::<U2>();
assert!(slice_empty.is_empty());
assert!(rem_empty.is_empty());
let (slice_one, rem_one) = [1].as_hybrid_chunks::<U2>();
assert!(slice_one.is_empty());
assert_eq!(rem_one, &[1]);
let (slice_aligned, rem_aligned) = [1u8, 2].as_hybrid_chunks::<U2>();
assert_eq!(slice_aligned, &[Array([1u8, 2])]);
assert_eq!(rem_aligned, b"");
let (slice_unaligned, rem_unaligned) = [1u8, 2, 3].as_hybrid_chunks::<U2>();
assert_eq!(slice_unaligned, &[Array([1u8, 2])]);
assert_eq!(rem_unaligned, &[3]);
}
#[test]
fn slice_as_hybrid_chunks_mut() {
let (slice_empty, rem_empty): (&mut [A], &mut [u8]) = [].as_hybrid_chunks_mut::<U2>();
assert!(slice_empty.is_empty());
assert!(rem_empty.is_empty());
let mut arr1 = [1];
let (slice_one, rem_one) = arr1.as_hybrid_chunks_mut::<U2>();
assert!(slice_one.is_empty());
assert_eq!(rem_one, &[1]);
let mut arr2 = [1u8, 2];
let (slice_aligned, rem_aligned) = arr2.as_hybrid_chunks_mut::<U2>();
assert_eq!(slice_aligned, &mut [Array([1u8, 2])]);
assert_eq!(rem_aligned, b"");
let mut arr3 = [1u8, 2, 3];
let (slice_unaligned, rem_unaligned) = arr3.as_hybrid_chunks_mut::<U2>();
assert_eq!(slice_unaligned, &mut [Array([1u8, 2])]);
assert_eq!(rem_unaligned, &mut [3]);
}
}