Debian Codegraph @

third_party/rust/generic-array/src/lib.rs

raw
1 //! This crate implements a structure that can be used as a generic array type.
2 //! Core Rust array types `[T; N]` can't be used generically with
3 //! respect to `N`, so for example this:
4 //!
5 //! ```rust{compile_fail}
6 //! struct Foo<T, N> {
7 //! data: [T; N]
8 //! }
9 //! ```
10 //!
11 //! won't work.
12 //!
13 //! **generic-array** exports a `GenericArray<T,N>` type, which lets
14 //! the above be implemented as:
15 //!
16 //! ```rust
17 //! use generic_array::{ArrayLength, GenericArray};
18 //!
19 //! struct Foo<T, N: ArrayLength<T>> {
20 //! data: GenericArray<T,N>
21 //! }
22 //! ```
23 //!
24 //! The `ArrayLength<T>` trait is implemented by default for
25 //! [unsigned integer types](../typenum/uint/index.html) from
26 //! [typenum](../typenum/index.html):
27 //!
28 //! ```rust
29 //! # use generic_array::{ArrayLength, GenericArray};
30 //! use generic_array::typenum::U5;
31 //!
32 //! struct Foo<N: ArrayLength<i32>> {
33 //! data: GenericArray<i32, N>
34 //! }
35 //!
36 //! # fn main() {
37 //! let foo = Foo::<U5>{data: GenericArray::default()};
38 //! # }
39 //! ```
40 //!
41 //! For example, `GenericArray<T, U5>` would work almost like `[T; 5]`:
42 //!
43 //! ```rust
44 //! # use generic_array::{ArrayLength, GenericArray};
45 //! use generic_array::typenum::U5;
46 //!
47 //! struct Foo<T, N: ArrayLength<T>> {
48 //! data: GenericArray<T, N>
49 //! }
50 //!
51 //! # fn main() {
52 //! let foo = Foo::<i32, U5>{data: GenericArray::default()};
53 //! # }
54 //! ```
55 //!
56 //! For ease of use, an `arr!` macro is provided - example below:
57 //!
58 //! ```
59 //! # #[macro_use]
60 //! # extern crate generic_array;
61 //! # extern crate typenum;
62 //! # fn main() {
63 //! let array = arr![u32; 1, 2, 3];
64 //! assert_eq!(array[2], 3);
65 //! # }
66 //! ```
67
68 #![deny(missing_docs)]
69 #![deny(meta_variable_misuse)]
70 #![no_std]
71
72 #[cfg(feature = "serde")]
73 extern crate serde;
74
75 #[cfg(feature = "zeroize")]
76 extern crate zeroize;
77
78 #[cfg(test)]
79 extern crate bincode;
80
81 pub extern crate typenum;
82
83 mod hex;
84 mod impls;
85
86 #[cfg(feature = "serde")]
87 mod impl_serde;
88
89 #[cfg(feature = "zeroize")]
90 mod impl_zeroize;
91
92 use core::iter::FromIterator;
93 use core::marker::PhantomData;
94 use core::mem::{MaybeUninit, ManuallyDrop};
95 use core::ops::{Deref, DerefMut};
96 use core::{mem, ptr, slice};
97 use typenum::bit::{B0, B1};
98 use typenum::uint::{UInt, UTerm, Unsigned};
99
100 #[cfg_attr(test, macro_use)]
101 pub mod arr;
102 pub mod functional;
103 pub mod iter;
104 pub mod sequence;
105
106 use self::functional::*;
107 pub use self::iter::GenericArrayIter;
108 use self::sequence::*;
109
110 /// Trait making `GenericArray` work, marking types to be used as length of an array
111 pub unsafe trait ArrayLength<T>: Unsigned {
112 /// Associated type representing the array type for the number
113 type ArrayType;
114 }
115
116 unsafe impl<T> ArrayLength<T> for UTerm {
117 #[doc(hidden)]
118 type ArrayType = [T; 0];
119 }
120
121 /// Internal type used to generate a struct of appropriate size
122 #[allow(dead_code)]
123 #[repr(C)]
124 #[doc(hidden)]
125 pub struct GenericArrayImplEven<T, U> {
126 parent1: U,
127 parent2: U,
128 _marker: PhantomData<T>,
129 }
130
131 impl<T: Clone, U: Clone> Clone for GenericArrayImplEven<T, U> {
132 fn clone(&self) -> GenericArrayImplEven<T, U> {
133 GenericArrayImplEven {
134 parent1: self.parent1.clone(),
135 parent2: self.parent2.clone(),
136 _marker: PhantomData,
137 }
138 }
139 }
140
141 impl<T: Copy, U: Copy> Copy for GenericArrayImplEven<T, U> {}
142
143 /// Internal type used to generate a struct of appropriate size
144 #[allow(dead_code)]
145 #[repr(C)]
146 #[doc(hidden)]
147 pub struct GenericArrayImplOdd<T, U> {
148 parent1: U,
149 parent2: U,
150 data: T,
151 }
152
153 impl<T: Clone, U: Clone> Clone for GenericArrayImplOdd<T, U> {
154 fn clone(&self) -> GenericArrayImplOdd<T, U> {
155 GenericArrayImplOdd {
156 parent1: self.parent1.clone(),
157 parent2: self.parent2.clone(),
158 data: self.data.clone(),
159 }
160 }
161 }
162
163 impl<T: Copy, U: Copy> Copy for GenericArrayImplOdd<T, U> {}
164
165 unsafe impl<T, N: ArrayLength<T>> ArrayLength<T> for UInt<N, B0> {
166 #[doc(hidden)]
167 type ArrayType = GenericArrayImplEven<T, N::ArrayType>;
168 }
169
170 unsafe impl<T, N: ArrayLength<T>> ArrayLength<T> for UInt<N, B1> {
171 #[doc(hidden)]
172 type ArrayType = GenericArrayImplOdd<T, N::ArrayType>;
173 }
174
175 /// Struct representing a generic array - `GenericArray<T, N>` works like [T; N]
176 #[allow(dead_code)]
177 #[repr(transparent)]
178 pub struct GenericArray<T, U: ArrayLength<T>> {
179 data: U::ArrayType,
180 }
181
182 unsafe impl<T: Send, N: ArrayLength<T>> Send for GenericArray<T, N> {}
183 unsafe impl<T: Sync, N: ArrayLength<T>> Sync for GenericArray<T, N> {}
184
185 impl<T, N> Deref for GenericArray<T, N>
186 where
187 N: ArrayLength<T>,
188 {
189 type Target = [T];
190
191 #[inline(always)]
192 fn deref(&self) -> &[T] {
193 unsafe { slice::from_raw_parts(self as *const Self as *const T, N::USIZE) }
194 }
195 }
196
197 impl<T, N> DerefMut for GenericArray<T, N>
198 where
199 N: ArrayLength<T>,
200 {
201 #[inline(always)]
202 fn deref_mut(&mut self) -> &mut [T] {
203 unsafe { slice::from_raw_parts_mut(self as *mut Self as *mut T, N::USIZE) }
204 }
205 }
206
207 /// Creates an array one element at a time using a mutable iterator
208 /// you can write to with `ptr::write`.
209 ///
210 /// Increment the position while iterating to mark off created elements,
211 /// which will be dropped if `into_inner` is not called.
212 #[doc(hidden)]
213 pub struct ArrayBuilder<T, N: ArrayLength<T>> {
214 array: MaybeUninit<GenericArray<T, N>>,
215 position: usize,
216 }
217
218 impl<T, N: ArrayLength<T>> ArrayBuilder<T, N> {
219 #[doc(hidden)]
220 #[inline]
221 pub unsafe fn new() -> ArrayBuilder<T, N> {
222 ArrayBuilder {
223 array: MaybeUninit::uninit(),
224 position: 0,
225 }
226 }
227
228 /// Creates a mutable iterator for writing to the array using `ptr::write`.
229 ///
230 /// Increment the position value given as a mutable reference as you iterate
231 /// to mark how many elements have been created.
232 #[doc(hidden)]
233 #[inline]
234 pub unsafe fn iter_position(&mut self) -> (slice::IterMut<T>, &mut usize) {
235 ((&mut *self.array.as_mut_ptr()).iter_mut(), &mut self.position)
236 }
237
238 /// When done writing (assuming all elements have been written to),
239 /// get the inner array.
240 #[doc(hidden)]
241 #[inline]
242 pub unsafe fn into_inner(self) -> GenericArray<T, N> {
243 let array = ptr::read(&self.array);
244
245 mem::forget(self);
246
247 array.assume_init()
248 }
249 }
250
251 impl<T, N: ArrayLength<T>> Drop for ArrayBuilder<T, N> {
252 fn drop(&mut self) {
253 if mem::needs_drop::<T>() {
254 unsafe {
255 for value in &mut (&mut *self.array.as_mut_ptr())[..self.position] {
256 ptr::drop_in_place(value);
257 }
258 }
259 }
260 }
261 }
262
263 /// Consumes an array.
264 ///
265 /// Increment the position while iterating and any leftover elements
266 /// will be dropped if position does not go to N
267 #[doc(hidden)]
268 pub struct ArrayConsumer<T, N: ArrayLength<T>> {
269 array: ManuallyDrop<GenericArray<T, N>>,
270 position: usize,
271 }
272
273 impl<T, N: ArrayLength<T>> ArrayConsumer<T, N> {
274 #[doc(hidden)]
275 #[inline]
276 pub unsafe fn new(array: GenericArray<T, N>) -> ArrayConsumer<T, N> {
277 ArrayConsumer {
278 array: ManuallyDrop::new(array),
279 position: 0,
280 }
281 }
282
283 /// Creates an iterator and mutable reference to the internal position
284 /// to keep track of consumed elements.
285 ///
286 /// Increment the position as you iterate to mark off consumed elements
287 #[doc(hidden)]
288 #[inline]
289 pub unsafe fn iter_position(&mut self) -> (slice::Iter<T>, &mut usize) {
290 (self.array.iter(), &mut self.position)
291 }
292 }
293
294 impl<T, N: ArrayLength<T>> Drop for ArrayConsumer<T, N> {
295 fn drop(&mut self) {
296 if mem::needs_drop::<T>() {
297 for value in &mut self.array[self.position..N::USIZE] {
298 unsafe {
299 ptr::drop_in_place(value);
300 }
301 }
302 }
303 }
304 }
305
306 impl<'a, T: 'a, N> IntoIterator for &'a GenericArray<T, N>
307 where
308 N: ArrayLength<T>,
309 {
310 type IntoIter = slice::Iter<'a, T>;
311 type Item = &'a T;
312
313 fn into_iter(self: &'a GenericArray<T, N>) -> Self::IntoIter {
314 self.as_slice().iter()
315 }
316 }
317
318 impl<'a, T: 'a, N> IntoIterator for &'a mut GenericArray<T, N>
319 where
320 N: ArrayLength<T>,
321 {
322 type IntoIter = slice::IterMut<'a, T>;
323 type Item = &'a mut T;
324
325 fn into_iter(self: &'a mut GenericArray<T, N>) -> Self::IntoIter {
326 self.as_mut_slice().iter_mut()
327 }
328 }
329
330 impl<T, N> FromIterator<T> for GenericArray<T, N>
331 where
332 N: ArrayLength<T>,
333 {
334 fn from_iter<I>(iter: I) -> GenericArray<T, N>
335 where
336 I: IntoIterator<Item = T>,
337 {
338 unsafe {
339 let mut destination = ArrayBuilder::new();
340
341 {
342 let (destination_iter, position) = destination.iter_position();
343
344 iter.into_iter()
345 .zip(destination_iter)
346 .for_each(|(src, dst)| {
347 ptr::write(dst, src);
348
349 *position += 1;
350 });
351 }
352
353 if destination.position < N::USIZE {
354 from_iter_length_fail(destination.position, N::USIZE);
355 }
356
357 destination.into_inner()
358 }
359 }
360 }
361
362 #[inline(never)]
363 #[cold]
364 fn from_iter_length_fail(length: usize, expected: usize) -> ! {
365 panic!(
366 "GenericArray::from_iter received {} elements but expected {}",
367 length, expected
368 );
369 }
370
371 unsafe impl<T, N> GenericSequence<T> for GenericArray<T, N>
372 where
373 N: ArrayLength<T>,
374 Self: IntoIterator<Item = T>,
375 {
376 type Length = N;
377 type Sequence = Self;
378
379 fn generate<F>(mut f: F) -> GenericArray<T, N>
380 where
381 F: FnMut(usize) -> T,
382 {
383 unsafe {
384 let mut destination = ArrayBuilder::new();
385
386 {
387 let (destination_iter, position) = destination.iter_position();
388
389 destination_iter.enumerate().for_each(|(i, dst)| {
390 ptr::write(dst, f(i));
391
392 *position += 1;
393 });
394 }
395
396 destination.into_inner()
397 }
398 }
399
400 #[doc(hidden)]
401 fn inverted_zip<B, U, F>(
402 self,
403 lhs: GenericArray<B, Self::Length>,
404 mut f: F,
405 ) -> MappedSequence<GenericArray<B, Self::Length>, B, U>
406 where
407 GenericArray<B, Self::Length>:
408 GenericSequence<B, Length = Self::Length> + MappedGenericSequence<B, U>,
409 Self: MappedGenericSequence<T, U>,
410 Self::Length: ArrayLength<B> + ArrayLength<U>,
411 F: FnMut(B, Self::Item) -> U,
412 {
413 unsafe {
414 let mut left = ArrayConsumer::new(lhs);
415 let mut right = ArrayConsumer::new(self);
416
417 let (left_array_iter, left_position) = left.iter_position();
418 let (right_array_iter, right_position) = right.iter_position();
419
420 FromIterator::from_iter(left_array_iter.zip(right_array_iter).map(|(l, r)| {
421 let left_value = ptr::read(l);
422 let right_value = ptr::read(r);
423
424 *left_position += 1;
425 *right_position += 1;
426
427 f(left_value, right_value)
428 }))
429 }
430 }
431
432 #[doc(hidden)]
433 fn inverted_zip2<B, Lhs, U, F>(self, lhs: Lhs, mut f: F) -> MappedSequence<Lhs, B, U>
434 where
435 Lhs: GenericSequence<B, Length = Self::Length> + MappedGenericSequence<B, U>,
436 Self: MappedGenericSequence<T, U>,
437 Self::Length: ArrayLength<B> + ArrayLength<U>,
438 F: FnMut(Lhs::Item, Self::Item) -> U,
439 {
440 unsafe {
441 let mut right = ArrayConsumer::new(self);
442
443 let (right_array_iter, right_position) = right.iter_position();
444
445 FromIterator::from_iter(
446 lhs.into_iter()
447 .zip(right_array_iter)
448 .map(|(left_value, r)| {
449 let right_value = ptr::read(r);
450
451 *right_position += 1;
452
453 f(left_value, right_value)
454 }),
455 )
456 }
457 }
458 }
459
460 unsafe impl<T, U, N> MappedGenericSequence<T, U> for GenericArray<T, N>
461 where
462 N: ArrayLength<T> + ArrayLength<U>,
463 GenericArray<U, N>: GenericSequence<U, Length = N>,
464 {
465 type Mapped = GenericArray<U, N>;
466 }
467
468 unsafe impl<T, N> FunctionalSequence<T> for GenericArray<T, N>
469 where
470 N: ArrayLength<T>,
471 Self: GenericSequence<T, Item = T, Length = N>,
472 {
473 fn map<U, F>(self, mut f: F) -> MappedSequence<Self, T, U>
474 where
475 Self::Length: ArrayLength<U>,
476 Self: MappedGenericSequence<T, U>,
477 F: FnMut(T) -> U,
478 {
479 unsafe {
480 let mut source = ArrayConsumer::new(self);
481
482 let (array_iter, position) = source.iter_position();
483
484 FromIterator::from_iter(array_iter.map(|src| {
485 let value = ptr::read(src);
486
487 *position += 1;
488
489 f(value)
490 }))
491 }
492 }
493
494 #[inline]
495 fn zip<B, Rhs, U, F>(self, rhs: Rhs, f: F) -> MappedSequence<Self, T, U>
496 where
497 Self: MappedGenericSequence<T, U>,
498 Rhs: MappedGenericSequence<B, U, Mapped = MappedSequence<Self, T, U>>,
499 Self::Length: ArrayLength<B> + ArrayLength<U>,
500 Rhs: GenericSequence<B, Length = Self::Length>,
501 F: FnMut(T, Rhs::Item) -> U,
502 {
503 rhs.inverted_zip(self, f)
504 }
505
506 fn fold<U, F>(self, init: U, mut f: F) -> U
507 where
508 F: FnMut(U, T) -> U,
509 {
510 unsafe {
511 let mut source = ArrayConsumer::new(self);
512
513 let (array_iter, position) = source.iter_position();
514
515 array_iter.fold(init, |acc, src| {
516 let value = ptr::read(src);
517
518 *position += 1;
519
520 f(acc, value)
521 })
522 }
523 }
524 }
525
526 impl<T, N> GenericArray<T, N>
527 where
528 N: ArrayLength<T>,
529 {
530 /// Extracts a slice containing the entire array.
531 #[inline]
532 pub fn as_slice(&self) -> &[T] {
533 self.deref()
534 }
535
536 /// Extracts a mutable slice containing the entire array.
537 #[inline]
538 pub fn as_mut_slice(&mut self) -> &mut [T] {
539 self.deref_mut()
540 }
541
542 /// Converts slice to a generic array reference with inferred length;
543 ///
544 /// Length of the slice must be equal to the length of the array.
545 #[inline]
546 pub fn from_slice(slice: &[T]) -> &GenericArray<T, N> {
547 slice.into()
548 }
549
550 /// Converts mutable slice to a mutable generic array reference
551 ///
552 /// Length of the slice must be equal to the length of the array.
553 #[inline]
554 pub fn from_mut_slice(slice: &mut [T]) -> &mut GenericArray<T, N> {
555 slice.into()
556 }
557 }
558
559 impl<'a, T, N: ArrayLength<T>> From<&'a [T]> for &'a GenericArray<T, N> {
560 /// Converts slice to a generic array reference with inferred length;
561 ///
562 /// Length of the slice must be equal to the length of the array.
563 #[inline]
564 fn from(slice: &[T]) -> &GenericArray<T, N> {
565 assert_eq!(slice.len(), N::USIZE);
566
567 unsafe { &*(slice.as_ptr() as *const GenericArray<T, N>) }
568 }
569 }
570
571 impl<'a, T, N: ArrayLength<T>> From<&'a mut [T]> for &'a mut GenericArray<T, N> {
572 /// Converts mutable slice to a mutable generic array reference
573 ///
574 /// Length of the slice must be equal to the length of the array.
575 #[inline]
576 fn from(slice: &mut [T]) -> &mut GenericArray<T, N> {
577 assert_eq!(slice.len(), N::USIZE);
578
579 unsafe { &mut *(slice.as_mut_ptr() as *mut GenericArray<T, N>) }
580 }
581 }
582
583 impl<T: Clone, N> GenericArray<T, N>
584 where
585 N: ArrayLength<T>,
586 {
587 /// Construct a `GenericArray` from a slice by cloning its content
588 ///
589 /// Length of the slice must be equal to the length of the array
590 #[inline]
591 pub fn clone_from_slice(list: &[T]) -> GenericArray<T, N> {
592 Self::from_exact_iter(list.iter().cloned())
593 .expect("Slice must be the same length as the array")
594 }
595 }
596
597 impl<T, N> GenericArray<T, N>
598 where
599 N: ArrayLength<T>,
600 {
601 /// Creates a new `GenericArray` instance from an iterator with a specific size.
602 ///
603 /// Returns `None` if the size is not equal to the number of elements in the `GenericArray`.
604 pub fn from_exact_iter<I>(iter: I) -> Option<Self>
605 where
606 I: IntoIterator<Item = T>,
607 {
608 let mut iter = iter.into_iter();
609
610 unsafe {
611 let mut destination = ArrayBuilder::new();
612
613 {
614 let (destination_iter, position) = destination.iter_position();
615
616 destination_iter.zip(&mut iter).for_each(|(dst, src)| {
617 ptr::write(dst, src);
618
619 *position += 1;
620 });
621
622 // The iterator produced fewer than `N` elements.
623 if *position != N::USIZE {
624 return None;
625 }
626
627 // The iterator produced more than `N` elements.
628 if iter.next().is_some() {
629 return None;
630 }
631 }
632
633 Some(destination.into_inner())
634 }
635 }
636 }
637
638 /// A reimplementation of the `transmute` function, avoiding problems
639 /// when the compiler can't prove equal sizes.
640 #[inline]
641 #[doc(hidden)]
642 pub unsafe fn transmute<A, B>(a: A) -> B {
643 let a = ManuallyDrop::new(a);
644 ::core::ptr::read(&*a as *const A as *const B)
645 }
646
647 #[cfg(test)]
648 mod test {
649 // Compile with:
650 // cargo rustc --lib --profile test --release --
651 // -C target-cpu=native -C opt-level=3 --emit asm
652 // and view the assembly to make sure test_assembly generates
653 // SIMD instructions instead of a naive loop.
654
655 #[inline(never)]
656 pub fn black_box<T>(val: T) -> T {
657 use core::{mem, ptr};
658
659 let ret = unsafe { ptr::read_volatile(&val) };
660 mem::forget(val);
661 ret
662 }
663
664 #[test]
665 fn test_assembly() {
666 use crate::functional::*;
667
668 let a = black_box(arr![i32; 1, 3, 5, 7]);
669 let b = black_box(arr![i32; 2, 4, 6, 8]);
670
671 let c = (&a).zip(b, |l, r| l + r);
672
673 let d = a.fold(0, |a, x| a + x);
674
675 assert_eq!(c, arr![i32; 3, 7, 11, 15]);
676
677 assert_eq!(d, 16);
678 }
679 }