Skip to main content

connectorx/
data_order.rs

1//! This module provides two data orders: row-wise and column-wise for tabular data,
2//! as well as a function to coordinate the data order between source and destination.
3
4use crate::errors::ConnectorXError;
5use fehler::{throw, throws};
6/// Layout in which a source produces, or a destination consumes, values.
7#[derive(Copy, Clone, Eq, PartialEq, Debug)]
8pub enum DataOrder {
9    /// Values are passed row by row.
10    RowMajor,
11    /// Values are passed column by column.
12    ColumnMajor,
13}
14
15/// Given the supported data order from source and destination, decide the optimal data order
16/// for producing and writing.
17#[throws(ConnectorXError)]
18pub fn coordinate(src: &[DataOrder], dst: &[DataOrder]) -> DataOrder {
19    assert!(!src.is_empty() && !dst.is_empty());
20
21    match (src, dst) {
22        ([s, ..], [d, ..]) if s == d => *s,
23        ([s, ..], [_, d, ..]) if s == d => *s,
24        ([_, s, ..], [d, ..]) if s == d => *s,
25        _ => throw!(ConnectorXError::CannotResolveDataOrder(
26            src.to_vec(),
27            dst.to_vec()
28        )),
29    }
30}
31
32#[cfg(test)]
33mod tests {
34    use super::{coordinate, DataOrder};
35
36    #[test]
37    fn selects_matching_first_supported_order() {
38        assert!(matches!(
39            coordinate(&[DataOrder::RowMajor], &[DataOrder::RowMajor]),
40            Ok(DataOrder::RowMajor)
41        ));
42    }
43
44    #[test]
45    fn selects_matching_secondary_supported_order() {
46        assert!(matches!(
47            coordinate(
48                &[DataOrder::RowMajor, DataOrder::ColumnMajor],
49                &[DataOrder::ColumnMajor],
50            ),
51            Ok(DataOrder::ColumnMajor)
52        ));
53        assert!(matches!(
54            coordinate(
55                &[DataOrder::ColumnMajor],
56                &[DataOrder::RowMajor, DataOrder::ColumnMajor],
57            ),
58            Ok(DataOrder::ColumnMajor)
59        ));
60    }
61
62    #[test]
63    fn reports_when_orders_cannot_be_resolved() {
64        assert!(coordinate(&[DataOrder::RowMajor], &[DataOrder::ColumnMajor]).is_err());
65    }
66}