orx_funvec/index.rs
1/// A convenience trait to allow accepting and interchangeably using indices as arrays or tuples.
2///
3/// A struct implementing `IntoIndex<DIM>` can be converted into and index represented as `[usize; DIM]`, such as:
4///
5/// * `usize`, `(usize)`, `[usize; 1]` implement `IntoIndex<1>`, and hence, can be converted into `[usize; 1]`;
6/// * `(usize, usize)`, `[usize; 2]` implement `IntoIndex<2>`, and hence, can be converted into `[usize; 2]`;
7/// * ...
8pub trait IntoIndex<const DIM: usize> {
9 /// Converts the value into an index represented as `[usize; DIM]`.
10 ///
11 /// # Example
12 ///
13 /// ```rust
14 /// use orx_funvec::*;
15 ///
16 /// let i = 2;
17 /// let index = i.into_index();
18 /// assert_eq!(index, [2]);
19 ///
20 /// let ij = (3, 4);
21 /// let index = ij.into_index();
22 /// assert_eq!(index, [3, 4]);
23 /// ```
24 fn into_index(self) -> [usize; DIM];
25}
26impl<const DIM: usize> IntoIndex<DIM> for [usize; DIM] {
27 fn into_index(self) -> [usize; DIM] {
28 self
29 }
30}
31
32/// A convenience trait to allow extending `FunVec` implementations.
33///
34/// A struct implementing `FromIndex<DIM>` can be created from `[usize; DIM]`, such as:
35///
36/// * `usize`, `(usize)`, `[usize; 1]` implement `FromIndex<1>`, and hence, can be created from `[usize; 1]`;
37/// * `(usize, usize)`, `[usize; 2]` implement `FromIndex<2>`, and hence, can be created from `[usize; 2]`;
38/// * ...
39pub trait FromIndex<const DIM: usize> {
40 /// Converts the index `[usize; DIM]` into value.
41 ///
42 /// # Example
43 ///
44 /// ```rust
45 /// use orx_funvec::*;
46 ///
47 /// let index = [2];
48 /// let i = usize::from_index(index);
49 /// assert_eq!(i, 2);
50 ///
51 /// let index = [3, 4];
52 /// let (i, j) = <(usize, usize)>::from_index(index);
53 /// assert_eq!(i, 3);
54 /// assert_eq!(j, 4);
55 /// ```
56 fn from_index(index: [usize; DIM]) -> Self;
57}
58impl<const DIM: usize> FromIndex<DIM> for [usize; DIM] {
59 fn from_index(index: [usize; DIM]) -> Self {
60 index
61 }
62}