use core::ops::Add;
use super::Cost;
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Lexicographic<P, S> {
pub primary: P,
pub secondary: S,
}
impl<P, S> Lexicographic<P, S> {
#[must_use]
pub const fn new(primary: P, secondary: S) -> Self {
Self { primary, secondary }
}
}
impl<P: Add<Output = P>, S: Add<Output = S>> Add for Lexicographic<P, S> {
type Output = Self;
fn add(self, other: Self) -> Self {
Self::new(
self.primary + other.primary,
self.secondary + other.secondary,
)
}
}
impl<P: Cost, S: Cost> Cost for Lexicographic<P, S> {
const ZERO: Self = Self::new(P::ZERO, S::ZERO);
fn saturating_add(self, other: Self) -> Self {
Self::new(
self.primary.saturating_add(other.primary),
self.secondary.saturating_add(other.secondary),
)
}
fn saturating_times(self, factor: u32) -> Self {
Self::new(
self.primary.saturating_times(factor),
self.secondary.saturating_times(factor),
)
}
}
#[cfg(test)]
mod tests {
use proptest::prelude::*;
use super::{Cost, Lexicographic};
use crate::Decimal;
fn cost(primary: u32, secondary: u32) -> Lexicographic<u32, u32> {
Lexicographic::new(primary, secondary)
}
#[test]
fn orders_lexicographically() {
assert!(cost(1, 9) < cost(2, 0));
assert!(cost(2, 0) < cost(2, 1));
assert_eq!(cost(3, 3).max(cost(3, 4)), cost(3, 4));
}
#[test]
fn saturates_per_component() {
assert_eq!(
cost(u32::MAX, 1).saturating_add(cost(1, 1)),
cost(u32::MAX, 2)
);
assert_eq!(cost(u32::MAX, 2).saturating_times(2), cost(u32::MAX, 4));
assert_eq!(cost(5, 7).saturating_times(0), Lexicographic::ZERO);
}
#[test]
fn mixes_cost_types() {
let a = Lexicographic::new(Decimal::<2>::from_raw(150), 1_u8);
let b = Lexicographic::new(Decimal::<2>::from_raw(150), 0_u8);
assert!(b < a);
assert_eq!((a + b).primary, Decimal::from_raw(300));
}
proptest! {
#[test]
fn matches_tuple_order(a: (u32, u32), b: (u32, u32)) {
prop_assert_eq!(cost(a.0, a.1).cmp(&cost(b.0, b.1)), a.cmp(&b));
}
#[test]
fn zero_secondary_heuristic_stays_consistent(
h_u in 0..1_000_u32, c in 0..1_000_u32, h_v in 0..1_000_u32, s: u16,
) {
prop_assume!(h_u <= c + h_v);
prop_assert!(cost(h_u, 0) <= cost(c, u32::from(s)) + cost(h_v, 0));
}
}
}