libreda_logic/
helpers.rs

1// SPDX-FileCopyrightText: 2022 Thomas Kramer <code@tkramer.ch>
2//
3// SPDX-License-Identifier: AGPL-3.0-or-later
4
5//! Small crate-internal helper functions.
6
7/// Sort a tuple with 2 values of the same type.
8pub fn sort2<T: PartialOrd>([a, b]: [T; 2]) -> [T; 2] {
9    if a <= b {
10        [a, b]
11    } else {
12        [b, a]
13    }
14}
15
16/// Sort a tuple with 3 values of the same type.
17pub fn sort3<T>([a, b, c]: [T; 3]) -> [T; 3]
18where
19    T: Ord,
20{
21    match [a <= b, b <= c, c <= a] {
22        [true, true, false] => [a, b, c],
23        [true, false, false] => [a, c, b],
24        [false, true, false] => [b, a, c],
25        [false, true, true] => [b, c, a],
26        [true, false, true] => [c, a, b],
27        [false, false, true] => [c, b, a],
28        _ => [a, b, c], // All equal.
29    }
30}
31
32#[test]
33fn test_sort3() {
34    let unsorted = [
35        [1, 2, 3],
36        [1, 3, 2],
37        [2, 1, 3],
38        [2, 3, 1],
39        [3, 1, 2],
40        [3, 2, 1],
41    ];
42
43    unsorted
44        .into_iter()
45        .for_each(|u| assert_eq!(sort3(u), [1, 2, 3]));
46
47    assert_eq!(sort3([1, 1, 1]), [1, 1, 1]);
48    assert_eq!(sort3([2, 1, 1]), [1, 1, 2]);
49    assert_eq!(sort3([1, 2, 1]), [1, 1, 2]);
50    assert_eq!(sort3([1, 1, 2]), [1, 1, 2]);
51}