mod indexed;
mod tree;
mod truncated;
use alloc::vec::Vec;
use search_core::Cost;
use crate::cost::weakly_dominates;
pub use indexed::{FrontIndex, IndexedFront};
pub use tree::TreeFront;
pub(crate) use truncated::{TruncatedFront, TruncatedTree};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Front<C, const N: usize> {
points: Vec<[C; N]>,
}
pub type BiFront<C> = Front<C, 2>;
impl<C, const N: usize> Default for Front<C, N> {
fn default() -> Self {
Self { points: Vec::new() }
}
}
impl<C: Cost, const N: usize> Front<C, N> {
#[must_use]
pub const fn new() -> Self {
Self { points: Vec::new() }
}
#[must_use]
pub fn weakly_dominates(&self, point: &[C; N]) -> bool {
let candidates = &self.points[..self.points.partition_point(|q| q <= point)];
if N <= 2 {
candidates
.last()
.is_some_and(|q| weakly_dominates(q, point))
} else {
candidates.iter().any(|q| weakly_dominates(q, point))
}
}
pub fn insert(&mut self, point: [C; N]) -> bool {
if self.weakly_dominates(&point) {
return false;
}
let start = self.points.partition_point(|q| q < &point);
if N <= 2 {
let dominated = self.points[start..].partition_point(|q| weakly_dominates(&point, q));
self.points.splice(start..start + dominated, [point]);
} else {
self.points.insert(start, point);
let mut index = 0;
self.points.retain(|q| {
let keep = index <= start || !weakly_dominates(&point, q);
index += 1;
keep
});
}
true
}
#[must_use]
pub fn len(&self) -> usize {
self.points.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.points.is_empty()
}
#[must_use]
pub fn as_slice(&self) -> &[[C; N]] {
&self.points
}
}
#[cfg(test)]
mod tests {
use super::{BiFront, Front};
#[test]
fn rejects_equal_point() {
let mut front = BiFront::new();
assert!(front.insert([2_u8, 2]));
assert!(!front.insert([2, 2]));
assert_eq!(front.len(), 1);
}
#[test]
fn replaces_point_with_equal_first_cost() {
let mut front = BiFront::new();
assert!(front.insert([1_u8, 5]));
assert!(front.insert([3, 3]));
assert!(front.insert([3, 2]));
assert_eq!(front.as_slice(), &[[1, 5], [3, 2]]);
}
#[test]
fn removes_only_dominated_run() {
let mut front = BiFront::new();
for p in [[0_u8, 9], [2, 7], [4, 5], [6, 3], [8, 1]] {
assert!(front.insert(p));
}
assert!(front.insert([3, 3]));
assert_eq!(front.as_slice(), &[[0, 9], [2, 7], [3, 3], [8, 1]]);
}
#[test]
fn removes_scattered_points_in_three_dimensions() {
let mut front = Front::new();
for p in [[1_u8, 1, 9], [2, 5, 5], [3, 9, 1], [4, 6, 4]] {
assert!(front.insert(p));
}
assert!(front.insert([2, 5, 4]));
assert_eq!(front.as_slice(), &[[1, 1, 9], [2, 5, 4], [3, 9, 1]]);
}
}