use core::cmp::Ordering;
#[derive(Debug, Clone, Copy)]
pub(super) struct VertexEntry {
pub(super) key: f64,
pub(super) cost: f64,
pub(super) vertex: usize,
}
#[derive(Debug, Clone, Copy)]
pub(super) struct EdgeEntry {
pub(super) key: [f64; 3],
pub(super) from: usize,
pub(super) to: usize,
}
impl VertexEntry {
fn order(&self, other: &Self) -> Ordering {
self.key
.total_cmp(&other.key)
.then_with(|| self.cost.total_cmp(&other.cost))
.then_with(|| self.vertex.cmp(&other.vertex))
}
}
impl EdgeEntry {
fn order(&self, other: &Self) -> Ordering {
self.key[0]
.total_cmp(&other.key[0])
.then_with(|| self.key[1].total_cmp(&other.key[1]))
.then_with(|| self.key[2].total_cmp(&other.key[2]))
.then_with(|| (self.from, self.to).cmp(&(other.from, other.to)))
}
}
macro_rules! reversed_order {
($entry:ty) => {
impl PartialEq for $entry {
fn eq(&self, other: &Self) -> bool {
self.order(other) == Ordering::Equal
}
}
impl Eq for $entry {}
impl PartialOrd for $entry {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for $entry {
fn cmp(&self, other: &Self) -> Ordering {
other.order(self)
}
}
};
}
reversed_order!(VertexEntry);
reversed_order!(EdgeEntry);
#[cfg(test)]
mod tests {
use super::*;
use alloc::collections::BinaryHeap;
#[test]
fn heaps_pop_the_best_entry_with_documented_tie_breaks() {
let edge = |key, from| EdgeEntry { key, from, to: 9 };
let mut edges = BinaryHeap::from([
edge([2.0, 1.0, 0.5], 0),
edge([1.0, 0.9, 0.5], 1),
edge([1.0, 0.8, 0.7], 2),
]);
assert_eq!(edges.pop().map(|e| e.from), Some(2));
assert_eq!(edges.pop().map(|e| e.from), Some(1));
let vertex = |key, cost, vertex| VertexEntry { key, cost, vertex };
let mut vertices = BinaryHeap::from([vertex(1.0, 0.5, 3), vertex(1.0, 0.5, 1)]);
assert_eq!(vertices.pop().map(|v| v.vertex), Some(1));
}
}