Skip to main content

Index

Struct Index 

Source
pub struct Index { /* private fields */ }
Expand description

A static R-tree over (Rect, u32) entries, bulk-loaded by STR packing.

The index is built once by Index::bulk_load and then queried, and it cannot be changed afterward. The u32 is the caller’s identifier for the entry, returned by Index::query, and it need not be unique.

use situs::{Index, Rect};

let r = |a, b, c, d| Rect::new(a, b, c, d).unwrap();
let index = Index::bulk_load(vec![(r(0.0, 0.0, 1.0, 1.0), 7), (r(5.0, 5.0, 6.0, 6.0), 9)]);

let mut hits = Vec::new();
index.query(&r(1.0, 1.0, 2.0, 2.0), |id| hits.push(id));
assert_eq!(hits, [7]); // touching at a corner counts

Implementations§

Source§

impl Index

Source

pub fn nearest_exact( &self, x: f64, y: f64, k: usize, ) -> Result<Vec<Neighbor>, QueryError>

Available on crate feature exact-nearest only.

The k entries nearest to (x, y) by exact Euclidean distance to their boxes, plus every entry exactly as near as the k-th.

The result is ordered by exact distance, and entries at exactly equal distance by id, then by internal position. Each Neighbor still carries its certified bounds, while the order and the cut are exact. The result has exactly k entries unless the k-th is exactly tied, and it never guesses between candidates the bounds alone could not order.

The ranking is exact by construction. The candidates of Index::nearest_candidates contain every entry within the k-th true distance, ties included. Each is ranked by comparing the exact distances from the query point to the nearest points of the boxes (the query clamped to each box, a selection of stored values), with arithmetica’s exact compare_distance. Entries outside the candidate set are strictly farther than the k-th, so ranking the set ranks every entry that can be in the answer. The nearest module of the crate’s source carries the full argument.

k = 0 gives an empty result, and k >= len gives every entry, exactly ordered.

use situs::{Index, Rect};

let r = |a, b, c, d| Rect::new(a, b, c, d).unwrap();
// Squared distances from the origin are 2^54 and 2^54 + 1. They round
// to the same f64, so the bounds cannot order them, and the exact
// ranking can.
let p27 = 134_217_728.0; // 2^27
let index = Index::bulk_load(vec![(r(p27, 1.0, p27, 1.0), 1), (r(p27, 0.0, p27, 0.0), 2)]);
assert_eq!(index.nearest_candidates(0.0, 0.0, 1).unwrap().len(), 2);
let exact = index.nearest_exact(0.0, 0.0, 1).unwrap();
assert_eq!(exact.len(), 1);
assert_eq!(exact[0].id, 2);
§Errors

QueryError::NonFinite if x or y is NaN or infinite, checked before anything else.

Source§

impl Index

Source

pub fn nearest_candidates( &self, x: f64, y: f64, k: usize, ) -> Result<Vec<Neighbor>, QueryError>

The candidates for the k entries nearest to (x, y): exactly the entries e with lower_sq(e) <= τ, where τ is the k-th smallest upper_sq over all entries (+∞ when k >= len).

The result always contains the k entries truly nearest to the point, and every entry tied with the k-th. Let d²ₖ be the k-th smallest exact squared distance. The k entries with the smallest upper_sq each have d² ≤ upper_sq ≤ τ, so at least k entries have d² ≤ τ, which means d²ₖ ≤ τ. Any entry among the true k nearest, or tied with the k-th, has lower_sq ≤ d² ≤ d²ₖ ≤ τ, so it is in the result.

The result has exactly k entries unless distances near the k-th lie within a few ulps of each other, in which case it holds the extras rather than guessing among them. It depends only on the entries and the point rather than on the tree’s shape. An entry stored twice is a candidate twice, and k = 0 gives an empty result.

The result is ordered by (lower_sq, id), then by internal position. The order is deterministic but carries no meaning.

use situs::{Index, Rect};

let r = |a, b, c, d| Rect::new(a, b, c, d).unwrap();
let index = Index::bulk_load(vec![(r(0.0, 0.0, 1.0, 1.0), 7), (r(5.0, 5.0, 6.0, 6.0), 9)]);

let near = index.nearest_candidates(2.0, 2.0, 1).unwrap();
assert_eq!(near.len(), 1);
assert_eq!(near[0].id, 7);
// d² = 2: the bounds bracket it.
assert!(near[0].lower_sq <= 2.0 && 2.0 <= near[0].upper_sq);
§Errors

QueryError::NonFinite if x or y is NaN or infinite, checked before anything else. An empty index gives Ok of an empty vector.

Source

pub fn browse(&self, x: f64, y: f64) -> Result<Browse<'_>, QueryError>

The entries in nondecreasing lower_sq (ties by id, then internal position), each exactly once per stored entry.

The iterator holds one contract. Once a Neighbor with lower_sq = ℓ has been yielded, every entry not yet yielded has true d² >= ℓ. A caller refining candidates by its own exact distance stops once its best answer is at or below the next lower_sq.

use situs::{Index, Rect};

let r = |a, b, c, d| Rect::new(a, b, c, d).unwrap();
let index = Index::bulk_load(vec![(r(0.0, 0.0, 1.0, 1.0), 7), (r(5.0, 5.0, 6.0, 6.0), 9)]);

let order: Vec<u32> = index.browse(2.0, 2.0).unwrap().map(|n| n.id).collect();
assert_eq!(order, [7, 9]);
§Errors

QueryError::NonFinite if x or y is NaN or infinite. An empty index gives an iterator that yields nothing.

Source§

impl Index

Source

pub fn join(&self, other: &Index, visit: impl FnMut(u32, u32))

Calls visit(a_id, b_id) once for every pair of entries a in self and b in other whose boxes meet (closed: boxes that touch at an edge or a corner meet).

A pair is a pair of stored entries, so an entry stored twice, or two entries with the same id, give one report per stored pair. The order of the reports is a deterministic function of both layouts rather than a meaningful one.

The join reports exactly those pairs (crate doc, “Joins”). A pair of nodes is descended only if their boxes meet, and every ancestor pair of two meeting entries meets; a pair of entries is reported only after their own boxes are tested. The output can be quadratic in the sizes, so it is never collected, and each pair goes to visit as it is found. The pending node pairs live on a heap stack.

use situs::{Index, Rect};

let r = |a, b, c, d| Rect::new(a, b, c, d).unwrap();
let roads = Index::bulk_load(vec![(r(0.0, 0.0, 10.0, 0.0), 1), (r(0.0, 5.0, 10.0, 5.0), 2)]);
let lots = Index::bulk_load(vec![(r(2.0, -1.0, 3.0, 1.0), 10), (r(4.0, 1.0, 5.0, 4.0), 11)]);

let mut pairs = Vec::new();
roads.join(&lots, |road, lot| pairs.push((road, lot)));
assert_eq!(pairs, [(1, 10)]); // lot 11 lies between the roads
Source

pub fn self_join(&self, visit: impl FnMut(u32, u32))

Calls visit(x_id, y_id) once for every unordered pair of distinct stored entries of self whose boxes meet (closed). An entry is never paired with itself; two stored entries with equal boxes or equal ids are distinct entries and are paired.

Within a pair, x is the entry earlier in the index’s depth-first order, the order in which a query covering every entry reports them. That order is deterministic rather than meaningful, so a caller that needs (min, max) normalizes the pair. The order of the pairs is likewise deterministic and carries no meaning.

The traversal is that of Index::join, over pairs (N, P) of this tree’s nodes. A node is paired with itself, which pairs its children (cᵢ, cⱼ) with i ≤ j (pairs within one child are found below (cᵢ, cᵢ)), and a leaf paired with itself tests its entries (eᵢ, eⱼ) with i < j. Two different nodes are joined as in Index::join, and their subtrees are disjoint, so every pair is found exactly once.

use situs::{Index, Rect};

let r = |a, b, c, d| Rect::new(a, b, c, d).unwrap();
let index = Index::bulk_load(vec![
    (r(0.0, 0.0, 2.0, 2.0), 1),
    (r(2.0, 2.0, 3.0, 3.0), 2), // touches 1 at a corner
    (r(9.0, 9.0, 9.0, 9.0), 3),
]);

let mut pairs = Vec::new();
index.self_join(|x, y| pairs.push((x.min(y), x.max(y))));
assert_eq!(pairs, [(1, 2)]);
Source§

impl Index

Source

pub fn query(&self, window: &Rect, visit: impl FnMut(u32))

Calls visit with the id of every entry whose box meets window.

The query reports exactly those entries. A node is descended only if its box meets the window (which, by condition 2 of the crate’s correctness argument, loses nothing), and a leaf entry is reported only if its own box meets the window. Below a node whose box the window contains, every entry is reported untested, because every one is a hit (the containment shortcut; crate doc, “Storage and search”). An entry stored twice is reported twice. The order of visits is a deterministic function of the index layout rather than a meaningful one.

The search is iterative, with a fixed stack on the call stack, so it never allocates.

§Panics

Never. The search stack’s capacity is a proven bound on its height, and were that bound ever broken, the query would panic rather than silently drop part of the tree.

Source

pub fn try_query<B>( &self, window: &Rect, visit: impl FnMut(u32) -> ControlFlow<B>, ) -> ControlFlow<B>

Calls visit with the id of each entry whose box meets window, in the same order as Index::query, until visit returns ControlFlow::Break.

Returns that Break, or Continue(()) if every such entry was visited. The entries visited before a break are exactly a prefix of query’s sequence. Like query, it never allocates.

use core::ops::ControlFlow;
use situs::{Index, Rect};

let r = |a, b, c, d| Rect::new(a, b, c, d).unwrap();
let index = Index::bulk_load([(r(0.0, 0.0, 1.0, 1.0), 7), (r(5.0, 5.0, 6.0, 6.0), 9)].into());

// Does any entry meet this box? Stop at the first one.
let w = r(0.5, 0.5, 2.0, 2.0);
assert!(index.try_query(&w, |_| ControlFlow::Break(())).is_break());

// The first entry meeting a box, if any.
let first = index.try_query(&r(4.0, 4.0, 9.0, 9.0), ControlFlow::Break);
assert_eq!(first, ControlFlow::Break(9));
§Panics

Never, as for Index::query.

Source§

impl Index

Source

pub const NODE_CAPACITY: usize = 16

Entries per leaf and children per node, the M of STR packing.

A capacity of 16 keeps a node’s boxes within a few cache lines and the tree shallow, so a million entries make five levels.

Source

pub fn memory_size_for(n: usize) -> usize

The heap bytes a built index of n entries holds, so that a caller can size an index before building it.

Exactly n · size_of::<(Rect, u32)>() + nodes(n) · size_of::<Node>(), where nodes(n) is the node count STR packing produces: ⌈n / M⌉ leaves, then ⌈· / M⌉ nodes per level above until one node remains, and none for n = 0; Node is the index’s private node record (a box and a child range). The count is a function of n alone, because every level is the level below cut into chunks of M.

The figure omits four things:

  • Spare capacity in the entry vector. The figure assumes the vector passed to Index::bulk_load has capacity equal to its length. The index keeps that vector, so any spare capacity is held as well.
  • Spare capacity in the node vector, of which there is none. It is allocated with exactly the node count.
  • The transient allocations made while building, one vector per level, freed before bulk_load returns. They total at most the node count again.
  • The inline size of the Index value itself (size_of::<Index>()), which is not heap memory.

The result saturates. For an n so large that the size overflows usize, it is usize::MAX, and no such index can be built.

use situs::{Index, Rect};

assert_eq!(Index::memory_size_for(0), 0);
assert!(Index::memory_size_for(1_000) > 1_000 * core::mem::size_of::<(Rect, u32)>());
assert_eq!(Index::memory_size_for(usize::MAX), usize::MAX);
Source

pub fn bulk_load(entries: Vec<(Rect, u32)>) -> Index

Builds the index over entries by STR packing (see the crate doc).

The build costs O(n log n), from the sorts. The entry vector is reordered into leaf order and kept rather than copied. The build never panics, because every Rect is finite, so every sort key is finite and total_cmp orders all of them.

Source

pub fn len(&self) -> usize

The number of entries.

Source

pub fn is_empty(&self) -> bool

true if the index holds no entry.

Source

pub fn bounds(&self) -> Option<Rect>

The box containing every entry, or None for an empty index.

It is the root’s box, an exact union of every entry’s box.

Trait Implementations§

Source§

impl Clone for Index

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Index

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl Forget for Index

§

impl Freeze for Index

§

impl RefUnwindSafe for Index

§

impl Send for Index

§

impl Sync for Index

§

impl Unpin for Index

§

impl UnsafeUnpin for Index

§

impl UnwindSafe for Index

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.