Skip to main content

rstar/primitives/
object_ref.rs

1use crate::object::PointDistance;
2use crate::object::RTreeObject;
3use crate::{envelope::Envelope, object::Distance};
4use core::ops::Deref;
5
6/// An [RTreeObject] that is a possibly short-lived reference to another object.
7///
8/// Sometimes it can be useful to build an [RTree] that does not own its constituent
9/// objects but references them from elsewhere. Wrapping the bare references with this
10/// combinator makes this possible.
11///
12/// **Note:** the wrapper implements [RTreeObject] and referenced object `T` can be
13/// accessed via an implementation of `Deref<Target=T>`.
14#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
15pub struct ObjectRef<'a, T: RTreeObject> {
16    inner: &'a T,
17}
18
19impl<T: RTreeObject> RTreeObject for ObjectRef<'_, T> {
20    type Envelope = T::Envelope;
21
22    fn envelope(&self) -> Self::Envelope {
23        self.inner.envelope()
24    }
25}
26
27impl<T: PointDistance> PointDistance for ObjectRef<'_, T> {
28    fn distance_2(&self, point: &<Self::Envelope as Envelope>::Point) -> Distance<Self> {
29        self.inner.distance_2(point)
30    }
31
32    fn contains_point(&self, p: &<Self::Envelope as Envelope>::Point) -> bool {
33        self.inner.contains_point(p)
34    }
35
36    fn distance_2_if_less_or_equal(
37        &self,
38        point: &<Self::Envelope as Envelope>::Point,
39        max_distance_2: Distance<Self>,
40    ) -> Option<Distance<Self>> {
41        self.inner
42            .distance_2_if_less_or_equal(point, max_distance_2)
43    }
44}
45
46impl<'a, T: RTreeObject> ObjectRef<'a, T> {
47    /// Create a new [ObjectRef] struct using the object.
48    pub fn new(inner: &'a T) -> Self {
49        Self { inner }
50    }
51}
52
53impl<T: RTreeObject> Deref for ObjectRef<'_, T> {
54    type Target = T;
55
56    fn deref(&self) -> &Self::Target {
57        self.inner
58    }
59}