use alloc::collections::{BTreeMap, BTreeSet};
use heuristic_search::Weight;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct Handle(u64);
#[derive(Debug, Clone)]
pub(crate) struct FocalList<S, T> {
weight: Weight,
open: BTreeSet<(u32, Handle)>,
values: BTreeSet<(u32, Handle)>,
focal: BTreeSet<(S, u32, Handle)>,
items: BTreeMap<Handle, Item<S, T>>,
bound: Option<u32>,
next: u64,
}
impl<S: Ord + Copy, T> FocalList<S, T> {
pub(crate) fn new(weight: Weight) -> Self {
Self {
weight,
open: BTreeSet::new(),
values: BTreeSet::new(),
focal: BTreeSet::new(),
items: BTreeMap::new(),
bound: None,
next: 0,
}
}
pub(crate) fn push(&mut self, f: u32, value: u32, secondary: S, item: T) -> Handle {
debug_assert!(
f <= value,
"the value of an item is at least its lower bound"
);
let handle = Handle(self.next);
self.next += 1;
self.open.insert((f, handle));
self.values.insert((value, handle));
if self.bound.is_some_and(|bound| value <= bound) {
self.focal.insert((secondary, value, handle));
}
self.items.insert(
handle,
Item {
f,
value,
secondary,
payload: item,
},
);
handle
}
pub(crate) fn remove(&mut self, handle: Handle) -> Option<T> {
let item = self.items.remove(&handle)?;
self.open.remove(&(item.f, handle));
self.values.remove(&(item.value, handle));
self.focal.remove(&(item.secondary, item.value, handle));
Some(item.payload)
}
pub(crate) fn f_min(&self) -> Option<u32> {
self.open.first().map(|&(f, _)| f)
}
pub(crate) fn pop(&mut self) -> Option<(T, u32)> {
let f_min = self.f_min()?;
self.synchronize(within(f_min, self.weight));
let &(_, _, handle) = self.focal.first()?;
let item = self.remove(handle).expect("focal items are in the list");
if self.items.is_empty() {
self.bound = None;
}
Some((item, f_min))
}
fn synchronize(&mut self, bound: u32) {
let old = self.bound.replace(bound);
let (low, high, enter) = match old {
None => (0, bound, true),
Some(old) if old < bound => (old + 1, bound, true),
Some(old) if old > bound => (bound + 1, old, false),
Some(_) => return,
};
let range = (low, Handle(0))..=(high, Handle(u64::MAX));
for &(value, handle) in self.values.range(range) {
let secondary = self.items[&handle].secondary;
if enter {
self.focal.insert((secondary, value, handle));
} else {
self.focal.remove(&(secondary, value, handle));
}
}
}
}
#[derive(Debug, Clone)]
struct Item<S, T> {
f: u32,
value: u32,
secondary: S,
payload: T,
}
pub(crate) fn within(f_min: u32, weight: Weight) -> u32 {
let scaled = u64::from(f_min) * u64::from(weight.numerator()) / u64::from(weight.denominator());
u32::try_from(scaled).unwrap_or(u32::MAX)
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::vec::Vec;
fn drain(list: &mut FocalList<u32, char>) -> Vec<(char, u32)> {
core::iter::from_fn(|| list.pop()).collect()
}
fn push(list: &mut FocalList<u32, char>, f: u32, secondary: u32, item: char) -> Handle {
list.push(f, f, secondary, item)
}
#[test]
fn weight_one_is_best_first() {
let mut list = FocalList::new(Weight::ONE);
push(&mut list, 5, 0, 'a');
push(&mut list, 3, 9, 'b');
push(&mut list, 3, 1, 'c');
assert_eq!(drain(&mut list), [('c', 3), ('b', 3), ('a', 5)]);
}
#[test]
fn weight_two_prefers_the_secondary_key() {
let mut list = FocalList::new(Weight::integer(2));
push(&mut list, 4, 5, 'a');
push(&mut list, 7, 0, 'b');
push(&mut list, 9, 0, 'c');
assert_eq!(list.pop(), Some(('b', 4)));
assert_eq!(list.pop(), Some(('a', 4)));
assert_eq!(list.pop(), Some(('c', 9)));
assert_eq!(list.pop(), None);
}
#[test]
fn removal_and_falling_bounds() {
let mut list = FocalList::new(Weight::new(3, 2));
let low = push(&mut list, 2, 9, 'a');
push(&mut list, 3, 0, 'b');
push(&mut list, 10, 0, 'c');
assert_eq!(list.pop(), Some(('b', 2)));
assert_eq!(list.remove(low), Some('a'));
assert_eq!(list.remove(low), None);
push(&mut list, 4, 0, 'd');
assert_eq!(list.pop(), Some(('d', 4)));
assert_eq!(list.pop(), Some(('c', 10)));
}
#[test]
fn value_decides_membership() {
let mut list = FocalList::new(Weight::integer(2));
list.push(3, 6, 1, 'a');
list.push(4, 5, 0, 'b');
list.push(5, 7, 0, 'c');
assert_eq!(list.pop(), Some(('b', 3)));
assert_eq!(list.pop(), Some(('a', 3)));
assert_eq!(list.pop(), Some(('c', 5)));
}
#[test]
fn bound_rounds_down() {
assert_eq!(within(10, Weight::new(11, 10)), 11);
assert_eq!(within(5, Weight::new(3, 2)), 7);
assert_eq!(within(u32::MAX, Weight::integer(2)), u32::MAX);
}
}