Skip to main content

array_trait/
lib.rs

1#![cfg_attr(not(test), no_std)]
2#![feature(const_trait_impl)]
3#![feature(trait_alias)]
4#![feature(const_convert)]
5#![feature(const_index)]
6#![feature(ptr_metadata)]
7#![feature(generic_const_exprs)]
8
9//! A trait for any array, with item as an associated type, and length as an assiciated constant.
10//!
11//! This crate is a subset of the crate [`array_ops`](https://crates.io/crates/array_ops).
12//!
13//! # Examples
14//!
15//! ```rust
16//! use array_trait::*;
17//!
18//! type Arr3 = [i8; 3];
19//!
20//! const A: Arr3 = [1, 2, 3];
21//!
22//! // The assiciated constant `LENGTH` equals the length of the array
23//! assert_eq!(Arr3::LENGTH, 3);
24//! assert_eq!(Arr3::LENGTH, A.len());
25//! ```
26//!
27//! ```rust
28//! #![feature(const_trait_impl)]
29//! #![feature(generic_const_exprs)]
30//!
31//! use array_trait::*;
32//!
33//! type Arr3 = [i8; 3];
34//!
35//! const A: Arr3 = [1, 2, 3];
36//!
37//! /// The trait can be used in a function like this:
38//! const fn first<'a, T: ~const Array>(array: &'a T) -> Option<&'a <T as AsSlice>::Elem>
39//! where
40//!     [(); T::LENGTH]: // This is required for now.
41//! {
42//!     array.as_array().first()
43//! }
44//! assert_eq!(first(&A), Some(&1));
45//! ```
46//!
47//! # N-dimensional arrays
48//!
49//! There is also a trait for N-dimensional arrays, which contain information on its inner structure, and supports a depth up to 64 dimensions.
50//!
51//! The associated constants [DIMENSIONS](ArrayNd::DIMENSIONS) and [FLAT_LENGTH](ArrayNd::FLAT_LENGTH) vary depending on the chosen depth.
52//!
53//!  The assiciated type [ItemNd](ArrayNd::ItemNd) represents the innermost type given a chosen depth.
54//!
55//! # Examples
56//!
57//! ```rust
58//! #![feature(generic_const_exprs)]
59//!
60//! use array_trait::*;
61//!
62//! type Mat2x3 = [[i8; 3]; 2];
63//!
64//! /// The number of dimensions
65//! const DEPTH: usize = 2;
66//!
67//! // `FLAT_LENGTH` is the combined length if the N-dimensional array was flattened,
68//! // i.e. the product of the lengths of each dimension.
69//! assert_eq!(<Mat2x3 as ArrayNd<DEPTH>>::FLAT_LENGTH, 6);
70//!
71//! // `DIMENSIONS` contains the lengths of each dimension ordered outermost to innermost.
72//! assert_eq!(<Mat2x3 as ArrayNd<DEPTH>>::DIMENSIONS, [2, 3]);
73//! ```
74
75moddef::moddef!(
76    flat(pub) mod {
77        array,
78        array_nd,
79        into_array,
80        as_array
81    }
82);
83
84#[cfg(feature = "alloc")]
85extern crate alloc;
86
87pub use slice_trait::*;
88
89mod private
90{
91    use crate::AsArray;
92
93    pub trait Array: AsArray {}
94    impl<Item, const LENGTH: usize> Array for [Item; LENGTH] {}
95}
96
97#[cfg(test)]
98mod test
99{
100    #[test]
101    fn test() {}
102}