//! This crate implements a structure that can be used as a generic array type. //! Core Rust array types `[T; N]` can't be used generically with //! respect to `N`, so for example this: //! //! ```rust{compile_fail} //! struct Foo { //! data: [T; N] //! } //! ``` //! //! won't work. //! //! **generic-array** exports a `GenericArray` type, which lets //! the above be implemented as: //! //! ```rust //! use generic_array::{ArrayLength, GenericArray}; //! //! struct Foo> { //! data: GenericArray //! } //! ``` //! //! The `ArrayLength` trait is implemented by default for //! [unsigned integer types](../typenum/uint/index.html) from //! [typenum](../typenum/index.html): //! //! ```rust //! # use generic_array::{ArrayLength, GenericArray}; //! use generic_array::typenum::U5; //! //! struct Foo> { //! data: GenericArray //! } //! //! # fn main() { //! let foo = Foo::{data: GenericArray::default()}; //! # } //! ``` //! //! For example, `GenericArray` would work almost like `[T; 5]`: //! //! ```rust //! # use generic_array::{ArrayLength, GenericArray}; //! use generic_array::typenum::U5; //! //! struct Foo> { //! data: GenericArray //! } //! //! # fn main() { //! let foo = Foo::{data: GenericArray::default()}; //! # } //! ``` //! //! For ease of use, an `arr!` macro is provided - example below: //! //! ``` //! # #[macro_use] //! # extern crate generic_array; //! # extern crate typenum; //! # fn main() { //! let array = arr![u32; 1, 2, 3]; //! assert_eq!(array[2], 3); //! # } //! ``` #![deny(missing_docs)] #![deny(meta_variable_misuse)] #![no_std] #[cfg(feature = "serde")] extern crate serde; #[cfg(feature = "zeroize")] extern crate zeroize; #[cfg(test)] extern crate bincode; pub extern crate typenum; mod hex; mod impls; #[cfg(feature = "serde")] mod impl_serde; #[cfg(feature = "zeroize")] mod impl_zeroize; use core::iter::FromIterator; use core::marker::PhantomData; use core::mem::{MaybeUninit, ManuallyDrop}; use core::ops::{Deref, DerefMut}; use core::{mem, ptr, slice}; use typenum::bit::{B0, B1}; use typenum::uint::{UInt, UTerm, Unsigned}; #[cfg_attr(test, macro_use)] pub mod arr; pub mod functional; pub mod iter; pub mod sequence; use self::functional::*; pub use self::iter::GenericArrayIter; use self::sequence::*; /// Trait making `GenericArray` work, marking types to be used as length of an array pub unsafe trait ArrayLength: Unsigned { /// Associated type representing the array type for the number type ArrayType; } unsafe impl ArrayLength for UTerm { #[doc(hidden)] type ArrayType = [T; 0]; } /// Internal type used to generate a struct of appropriate size #[allow(dead_code)] #[repr(C)] #[doc(hidden)] pub struct GenericArrayImplEven { parent1: U, parent2: U, _marker: PhantomData, } impl Clone for GenericArrayImplEven { fn clone(&self) -> GenericArrayImplEven { GenericArrayImplEven { parent1: self.parent1.clone(), parent2: self.parent2.clone(), _marker: PhantomData, } } } impl Copy for GenericArrayImplEven {} /// Internal type used to generate a struct of appropriate size #[allow(dead_code)] #[repr(C)] #[doc(hidden)] pub struct GenericArrayImplOdd { parent1: U, parent2: U, data: T, } impl Clone for GenericArrayImplOdd { fn clone(&self) -> GenericArrayImplOdd { GenericArrayImplOdd { parent1: self.parent1.clone(), parent2: self.parent2.clone(), data: self.data.clone(), } } } impl Copy for GenericArrayImplOdd {} unsafe impl> ArrayLength for UInt { #[doc(hidden)] type ArrayType = GenericArrayImplEven; } unsafe impl> ArrayLength for UInt { #[doc(hidden)] type ArrayType = GenericArrayImplOdd; } /// Struct representing a generic array - `GenericArray` works like [T; N] #[allow(dead_code)] #[repr(transparent)] pub struct GenericArray> { data: U::ArrayType, } unsafe impl> Send for GenericArray {} unsafe impl> Sync for GenericArray {} impl Deref for GenericArray where N: ArrayLength, { type Target = [T]; #[inline(always)] fn deref(&self) -> &[T] { unsafe { slice::from_raw_parts(self as *const Self as *const T, N::USIZE) } } } impl DerefMut for GenericArray where N: ArrayLength, { #[inline(always)] fn deref_mut(&mut self) -> &mut [T] { unsafe { slice::from_raw_parts_mut(self as *mut Self as *mut T, N::USIZE) } } } /// Creates an array one element at a time using a mutable iterator /// you can write to with `ptr::write`. /// /// Increment the position while iterating to mark off created elements, /// which will be dropped if `into_inner` is not called. #[doc(hidden)] pub struct ArrayBuilder> { array: MaybeUninit>, position: usize, } impl> ArrayBuilder { #[doc(hidden)] #[inline] pub unsafe fn new() -> ArrayBuilder { ArrayBuilder { array: MaybeUninit::uninit(), position: 0, } } /// Creates a mutable iterator for writing to the array using `ptr::write`. /// /// Increment the position value given as a mutable reference as you iterate /// to mark how many elements have been created. #[doc(hidden)] #[inline] pub unsafe fn iter_position(&mut self) -> (slice::IterMut, &mut usize) { ((&mut *self.array.as_mut_ptr()).iter_mut(), &mut self.position) } /// When done writing (assuming all elements have been written to), /// get the inner array. #[doc(hidden)] #[inline] pub unsafe fn into_inner(self) -> GenericArray { let array = ptr::read(&self.array); mem::forget(self); array.assume_init() } } impl> Drop for ArrayBuilder { fn drop(&mut self) { if mem::needs_drop::() { unsafe { for value in &mut (&mut *self.array.as_mut_ptr())[..self.position] { ptr::drop_in_place(value); } } } } } /// Consumes an array. /// /// Increment the position while iterating and any leftover elements /// will be dropped if position does not go to N #[doc(hidden)] pub struct ArrayConsumer> { array: ManuallyDrop>, position: usize, } impl> ArrayConsumer { #[doc(hidden)] #[inline] pub unsafe fn new(array: GenericArray) -> ArrayConsumer { ArrayConsumer { array: ManuallyDrop::new(array), position: 0, } } /// Creates an iterator and mutable reference to the internal position /// to keep track of consumed elements. /// /// Increment the position as you iterate to mark off consumed elements #[doc(hidden)] #[inline] pub unsafe fn iter_position(&mut self) -> (slice::Iter, &mut usize) { (self.array.iter(), &mut self.position) } } impl> Drop for ArrayConsumer { fn drop(&mut self) { if mem::needs_drop::() { for value in &mut self.array[self.position..N::USIZE] { unsafe { ptr::drop_in_place(value); } } } } } impl<'a, T: 'a, N> IntoIterator for &'a GenericArray where N: ArrayLength, { type IntoIter = slice::Iter<'a, T>; type Item = &'a T; fn into_iter(self: &'a GenericArray) -> Self::IntoIter { self.as_slice().iter() } } impl<'a, T: 'a, N> IntoIterator for &'a mut GenericArray where N: ArrayLength, { type IntoIter = slice::IterMut<'a, T>; type Item = &'a mut T; fn into_iter(self: &'a mut GenericArray) -> Self::IntoIter { self.as_mut_slice().iter_mut() } } impl FromIterator for GenericArray where N: ArrayLength, { fn from_iter(iter: I) -> GenericArray where I: IntoIterator, { unsafe { let mut destination = ArrayBuilder::new(); { let (destination_iter, position) = destination.iter_position(); iter.into_iter() .zip(destination_iter) .for_each(|(src, dst)| { ptr::write(dst, src); *position += 1; }); } if destination.position < N::USIZE { from_iter_length_fail(destination.position, N::USIZE); } destination.into_inner() } } } #[inline(never)] #[cold] fn from_iter_length_fail(length: usize, expected: usize) -> ! { panic!( "GenericArray::from_iter received {} elements but expected {}", length, expected ); } unsafe impl GenericSequence for GenericArray where N: ArrayLength, Self: IntoIterator, { type Length = N; type Sequence = Self; fn generate(mut f: F) -> GenericArray where F: FnMut(usize) -> T, { unsafe { let mut destination = ArrayBuilder::new(); { let (destination_iter, position) = destination.iter_position(); destination_iter.enumerate().for_each(|(i, dst)| { ptr::write(dst, f(i)); *position += 1; }); } destination.into_inner() } } #[doc(hidden)] fn inverted_zip( self, lhs: GenericArray, mut f: F, ) -> MappedSequence, B, U> where GenericArray: GenericSequence + MappedGenericSequence, Self: MappedGenericSequence, Self::Length: ArrayLength + ArrayLength, F: FnMut(B, Self::Item) -> U, { unsafe { let mut left = ArrayConsumer::new(lhs); let mut right = ArrayConsumer::new(self); let (left_array_iter, left_position) = left.iter_position(); let (right_array_iter, right_position) = right.iter_position(); FromIterator::from_iter(left_array_iter.zip(right_array_iter).map(|(l, r)| { let left_value = ptr::read(l); let right_value = ptr::read(r); *left_position += 1; *right_position += 1; f(left_value, right_value) })) } } #[doc(hidden)] fn inverted_zip2(self, lhs: Lhs, mut f: F) -> MappedSequence where Lhs: GenericSequence + MappedGenericSequence, Self: MappedGenericSequence, Self::Length: ArrayLength + ArrayLength, F: FnMut(Lhs::Item, Self::Item) -> U, { unsafe { let mut right = ArrayConsumer::new(self); let (right_array_iter, right_position) = right.iter_position(); FromIterator::from_iter( lhs.into_iter() .zip(right_array_iter) .map(|(left_value, r)| { let right_value = ptr::read(r); *right_position += 1; f(left_value, right_value) }), ) } } } unsafe impl MappedGenericSequence for GenericArray where N: ArrayLength + ArrayLength, GenericArray: GenericSequence, { type Mapped = GenericArray; } unsafe impl FunctionalSequence for GenericArray where N: ArrayLength, Self: GenericSequence, { fn map(self, mut f: F) -> MappedSequence where Self::Length: ArrayLength, Self: MappedGenericSequence, F: FnMut(T) -> U, { unsafe { let mut source = ArrayConsumer::new(self); let (array_iter, position) = source.iter_position(); FromIterator::from_iter(array_iter.map(|src| { let value = ptr::read(src); *position += 1; f(value) })) } } #[inline] fn zip(self, rhs: Rhs, f: F) -> MappedSequence where Self: MappedGenericSequence, Rhs: MappedGenericSequence>, Self::Length: ArrayLength + ArrayLength, Rhs: GenericSequence, F: FnMut(T, Rhs::Item) -> U, { rhs.inverted_zip(self, f) } fn fold(self, init: U, mut f: F) -> U where F: FnMut(U, T) -> U, { unsafe { let mut source = ArrayConsumer::new(self); let (array_iter, position) = source.iter_position(); array_iter.fold(init, |acc, src| { let value = ptr::read(src); *position += 1; f(acc, value) }) } } } impl GenericArray where N: ArrayLength, { /// Extracts a slice containing the entire array. #[inline] pub fn as_slice(&self) -> &[T] { self.deref() } /// Extracts a mutable slice containing the entire array. #[inline] pub fn as_mut_slice(&mut self) -> &mut [T] { self.deref_mut() } /// Converts slice to a generic array reference with inferred length; /// /// Length of the slice must be equal to the length of the array. #[inline] pub fn from_slice(slice: &[T]) -> &GenericArray { slice.into() } /// Converts mutable slice to a mutable generic array reference /// /// Length of the slice must be equal to the length of the array. #[inline] pub fn from_mut_slice(slice: &mut [T]) -> &mut GenericArray { slice.into() } } impl<'a, T, N: ArrayLength> From<&'a [T]> for &'a GenericArray { /// Converts slice to a generic array reference with inferred length; /// /// Length of the slice must be equal to the length of the array. #[inline] fn from(slice: &[T]) -> &GenericArray { assert_eq!(slice.len(), N::USIZE); unsafe { &*(slice.as_ptr() as *const GenericArray) } } } impl<'a, T, N: ArrayLength> From<&'a mut [T]> for &'a mut GenericArray { /// Converts mutable slice to a mutable generic array reference /// /// Length of the slice must be equal to the length of the array. #[inline] fn from(slice: &mut [T]) -> &mut GenericArray { assert_eq!(slice.len(), N::USIZE); unsafe { &mut *(slice.as_mut_ptr() as *mut GenericArray) } } } impl GenericArray where N: ArrayLength, { /// Construct a `GenericArray` from a slice by cloning its content /// /// Length of the slice must be equal to the length of the array #[inline] pub fn clone_from_slice(list: &[T]) -> GenericArray { Self::from_exact_iter(list.iter().cloned()) .expect("Slice must be the same length as the array") } } impl GenericArray where N: ArrayLength, { /// Creates a new `GenericArray` instance from an iterator with a specific size. /// /// Returns `None` if the size is not equal to the number of elements in the `GenericArray`. pub fn from_exact_iter(iter: I) -> Option where I: IntoIterator, { let mut iter = iter.into_iter(); unsafe { let mut destination = ArrayBuilder::new(); { let (destination_iter, position) = destination.iter_position(); destination_iter.zip(&mut iter).for_each(|(dst, src)| { ptr::write(dst, src); *position += 1; }); // The iterator produced fewer than `N` elements. if *position != N::USIZE { return None; } // The iterator produced more than `N` elements. if iter.next().is_some() { return None; } } Some(destination.into_inner()) } } } /// A reimplementation of the `transmute` function, avoiding problems /// when the compiler can't prove equal sizes. #[inline] #[doc(hidden)] pub unsafe fn transmute(a: A) -> B { let a = ManuallyDrop::new(a); ::core::ptr::read(&*a as *const A as *const B) } #[cfg(test)] mod test { // Compile with: // cargo rustc --lib --profile test --release -- // -C target-cpu=native -C opt-level=3 --emit asm // and view the assembly to make sure test_assembly generates // SIMD instructions instead of a naive loop. #[inline(never)] pub fn black_box(val: T) -> T { use core::{mem, ptr}; let ret = unsafe { ptr::read_volatile(&val) }; mem::forget(val); ret } #[test] fn test_assembly() { use crate::functional::*; let a = black_box(arr![i32; 1, 3, 5, 7]); let b = black_box(arr![i32; 2, 4, 6, 8]); let c = (&a).zip(b, |l, r| l + r); let d = a.fold(0, |a, x| a + x); assert_eq!(c, arr![i32; 3, 7, 11, 15]); assert_eq!(d, 16); } }