/// For `QueryBound::SqDist(d)`, this means points whose sqdist from the query point is <= d will be excluded.
/// Since the query point itself is included by default if it is in the tree, passing `QueryBound::SqDist(Distance::zero())`
/// For `QueryBound::Region(&r)`, this means points within `r` (where `r.min_sqdist` is `Distance::zero()`) will excluded.
/// That is, if `R::min_sqdist` can be an underestimate, then `QueryBound::Region` should not be used.
/// This makes the overall included region a half open set, excluding the inner bound but including
/// the outer bound. This is to make it easy to have successive queries cover additional area without duplicate results.
/// For `QueryBound::SqDist(d)`, points whose sqdist from the query point is > d will be excluded.
/// For `QueryBount::Region(&r)`, points outside `r` (where `r.min_sqdist` is not `Distance::zero()`) will be excluded.
/// Unlike the inner bound, this will work correctly with a conservative `R::min_sqdist` (ie if min_sqdist is an underestimate
/// it can only cause the result to include extra points, not miss points that should be included).
/// If false, if multiple points are tied for being the kth closest, which one will be returned is arbitrary,
/// If true, if multiple points are tied for being the kth closest, all of them will be returned,
/// Setting this to true is necessary to correctly call [`KdTree::k_closest`] with an iteratively increasing sampling
pub const ALL_KEEP_TIES: Self = Self{inner_bound: QueryBound::None, outer_bound: QueryBound::None, keep_ties: true};
/// and arbitrarily break ties for the kth-closest point so no more than k points are ever returned.
pub const ALL_NO_TIES: Self = Self{inner_bound: QueryBound::None, outer_bound: QueryBound::None, keep_ties: false};
/// Returns true if the included region contains the point `pt`, where `point` is the center of the query,
QueryBound::Region(r) => if r.min_sqdist(pt) > <R::Point as KdPoint>::Distance::zero() { return false },
/// However, when this function returns false, the query region will always be disjoint from `bounds`,
/// UNLESS `self.inner_bound` is not `QueryBound::None` and a conservative implementation is used for [`KdRegion`].
pub fn might_overlap(&self, point: &R::Point, max_sqdist: Option<&<R::Point as KdPoint>::Distance>, bounds: &R) -> bool {
QueryBound::SqDist(outer_sqdist) => if bounds.min_sqdist(point) > *outer_sqdist { return false },
QueryBound::SqDist(inner_sqdist) => !bounds.max_sqdist(point).is_some_and(|d|d <= *inner_sqdist),
/// A KD tree represents a collection of points in space, with the ability to answer distance related queries, mainly:
/// - What are the k closest points to a given point? (The first k points in the tree, ordered by increasing squared
/// distance from the given point, including the given point if it is in the tree). (Sometimes called a nearest
/// - What are all the points within a distance d of a given point? (All points whose squared distance from a given
/// This implementation uses an implicit tree, meaning all points are stored in one contiguous buffer and no dereferences
/// are needed to traverse the tree. This is good for lookup performance, but unfortunately it means that adding/removing
/// Besides the three basic distance related queries, KD trees can be used to some extent to help with more complicated
pub fn walk<'a>(&'a self, visitor: &mut impl FnMut(&R, &'a R::Point, &'a V) -> WalkDecision) {
pub fn walk_mut<'a>(&'a mut self, visitor: &mut impl FnMut(&R, &'a R::Point, &mut V) -> WalkDecision) {
/// - Can restrict the result set to only include points within a certain sqdist of the query point
/// or withn a certain region, as well as to exclude points within another smaller sqdist or subregion.
/// - Can specify how any points tied for kth closest should be handled (keep all or keep one arbitrarily).
pub fn k_closest<'a>(&'a self, point: &R::Point, k: usize, cfg: QueryOptions<'a, R>) -> MmHeap<(&'a R::Point, &'a V)> {
let mut max_sqdist = if let QueryBound::SqDist(max_sqdist) = &cfg.outer_bound { Some(max_sqdist.clone()) } else { None };
/// The order of the result is arbitrary, but the value for each point will be visited exactly once.
/// The order of the result is arbitrary, but the value for each point will be visited exactly once.
/// This is a splitting borrow, so it is safe to store a reference to some value and mutate it even
/// The order of the result is arbitrary, but the value for each point will be visited exactly once.
/// Return a reference to the value for some point in the tree, or None if the point is not found
/// Return a reference to a point in the tree and the corresponding value, or None if the point is not found
/// Return a mutable reference to the value for some point in the tree, or None if the point is not found
/// [`Self::launder_idx_mut`]. `ent` MUST be a reference to one of the points actually stored in
/// [`Self::launder_idx_point`]. `ent` MUST be a reference to one of the values actually stored in
/// The internal index must have come from [`Self::launder_point_ref`] or [`Self::launder_value_ref`]
/// The internal index must have come from [`Self::launder_point_ref`] or [`Self::launder_value_ref`]
self.points[a..b].select_nth_unstable_by(med_idx - a, |(p, _), (q, _)| p.cmp(q, layer)); // rust picks up Ord::cmp if we don't handhold it
pub(crate) fn k_closest_naive<'a>(&'a self, point: &R::Point, k: usize) -> Vec<(&'a R::Point, &'a V)> {
let Some(([(a, b)], tail)) = mem::take(&mut self.tail).split_at_mut_checked(1) else { return None };