rstar/primitives/
object_ref.rs

1use crate::envelope::Envelope;
2use crate::object::PointDistance;
3use crate::{object::RTreeObject, point::Point};
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<'a, T: RTreeObject> RTreeObject for ObjectRef<'a, T> {
20    type Envelope = T::Envelope;
21
22    fn envelope(&self) -> Self::Envelope {
23        self.inner.envelope()
24    }
25}
26
27impl<'a, T: PointDistance> PointDistance for ObjectRef<'a, T> {
28    fn distance_2(
29        &self,
30        point: &<Self::Envelope as Envelope>::Point,
31    ) -> <<Self::Envelope as Envelope>::Point as Point>::Scalar {
32        self.inner.distance_2(point)
33    }
34
35    fn contains_point(&self, p: &<Self::Envelope as Envelope>::Point) -> bool {
36        self.inner.contains_point(p)
37    }
38
39    fn distance_2_if_less_or_equal(
40        &self,
41        point: &<Self::Envelope as Envelope>::Point,
42        max_distance_2: <<Self::Envelope as Envelope>::Point as Point>::Scalar,
43    ) -> Option<<<Self::Envelope as Envelope>::Point as Point>::Scalar> {
44        self.inner
45            .distance_2_if_less_or_equal(point, max_distance_2)
46    }
47}
48
49impl<'a, T: RTreeObject> ObjectRef<'a, T> {
50    /// Create a new [ObjectRef] struct using the object.
51    pub fn new(inner: &'a T) -> Self {
52        Self { inner }
53    }
54}
55
56impl<'a, T: RTreeObject> Deref for ObjectRef<'a, T> {
57    type Target = T;
58
59    fn deref(&self) -> &Self::Target {
60        self.inner
61    }
62}