ndarray/
order.rs

1/// Array order
2///
3/// Order refers to indexing order, or how a linear sequence is translated
4/// into a two-dimensional or multi-dimensional array.
5///
6/// - `RowMajor` means that the index along the row is the most rapidly changing
7/// - `ColumnMajor` means that the index along the column is the most rapidly changing
8///
9/// Given a sequence like: 1, 2, 3, 4, 5, 6
10///
11/// If it is laid it out in a 2 x 3 matrix using row major ordering, it results in:
12///
13/// ```text
14/// 1  2  3
15/// 4  5  6
16/// ```
17///
18/// If it is laid using column major ordering, it results in:
19///
20/// ```text
21/// 1  3  5
22/// 2  4  6
23/// ```
24///
25/// It can be seen as filling in "rows first" or "columns first".
26///
27/// `Order` can be used both to refer to logical ordering as well as memory ordering or memory
28/// layout. The orderings have common short names, also seen in other environments, where
29/// row major is called "C" order (after the C programming language) and column major is called "F"
30/// or "Fortran" order.
31#[derive(Copy, Clone, Debug, PartialEq, Eq)]
32#[non_exhaustive]
33pub enum Order
34{
35    /// Row major or "C" order
36    RowMajor,
37    /// Column major or "F" order
38    ColumnMajor,
39}
40
41impl Order
42{
43    /// "C" is an alias for row major ordering
44    pub const C: Order = Order::RowMajor;
45
46    /// "F" (for Fortran) is an alias for column major ordering
47    pub const F: Order = Order::ColumnMajor;
48
49    /// Return true if input is Order::RowMajor, false otherwise
50    #[inline]
51    pub fn is_row_major(self) -> bool
52    {
53        match self {
54            Order::RowMajor => true,
55            Order::ColumnMajor => false,
56        }
57    }
58
59    /// Return true if input is Order::ColumnMajor, false otherwise
60    #[inline]
61    pub fn is_column_major(self) -> bool
62    {
63        !self.is_row_major()
64    }
65
66    /// Return Order::RowMajor if the input is true, Order::ColumnMajor otherwise
67    #[inline]
68    pub fn row_major(row_major: bool) -> Order
69    {
70        if row_major {
71            Order::RowMajor
72        } else {
73            Order::ColumnMajor
74        }
75    }
76
77    /// Return Order::ColumnMajor if the input is true, Order::RowMajor otherwise
78    #[inline]
79    pub fn column_major(column_major: bool) -> Order
80    {
81        Self::row_major(!column_major)
82    }
83
84    /// Return the transpose: row major becomes column major and vice versa.
85    #[inline]
86    pub fn transpose(self) -> Order
87    {
88        match self {
89            Order::RowMajor => Order::ColumnMajor,
90            Order::ColumnMajor => Order::RowMajor,
91        }
92    }
93}