generic_array/lib.rs
1//! This crate implements a structure that can be used as a generic array type.
2//!
3//! **Requires minimum Rust version of 1.83.0
4//!
5//! [Documentation on GH Pages](https://fizyk20.github.io/generic-array/generic_array/)
6//! may be required to view certain types on foreign crates.
7//!
8//! Before Rust 1.51, arrays `[T; N]` were problematic in that they couldn't be
9//! generic with respect to the length `N`, so this wouldn't work:
10//!
11//! ```compile_fail
12//! struct Foo<N> {
13//! data: [i32; N],
14//! }
15//! ```
16//!
17//! Since 1.51, the below syntax is valid:
18//!
19//! ```rust
20//! struct Foo<const N: usize> {
21//! data: [i32; N],
22//! }
23//! ```
24//!
25//! However, the const-generics we have as of writing this are still the minimum-viable product (`min_const_generics`), so many situations still result in errors, such as this example:
26//!
27//! ```compile_fail
28//! # struct Foo<const N: usize> {
29//! # data: [i32; N],
30//! # }
31//! trait Bar {
32//! const LEN: usize;
33//!
34//! // Error: cannot perform const operation using `Self`
35//! fn bar(&self) -> Foo<{ Self::LEN }>;
36//! }
37//! ```
38//!
39//! **generic-array** defines a new trait [`ArrayLength`] and a struct [`GenericArray<T, N: ArrayLength>`](GenericArray),
40//! which lets the above be implemented as:
41//!
42//! ```rust
43//! use generic_array::{GenericArray, ArrayLength};
44//!
45//! struct Foo<N: ArrayLength> {
46//! data: GenericArray<i32, N>
47//! }
48//!
49//! trait Bar {
50//! type LEN: ArrayLength;
51//! fn bar(&self) -> Foo<Self::LEN>;
52//! }
53//! ```
54//!
55//! The [`ArrayLength`] trait is implemented for
56//! [unsigned integer types](typenum::Unsigned) from
57//! [typenum]. For example, [`GenericArray<T, U5>`] would work almost like `[T; 5]`:
58//!
59//! ```rust
60//! # use generic_array::{ArrayLength, GenericArray};
61//! use generic_array::typenum::U5;
62//!
63//! struct Foo<T, N: ArrayLength> {
64//! data: GenericArray<T, N>
65//! }
66//!
67//! let foo = Foo::<i32, U5> { data: GenericArray::default() };
68//! ```
69//!
70//! The `arr!` macro is provided to allow easier creation of literal arrays, as shown below:
71//!
72//! ```rust
73//! # use generic_array::arr;
74//! let array = arr![1, 2, 3];
75//! // array: GenericArray<i32, typenum::U3>
76//! assert_eq!(array[2], 3);
77//! ```
78//! ## Feature flags
79//!
80//! ```toml
81//! [dependencies.generic-array]
82//! features = [
83//! "serde", # Serialize/Deserialize implementation
84//! "zeroize", # Zeroize implementation for setting array elements to zero
85//! "const-default", # Compile-time const default value support via trait
86//! "alloc", # Enables From/TryFrom implementations between GenericArray and Vec<T>/Box<[T]>
87//! "faster-hex" # Enables internal use of the `faster-hex` crate for faster hex encoding via SIMD
88//! ]
89//! ```
90
91#![deny(missing_docs)]
92#![deny(meta_variable_misuse)]
93#![no_std]
94#![cfg_attr(docsrs, feature(doc_auto_cfg))]
95
96pub extern crate typenum;
97
98#[doc(hidden)]
99#[cfg(feature = "alloc")]
100pub extern crate alloc;
101
102mod hex;
103mod impls;
104mod iter;
105
106#[cfg(feature = "alloc")]
107mod impl_alloc;
108
109#[cfg(feature = "const-default")]
110mod impl_const_default;
111
112#[cfg(feature = "serde")]
113mod impl_serde;
114
115#[cfg(feature = "zeroize")]
116mod impl_zeroize;
117
118use core::iter::FromIterator;
119use core::marker::PhantomData;
120use core::mem::{ManuallyDrop, MaybeUninit};
121use core::ops::{Deref, DerefMut};
122use core::{mem, ptr, slice};
123use typenum::bit::{B0, B1};
124use typenum::generic_const_mappings::{Const, ToUInt};
125use typenum::uint::{UInt, UTerm, Unsigned};
126
127#[doc(hidden)]
128#[cfg_attr(test, macro_use)]
129pub mod arr;
130
131pub mod functional;
132pub mod sequence;
133
134mod internal;
135use internal::{ArrayConsumer, IntrusiveArrayBuilder, Sealed};
136
137// re-export to allow doc_auto_cfg to handle it
138#[cfg(feature = "internals")]
139pub mod internals {
140 //! Very unsafe internal functionality.
141 //!
142 //! These are used internally for building and consuming generic arrays. When used correctly,
143 //! they can ensure elements are correctly dropped if something panics while using them.
144 //!
145 //! The API of these is not guaranteed to be stable, as they are not intended for general use.
146
147 pub use crate::internal::{ArrayBuilder, ArrayConsumer, IntrusiveArrayBuilder};
148}
149
150use self::functional::*;
151use self::sequence::*;
152
153pub use self::iter::GenericArrayIter;
154
155/// `ArrayLength` is a type-level [`Unsigned`] integer used to
156/// define the number of elements in a [`GenericArray`].
157///
158/// Consider `N: ArrayLength` to be equivalent to `const N: usize`
159///
160/// ```
161/// # use generic_array::{GenericArray, ArrayLength};
162/// fn foo<N: ArrayLength>(arr: GenericArray<i32, N>) -> i32 {
163/// arr.iter().sum()
164/// }
165/// ```
166/// is equivalent to:
167/// ```
168/// fn foo<const N: usize>(arr: [i32; N]) -> i32 {
169/// arr.iter().sum()
170/// }
171/// ```
172///
173/// # Safety
174///
175/// This trait is effectively sealed due to only being allowed on [`Unsigned`] types,
176/// and therefore cannot be implemented in user code.
177pub unsafe trait ArrayLength: Unsigned + 'static {
178 /// Associated type representing the underlying contiguous memory
179 /// that constitutes an array with the given number of elements.
180 ///
181 /// This is an implementation detail, but is required to be public in cases where certain attributes
182 /// of the inner type of [`GenericArray`] cannot be proven, such as [`Copy`] bounds.
183 ///
184 /// [`Copy`] example:
185 /// ```
186 /// # use generic_array::{GenericArray, ArrayLength};
187 /// struct MyType<N: ArrayLength> {
188 /// data: GenericArray<f32, N>,
189 /// }
190 ///
191 /// impl<N: ArrayLength> Clone for MyType<N> where N::ArrayType<f32>: Copy {
192 /// fn clone(&self) -> Self { MyType { ..*self } }
193 /// }
194 ///
195 /// impl<N: ArrayLength> Copy for MyType<N> where N::ArrayType<f32>: Copy {}
196 /// ```
197 ///
198 /// Alternatively, using the entire `GenericArray<f32, N>` type as the bounds works:
199 /// ```ignore
200 /// where GenericArray<f32, N>: Copy
201 /// ```
202 type ArrayType<T>: Sealed;
203}
204
205unsafe impl ArrayLength for UTerm {
206 #[doc(hidden)]
207 type ArrayType<T> = [T; 0];
208}
209
210/// Implemented for types which can have an associated [`ArrayLength`],
211/// such as [`Const<N>`] for use with const-generics.
212///
213/// ```
214/// use generic_array::{GenericArray, IntoArrayLength, ConstArrayLength, typenum::Const};
215///
216/// fn some_array_interopt<const N: usize>(value: [u32; N]) -> GenericArray<u32, ConstArrayLength<N>>
217/// where
218/// Const<N>: IntoArrayLength,
219/// {
220/// let ga = GenericArray::from(value);
221/// // do stuff
222/// ga
223/// }
224/// ```
225///
226/// This is mostly to simplify the `where` bounds, equivalent to:
227///
228/// ```
229/// use generic_array::{GenericArray, ArrayLength, typenum::{Const, U, ToUInt}};
230///
231/// fn some_array_interopt<const N: usize>(value: [u32; N]) -> GenericArray<u32, U<N>>
232/// where
233/// Const<N>: ToUInt,
234/// U<N>: ArrayLength,
235/// {
236/// let ga = GenericArray::from(value);
237/// // do stuff
238/// ga
239/// }
240/// ```
241pub trait IntoArrayLength {
242 /// The associated `ArrayLength`
243 type ArrayLength: ArrayLength;
244}
245
246impl<const N: usize> IntoArrayLength for Const<N>
247where
248 Const<N>: ToUInt,
249 typenum::U<N>: ArrayLength,
250{
251 type ArrayLength = typenum::U<N>;
252}
253
254impl<N> IntoArrayLength for N
255where
256 N: ArrayLength,
257{
258 type ArrayLength = Self;
259}
260
261/// Associated [`ArrayLength`] for one [`Const<N>`]
262///
263/// See [`IntoArrayLength`] for more information.
264pub type ConstArrayLength<const N: usize> = <Const<N> as IntoArrayLength>::ArrayLength;
265
266/// Internal type used to generate a struct of appropriate size
267#[allow(dead_code)]
268#[repr(C)]
269#[doc(hidden)]
270pub struct GenericArrayImplEven<T, U> {
271 parent1: U,
272 parent2: U,
273 _marker: PhantomData<T>,
274}
275
276/// Internal type used to generate a struct of appropriate size
277#[allow(dead_code)]
278#[repr(C)]
279#[doc(hidden)]
280pub struct GenericArrayImplOdd<T, U> {
281 parent1: U,
282 parent2: U,
283 data: T,
284}
285
286impl<T: Clone, U: Clone> Clone for GenericArrayImplEven<T, U> {
287 #[inline(always)]
288 fn clone(&self) -> GenericArrayImplEven<T, U> {
289 // Clone is never called on the GenericArrayImpl types,
290 // as we use `self.map(clone)` elsewhere. This helps avoid
291 // extra codegen for recursive clones when they are never used.
292 unsafe { core::hint::unreachable_unchecked() }
293 }
294}
295
296impl<T: Clone, U: Clone> Clone for GenericArrayImplOdd<T, U> {
297 #[inline(always)]
298 fn clone(&self) -> GenericArrayImplOdd<T, U> {
299 unsafe { core::hint::unreachable_unchecked() }
300 }
301}
302
303// Even if Clone is never used, they can still be byte-copyable.
304impl<T: Copy, U: Copy> Copy for GenericArrayImplEven<T, U> {}
305impl<T: Copy, U: Copy> Copy for GenericArrayImplOdd<T, U> {}
306
307impl<T, U> Sealed for GenericArrayImplEven<T, U> {}
308impl<T, U> Sealed for GenericArrayImplOdd<T, U> {}
309
310unsafe impl<N: ArrayLength> ArrayLength for UInt<N, B0> {
311 #[doc(hidden)]
312 type ArrayType<T> = GenericArrayImplEven<T, N::ArrayType<T>>;
313}
314
315unsafe impl<N: ArrayLength> ArrayLength for UInt<N, B1> {
316 #[doc(hidden)]
317 type ArrayType<T> = GenericArrayImplOdd<T, N::ArrayType<T>>;
318}
319
320/// Struct representing a generic array - `GenericArray<T, N>` works like `[T; N]`
321///
322/// For how to implement [`Copy`] on structs using a generic-length `GenericArray` internally, see
323/// the docs for [`ArrayLength::ArrayType`].
324///
325/// # Usage Notes
326///
327/// ### Initialization
328///
329/// Initialization of known-length `GenericArray`s can be done via the [`arr![]`](arr!) macro,
330/// or [`from_array`](GenericArray::from_array)/[`from_slice`](GenericArray::from_slice).
331///
332/// For generic arrays of unknown/generic length, several safe methods are included to initialize
333/// them, such as the [`GenericSequence::generate`] method:
334///
335/// ```rust
336/// use generic_array::{GenericArray, sequence::GenericSequence, typenum, arr};
337///
338/// let evens: GenericArray<i32, typenum::U4> =
339/// GenericArray::generate(|i: usize| i as i32 * 2);
340///
341/// assert_eq!(evens, arr![0, 2, 4, 6]);
342/// ```
343///
344/// Furthermore, [`FromIterator`] and [`try_from_iter`](GenericArray::try_from_iter) exist to construct them
345/// from iterators, but will panic/fail if not given exactly the correct number of elements.
346///
347/// ### Utilities
348///
349/// The [`GenericSequence`], [`FunctionalSequence`], [`Lengthen`], [`Shorten`], [`Split`], and [`Concat`] traits implement
350/// some common operations on generic arrays.
351///
352/// ### Optimizations
353///
354/// Prefer to use the slice iterators like `.iter()`/`.iter_mut()` rather than by-value [`IntoIterator`]/[`GenericArrayIter`] if you can.
355/// Slices optimize better. Using the [`FunctionalSequence`] methods also optimize well.
356///
357/// # How it works
358///
359/// The `typenum` crate uses Rust's type system to define binary integers as nested types,
360/// and allows for operations which can be applied to those type-numbers, such as `Add`, `Sub`, etc.
361///
362/// e.g. `6` would be `UInt<UInt<UInt<UTerm, B1>, B1>, B0>`
363///
364/// `generic-array` uses this nested type to recursively allocate contiguous elements, statically.
365/// The [`ArrayLength`] trait is implemented on `UInt<N, B0>`, `UInt<N, B1>` and `UTerm`,
366/// which correspond to even, odd and zero numeric values, respectively.
367/// Together, these three cover all cases of `Unsigned` integers from `typenum`.
368/// For `UInt<N, B0>` and `UInt<N, B1>`, it peels away the highest binary digit and
369/// builds up a recursive structure that looks almost like a binary tree.
370/// Then, within `GenericArray`, the recursive structure is reinterpreted as a contiguous
371/// chunk of memory and allowing access to it as a slice.
372///
373/// <details>
374/// <summary><strong>Expand for internal structure demonstration</strong></summary>
375///
376/// For example, `GenericArray<T, U6>` more or less expands to (at compile time):
377///
378/// ```ignore
379/// GenericArray {
380/// // 6 = UInt<UInt<UInt<UTerm, B1>, B1>, B0>
381/// data: EvenData {
382/// // 3 = UInt<UInt<UTerm, B1>, B1>
383/// left: OddData {
384/// // 1 = UInt<UTerm, B1>
385/// left: OddData {
386/// left: (), // UTerm
387/// right: (), // UTerm
388/// data: T, // Element 0
389/// },
390/// // 1 = UInt<UTerm, B1>
391/// right: OddData {
392/// left: (), // UTerm
393/// right: (), // UTerm
394/// data: T, // Element 1
395/// },
396/// data: T // Element 2
397/// },
398/// // 3 = UInt<UInt<UTerm, B1>, B1>
399/// right: OddData {
400/// // 1 = UInt<UTerm, B1>
401/// left: OddData {
402/// left: (), // UTerm
403/// right: (), // UTerm
404/// data: T, // Element 3
405/// },
406/// // 1 = UInt<UTerm, B1>
407/// right: OddData {
408/// left: (), // UTerm
409/// right: (), // UTerm
410/// data: T, // Element 4
411/// },
412/// data: T // Element 5
413/// }
414/// }
415/// }
416/// ```
417///
418/// This has the added benefit of only being `log2(N)` deep, which is important for things like `Drop`
419/// to avoid stack overflows, since we can't implement `Drop` manually.
420///
421/// Then, we take the contiguous block of data and cast it to `*const T` or `*mut T` and use it as a slice:
422///
423/// ```ignore
424/// unsafe {
425/// slice::from_raw_parts(
426/// self as *const GenericArray<T, N> as *const T,
427/// <N as Unsigned>::USIZE
428/// )
429/// }
430/// ```
431///
432/// </details>
433#[repr(transparent)]
434pub struct GenericArray<T, N: ArrayLength> {
435 #[allow(dead_code)] // data is never accessed directly
436 data: N::ArrayType<T>,
437}
438
439unsafe impl<T: Send, N: ArrayLength> Send for GenericArray<T, N> {}
440unsafe impl<T: Sync, N: ArrayLength> Sync for GenericArray<T, N> {}
441
442impl<T, N: ArrayLength> Deref for GenericArray<T, N> {
443 type Target = [T];
444
445 #[inline(always)]
446 fn deref(&self) -> &[T] {
447 GenericArray::as_slice(self)
448 }
449}
450
451impl<T, N: ArrayLength> DerefMut for GenericArray<T, N> {
452 #[inline(always)]
453 fn deref_mut(&mut self) -> &mut [T] {
454 GenericArray::as_mut_slice(self)
455 }
456}
457
458impl<'a, T: 'a, N: ArrayLength> IntoIterator for &'a GenericArray<T, N> {
459 type IntoIter = slice::Iter<'a, T>;
460 type Item = &'a T;
461
462 fn into_iter(self: &'a GenericArray<T, N>) -> Self::IntoIter {
463 self.as_slice().iter()
464 }
465}
466
467impl<'a, T: 'a, N: ArrayLength> IntoIterator for &'a mut GenericArray<T, N> {
468 type IntoIter = slice::IterMut<'a, T>;
469 type Item = &'a mut T;
470
471 fn into_iter(self: &'a mut GenericArray<T, N>) -> Self::IntoIter {
472 self.as_mut_slice().iter_mut()
473 }
474}
475
476impl<T, N: ArrayLength> FromIterator<T> for GenericArray<T, N> {
477 /// Create a `GenericArray` from an iterator.
478 ///
479 /// Will panic if the number of elements is not exactly the array length.
480 ///
481 /// See [`GenericArray::try_from_iter]` for a fallible alternative.
482 #[inline]
483 fn from_iter<I>(iter: I) -> GenericArray<T, N>
484 where
485 I: IntoIterator<Item = T>,
486 {
487 match Self::try_from_iter(iter) {
488 Ok(res) => res,
489 Err(_) => from_iter_length_fail(N::USIZE),
490 }
491 }
492}
493
494#[inline(never)]
495#[cold]
496pub(crate) fn from_iter_length_fail(length: usize) -> ! {
497 panic!("GenericArray::from_iter expected {length} items");
498}
499
500unsafe impl<T, N: ArrayLength> GenericSequence<T> for GenericArray<T, N>
501where
502 Self: IntoIterator<Item = T>,
503{
504 type Length = N;
505 type Sequence = Self;
506
507 #[inline(always)]
508 fn generate<F>(mut f: F) -> GenericArray<T, N>
509 where
510 F: FnMut(usize) -> T,
511 {
512 unsafe {
513 let mut array = GenericArray::<T, N>::uninit();
514 let mut builder = IntrusiveArrayBuilder::new(&mut array);
515
516 {
517 let (builder_iter, position) = builder.iter_position();
518
519 builder_iter.enumerate().for_each(|(i, dst)| {
520 dst.write(f(i));
521 *position += 1;
522 });
523 }
524
525 builder.finish();
526 IntrusiveArrayBuilder::array_assume_init(array)
527 }
528 }
529
530 #[inline(always)]
531 fn inverted_zip<B, U, F>(
532 self,
533 lhs: GenericArray<B, Self::Length>,
534 mut f: F,
535 ) -> MappedSequence<GenericArray<B, Self::Length>, B, U>
536 where
537 GenericArray<B, Self::Length>:
538 GenericSequence<B, Length = Self::Length> + MappedGenericSequence<B, U>,
539 Self: MappedGenericSequence<T, U>,
540 F: FnMut(B, Self::Item) -> U,
541 {
542 unsafe {
543 if mem::needs_drop::<T>() || mem::needs_drop::<B>() {
544 let mut left = ArrayConsumer::new(lhs);
545 let mut right = ArrayConsumer::new(self);
546
547 let (left_array_iter, left_position) = left.iter_position();
548 let (right_array_iter, right_position) = right.iter_position();
549
550 FromIterator::from_iter(left_array_iter.zip(right_array_iter).map(|(l, r)| {
551 let left_value = ptr::read(l);
552 let right_value = ptr::read(r);
553
554 *left_position += 1;
555 *right_position = *left_position;
556
557 f(left_value, right_value)
558 }))
559 } else {
560 // Despite neither needing `Drop`, they may not be `Copy`, so be paranoid
561 // and avoid anything related to drop anyway. Assume it's moved out on each read.
562 let left = ManuallyDrop::new(lhs);
563 let right = ManuallyDrop::new(self);
564
565 // Neither right nor left require `Drop` be called, so choose an iterator that's easily optimized
566 //
567 // Note that because ArrayConsumer checks for `needs_drop` itself, if `f` panics then nothing
568 // would have been done about it anyway. Only the other branch needs `ArrayConsumer`
569 FromIterator::from_iter(left.iter().zip(right.iter()).map(|(l, r)| {
570 f(ptr::read(l), ptr::read(r)) //
571 }))
572 }
573 }
574 }
575
576 #[inline(always)]
577 fn inverted_zip2<B, Lhs, U, F>(self, lhs: Lhs, mut f: F) -> MappedSequence<Lhs, B, U>
578 where
579 Lhs: GenericSequence<B, Length = Self::Length> + MappedGenericSequence<B, U>,
580 Self: MappedGenericSequence<T, U>,
581 F: FnMut(Lhs::Item, Self::Item) -> U,
582 {
583 unsafe {
584 if mem::needs_drop::<T>() {
585 let mut right = ArrayConsumer::new(self);
586
587 let (right_array_iter, right_position) = right.iter_position();
588
589 FromIterator::from_iter(right_array_iter.zip(lhs).map(|(r, left_value)| {
590 let right_value = ptr::read(r);
591
592 *right_position += 1;
593
594 f(left_value, right_value)
595 }))
596 } else {
597 let right = ManuallyDrop::new(self);
598
599 // Similar logic to `inverted_zip`'s no-drop branch
600 FromIterator::from_iter(right.iter().zip(lhs).map(|(r, left_value)| {
601 f(left_value, ptr::read(r)) //
602 }))
603 }
604 }
605 }
606}
607
608impl<T, U, N: ArrayLength> MappedGenericSequence<T, U> for GenericArray<T, N>
609where
610 GenericArray<U, N>: GenericSequence<U, Length = N>,
611{
612 type Mapped = GenericArray<U, N>;
613}
614
615impl<T, N: ArrayLength> FunctionalSequence<T> for GenericArray<T, N>
616where
617 Self: GenericSequence<T, Item = T, Length = N>,
618{
619 #[inline(always)]
620 fn map<U, F>(self, mut f: F) -> MappedSequence<Self, T, U>
621 where
622 Self: MappedGenericSequence<T, U>,
623 F: FnMut(T) -> U,
624 {
625 unsafe {
626 let mut source = ArrayConsumer::new(self);
627
628 let (array_iter, position) = source.iter_position();
629
630 FromIterator::from_iter(array_iter.map(|src| {
631 let value = ptr::read(src);
632
633 *position += 1;
634
635 f(value)
636 }))
637 }
638 }
639
640 #[inline(always)]
641 fn zip<B, Rhs, U, F>(self, rhs: Rhs, f: F) -> MappedSequence<Self, T, U>
642 where
643 Self: MappedGenericSequence<T, U>,
644 Rhs: MappedGenericSequence<B, U, Mapped = MappedSequence<Self, T, U>>,
645 Rhs: GenericSequence<B, Length = Self::Length>,
646 F: FnMut(T, Rhs::Item) -> U,
647 {
648 rhs.inverted_zip(self, f)
649 }
650
651 #[inline(always)]
652 fn fold<U, F>(self, init: U, mut f: F) -> U
653 where
654 F: FnMut(U, T) -> U,
655 {
656 unsafe {
657 let mut source = ArrayConsumer::new(self);
658
659 let (array_iter, position) = source.iter_position();
660
661 array_iter.fold(init, |acc, src| {
662 let value = ptr::read(src);
663 *position += 1;
664 f(acc, value)
665 })
666 }
667 }
668}
669
670impl<T, N: ArrayLength> GenericArray<T, N> {
671 /// Returns the number of elements in the array.
672 ///
673 /// Equivalent to [`<N as Unsigned>::USIZE`](typenum::Unsigned) where `N` is the array length.
674 ///
675 /// Useful for when only a type alias is available.
676 pub const fn len() -> usize {
677 N::USIZE
678 }
679
680 /// Extracts a slice containing the entire array.
681 #[inline(always)]
682 pub const fn as_slice(&self) -> &[T] {
683 unsafe { slice::from_raw_parts(self as *const Self as *const T, N::USIZE) }
684 }
685
686 /// Extracts a mutable slice containing the entire array.
687 #[inline(always)]
688 pub const fn as_mut_slice(&mut self) -> &mut [T] {
689 unsafe { slice::from_raw_parts_mut(self as *mut Self as *mut T, N::USIZE) }
690 }
691
692 /// Converts a slice to a generic array reference with inferred length.
693 ///
694 /// # Panics
695 ///
696 /// Panics if the slice is not equal to the length of the array.
697 ///
698 /// Consider [`TryFrom`]/[`TryInto`] for a fallible conversion,
699 /// or [`try_from_slice`](GenericArray::try_from_slice) for use in const expressions.
700 #[inline(always)]
701 pub const fn from_slice(slice: &[T]) -> &GenericArray<T, N> {
702 if slice.len() != N::USIZE {
703 panic!("slice.len() != N in GenericArray::from_slice");
704 }
705
706 unsafe { &*(slice.as_ptr() as *const GenericArray<T, N>) }
707 }
708
709 /// Converts a slice to a generic array reference with inferred length.
710 ///
711 /// This is a fallible alternative to [`from_slice`](GenericArray::from_slice), and can be used in const expressions,
712 /// but [`TryFrom`]/[`TryInto`] are also available to do the same thing.
713 #[inline(always)]
714 pub const fn try_from_slice(slice: &[T]) -> Result<&GenericArray<T, N>, LengthError> {
715 if slice.len() != N::USIZE {
716 return Err(LengthError);
717 }
718
719 Ok(unsafe { &*(slice.as_ptr() as *const GenericArray<T, N>) })
720 }
721
722 /// Converts a mutable slice to a mutable generic array reference with inferred length.
723 ///
724 /// # Panics
725 ///
726 /// Panics if the slice is not equal to the length of the array.
727 ///
728 /// Consider [`TryFrom`]/[`TryInto`] for a fallible conversion.
729 #[inline(always)]
730 pub const fn from_mut_slice(slice: &mut [T]) -> &mut GenericArray<T, N> {
731 assert!(
732 slice.len() == N::USIZE,
733 "slice.len() != N in GenericArray::from_mut_slice"
734 );
735
736 unsafe { &mut *(slice.as_mut_ptr() as *mut GenericArray<T, N>) }
737 }
738
739 /// Converts a mutable slice to a mutable generic array reference with inferred length.
740 ///
741 /// This is a fallible alternative to [`from_mut_slice`](GenericArray::from_mut_slice),
742 /// and is equivalent to the [`TryFrom`] implementation with the added benefit of being `const`.
743 #[inline(always)]
744 pub const fn try_from_mut_slice(
745 slice: &mut [T],
746 ) -> Result<&mut GenericArray<T, N>, LengthError> {
747 match slice.len() == N::USIZE {
748 true => Ok(GenericArray::from_mut_slice(slice)),
749 false => Err(LengthError),
750 }
751 }
752
753 /// Converts a slice of `T` elements into a slice of `GenericArray<T, N>` chunks.
754 ///
755 /// Any remaining elements that do not fill the array will be returned as a second slice.
756 ///
757 /// # Panics
758 ///
759 /// Panics if `N` is `U0` _AND_ the input slice is not empty.
760 pub const fn chunks_from_slice(slice: &[T]) -> (&[GenericArray<T, N>], &[T]) {
761 if N::USIZE == 0 {
762 assert!(slice.is_empty(), "GenericArray length N must be non-zero");
763 return (&[], &[]);
764 }
765
766 // NOTE: Using `slice.split_at` adds an unnecessary assert
767 let num_chunks = slice.len() / N::USIZE; // integer division
768 let num_in_chunks = num_chunks * N::USIZE;
769 let num_remainder = slice.len() - num_in_chunks;
770
771 unsafe {
772 (
773 slice::from_raw_parts(slice.as_ptr() as *const GenericArray<T, N>, num_chunks),
774 slice::from_raw_parts(slice.as_ptr().add(num_in_chunks), num_remainder),
775 )
776 }
777 }
778
779 /// Converts a mutable slice of `T` elements into a mutable slice `GenericArray<T, N>` chunks.
780 ///
781 /// Any remaining elements that do not fill the array will be returned as a second slice.
782 ///
783 /// # Panics
784 ///
785 /// Panics if `N` is `U0` _AND_ the input slice is not empty.
786 pub const fn chunks_from_slice_mut(slice: &mut [T]) -> (&mut [GenericArray<T, N>], &mut [T]) {
787 if N::USIZE == 0 {
788 assert!(slice.is_empty(), "GenericArray length N must be non-zero");
789 return (&mut [], &mut []);
790 }
791
792 // NOTE: Using `slice.split_at_mut` adds an unnecessary assert
793 let num_chunks = slice.len() / N::USIZE; // integer division
794 let num_in_chunks = num_chunks * N::USIZE;
795 let num_remainder = slice.len() - num_in_chunks;
796
797 unsafe {
798 (
799 slice::from_raw_parts_mut(
800 slice.as_mut_ptr() as *mut GenericArray<T, N>,
801 num_chunks,
802 ),
803 slice::from_raw_parts_mut(slice.as_mut_ptr().add(num_in_chunks), num_remainder),
804 )
805 }
806 }
807
808 /// Convert a slice of `GenericArray<T, N>` into a slice of `T`, effectively flattening the arrays.
809 #[inline(always)]
810 pub const fn slice_from_chunks(slice: &[GenericArray<T, N>]) -> &[T] {
811 unsafe { slice::from_raw_parts(slice.as_ptr() as *const T, slice.len() * N::USIZE) }
812 }
813
814 /// Convert a slice of `GenericArray<T, N>` into a slice of `T`, effectively flattening the arrays.
815 #[inline(always)]
816 pub const fn slice_from_chunks_mut(slice: &mut [GenericArray<T, N>]) -> &mut [T] {
817 unsafe { slice::from_raw_parts_mut(slice.as_mut_ptr() as *mut T, slice.len() * N::USIZE) }
818 }
819
820 /// Convert a native array into `GenericArray` of the same length and type.
821 ///
822 /// This is the `const` equivalent of using the standard [`From`]/[`Into`] traits methods.
823 #[inline(always)]
824 pub const fn from_array<const U: usize>(value: [T; U]) -> Self
825 where
826 Const<U>: IntoArrayLength<ArrayLength = N>,
827 {
828 unsafe { crate::const_transmute(value) }
829 }
830
831 /// Convert the `GenericArray` into a native array of the same length and type.
832 ///
833 /// This is the `const` equivalent of using the standard [`From`]/[`Into`] traits methods.
834 #[inline(always)]
835 pub const fn into_array<const U: usize>(self) -> [T; U]
836 where
837 Const<U>: IntoArrayLength<ArrayLength = N>,
838 {
839 unsafe { crate::const_transmute(self) }
840 }
841
842 /// Convert a slice of native arrays into a slice of `GenericArray`s.
843 #[inline(always)]
844 pub const fn from_chunks<const U: usize>(chunks: &[[T; U]]) -> &[GenericArray<T, N>]
845 where
846 Const<U>: IntoArrayLength<ArrayLength = N>,
847 {
848 unsafe { mem::transmute(chunks) }
849 }
850
851 /// Convert a mutable slice of native arrays into a mutable slice of `GenericArray`s.
852 #[inline(always)]
853 pub const fn from_chunks_mut<const U: usize>(chunks: &mut [[T; U]]) -> &mut [GenericArray<T, N>]
854 where
855 Const<U>: IntoArrayLength<ArrayLength = N>,
856 {
857 unsafe { mem::transmute(chunks) }
858 }
859
860 /// Converts a slice `GenericArray<T, N>` into a slice of `[T; N]`
861 #[inline(always)]
862 pub const fn into_chunks<const U: usize>(chunks: &[GenericArray<T, N>]) -> &[[T; U]]
863 where
864 Const<U>: IntoArrayLength<ArrayLength = N>,
865 {
866 unsafe { mem::transmute(chunks) }
867 }
868
869 /// Converts a mutable slice `GenericArray<T, N>` into a mutable slice of `[T; N]`
870 #[inline(always)]
871 pub const fn into_chunks_mut<const U: usize>(chunks: &mut [GenericArray<T, N>]) -> &mut [[T; U]]
872 where
873 Const<U>: IntoArrayLength<ArrayLength = N>,
874 {
875 unsafe { mem::transmute(chunks) }
876 }
877}
878
879impl<T, N: ArrayLength> GenericArray<T, N> {
880 /// Create a new array of `MaybeUninit<T>` items, in an uninitialized state.
881 ///
882 /// See [`GenericArray::assume_init`] for a full example.
883 #[inline(always)]
884 #[allow(clippy::uninit_assumed_init)]
885 pub const fn uninit() -> GenericArray<MaybeUninit<T>, N> {
886 unsafe {
887 // SAFETY: An uninitialized `[MaybeUninit<_>; N]` is valid, same as regular array
888 MaybeUninit::<GenericArray<MaybeUninit<T>, N>>::uninit().assume_init()
889 }
890 }
891
892 /// Extracts the values from a generic array of `MaybeUninit` containers.
893 ///
894 /// # Safety
895 ///
896 /// It is up to the caller to guarantee that all elements of the array are in an initialized state.
897 ///
898 /// # Example
899 ///
900 /// ```
901 /// # use core::mem::MaybeUninit;
902 /// # use generic_array::{GenericArray, typenum::U3, arr};
903 /// let mut array: GenericArray<MaybeUninit<i32>, U3> = GenericArray::uninit();
904 /// array[0].write(0);
905 /// array[1].write(1);
906 /// array[2].write(2);
907 ///
908 /// // SAFETY: Now safe as we initialised all elements
909 /// let array = unsafe {
910 /// GenericArray::assume_init(array)
911 /// };
912 ///
913 /// assert_eq!(array, arr![0, 1, 2]);
914 /// ```
915 #[inline(always)]
916 pub const unsafe fn assume_init(array: GenericArray<MaybeUninit<T>, N>) -> Self {
917 const_transmute::<_, MaybeUninit<GenericArray<T, N>>>(array).assume_init()
918 }
919}
920
921/// Error for [`TryFrom`] and [`try_from_iter`](GenericArray::try_from_iter)
922#[derive(Debug, Clone, Copy)]
923pub struct LengthError;
924
925// TODO: Impl core::error::Error when when https://github.com/rust-lang/rust/issues/103765 is finished
926
927impl core::fmt::Display for LengthError {
928 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
929 f.write_str("LengthError: Slice or iterator does not match GenericArray length")
930 }
931}
932
933impl<'a, T, N: ArrayLength> TryFrom<&'a [T]> for &'a GenericArray<T, N> {
934 type Error = LengthError;
935
936 #[inline(always)]
937 fn try_from(slice: &'a [T]) -> Result<Self, Self::Error> {
938 GenericArray::try_from_slice(slice)
939 }
940}
941
942impl<'a, T, N: ArrayLength> TryFrom<&'a mut [T]> for &'a mut GenericArray<T, N> {
943 type Error = LengthError;
944
945 #[inline(always)]
946 fn try_from(slice: &'a mut [T]) -> Result<Self, Self::Error> {
947 GenericArray::try_from_mut_slice(slice)
948 }
949}
950
951impl<T, N: ArrayLength> GenericArray<T, N> {
952 /// Fallible equivalent of [`FromIterator::from_iter`]
953 ///
954 /// Given iterator must yield exactly `N` elements or an error will be returned. Using [`.take(N)`](Iterator::take)
955 /// with an iterator longer than the array may be helpful.
956 #[inline]
957 pub fn try_from_iter<I>(iter: I) -> Result<Self, LengthError>
958 where
959 I: IntoIterator<Item = T>,
960 {
961 let mut iter = iter.into_iter();
962
963 // pre-checks
964 match iter.size_hint() {
965 // if the lower bound is greater than N, array will overflow
966 (n, _) if n > N::USIZE => return Err(LengthError),
967 // if the upper bound is smaller than N, array cannot be filled
968 (_, Some(n)) if n < N::USIZE => return Err(LengthError),
969 _ => {}
970 }
971
972 unsafe {
973 let mut array = GenericArray::uninit();
974 let mut builder = IntrusiveArrayBuilder::new(&mut array);
975
976 builder.extend(&mut iter);
977
978 if !builder.is_full() || iter.next().is_some() {
979 return Err(LengthError);
980 }
981
982 Ok({
983 builder.finish();
984 IntrusiveArrayBuilder::array_assume_init(array)
985 })
986 }
987 }
988}
989
990/// A const reimplementation of the [`transmute`](core::mem::transmute) function,
991/// avoiding problems when the compiler can't prove equal sizes.
992///
993/// # Safety
994/// Treat this the same as [`transmute`](core::mem::transmute), or (preferably) don't use it at all.
995#[inline(always)]
996#[cfg_attr(not(feature = "internals"), doc(hidden))]
997pub const unsafe fn const_transmute<A, B>(a: A) -> B {
998 if mem::size_of::<A>() != mem::size_of::<B>() {
999 panic!("Size mismatch for generic_array::const_transmute");
1000 }
1001
1002 #[repr(C)]
1003 union Union<A, B> {
1004 a: ManuallyDrop<A>,
1005 b: ManuallyDrop<B>,
1006 }
1007
1008 let a = ManuallyDrop::new(a);
1009 ManuallyDrop::into_inner(Union { a }.b)
1010}
1011
1012#[cfg(test)]
1013mod test {
1014 // Compile with:
1015 // cargo rustc --lib --profile test --release --
1016 // -C target-cpu=native -C opt-level=3 --emit asm
1017 // and view the assembly to make sure test_assembly generates
1018 // SIMD instructions instead of a naive loop.
1019
1020 #[inline(never)]
1021 pub fn black_box<T>(val: T) -> T {
1022 use core::{mem, ptr};
1023
1024 let ret = unsafe { ptr::read_volatile(&val) };
1025 mem::forget(val);
1026 ret
1027 }
1028
1029 #[test]
1030 fn test_assembly() {
1031 use crate::functional::*;
1032
1033 let a = black_box(arr![1, 3, 5, 7]);
1034 let b = black_box(arr![2, 4, 6, 8]);
1035
1036 let c = (&a).zip(b, |l, r| l + r);
1037
1038 let d = a.fold(0, |a, x| a + x);
1039
1040 assert_eq!(c, arr![3, 7, 11, 15]);
1041
1042 assert_eq!(d, 16);
1043 }
1044}