libreda-logic 0.0.3

Logic library for LibrEDA.
Documentation
// SPDX-FileCopyrightText: 2022 Thomas Kramer <code@tkramer.ch>
//
// SPDX-License-Identifier: AGPL-3.0-or-later

//! Small crate-internal helper functions.

/// Sort a tuple with 2 values of the same type.
pub fn sort2<T: PartialOrd>([a, b]: [T; 2]) -> [T; 2] {
    if a <= b {
        [a, b]
    } else {
        [b, a]
    }
}

/// Sort a tuple with 3 values of the same type.
pub fn sort3<T>([a, b, c]: [T; 3]) -> [T; 3]
where
    T: Ord,
{
    match [a <= b, b <= c, c <= a] {
        [true, true, false] => [a, b, c],
        [true, false, false] => [a, c, b],
        [false, true, false] => [b, a, c],
        [false, true, true] => [b, c, a],
        [true, false, true] => [c, a, b],
        [false, false, true] => [c, b, a],
        _ => [a, b, c], // All equal.
    }
}

#[test]
fn test_sort3() {
    let unsorted = [
        [1, 2, 3],
        [1, 3, 2],
        [2, 1, 3],
        [2, 3, 1],
        [3, 1, 2],
        [3, 2, 1],
    ];

    unsorted
        .into_iter()
        .for_each(|u| assert_eq!(sort3(u), [1, 2, 3]));

    assert_eq!(sort3([1, 1, 1]), [1, 1, 1]);
    assert_eq!(sort3([2, 1, 1]), [1, 1, 2]);
    assert_eq!(sort3([1, 2, 1]), [1, 1, 2]);
    assert_eq!(sort3([1, 1, 2]), [1, 1, 2]);
}