rstar/primitives/
point_with_data.rs

1use crate::{Point, PointDistance, RTreeObject, AABB};
2
3/// A point with some associated data that can be inserted into an r-tree.
4///
5/// **Note**: `PointWithData` has been deprecated in favour of [`GeomWithData`](crate::primitives::GeomWithData)
6///
7/// Often, adding metadata (like a database index) to a point is required before adding them
8/// into an r-tree. This struct removes some of the boilerplate required to do so.
9///
10/// # Example
11/// ```
12/// use rstar::{RTree, PointDistance};
13/// use rstar::primitives::PointWithData;
14///
15/// type RestaurantLocation = PointWithData<&'static str, [f64; 2]>;
16///
17/// let mut restaurants = RTree::new();
18/// restaurants.insert(RestaurantLocation::new("Pete's Pizza Place", [0.3, 0.2]));
19/// restaurants.insert(RestaurantLocation::new("The Great Steak", [-0.8, 0.0]));
20/// restaurants.insert(RestaurantLocation::new("Fishy Fortune", [0.2, -0.2]));
21///
22/// let my_location = [0.0, 0.0];
23///
24/// // Now find the closest restaurant!
25/// let place = restaurants.nearest_neighbor(&my_location).unwrap();
26/// println!("Let's go to {}", place.data);
27/// println!("It's really close, only {} miles", place.distance_2(&my_location))
28/// ```
29#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
30#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
31pub struct PointWithData<T, P> {
32    /// Any data associated with a point.
33    pub data: T,
34    point: P, // Private to prevent modification.
35}
36
37impl<T, P> PointWithData<T, P> {
38    /// Creates a new `PointWithData` with the provided data.
39    #[deprecated(note = "`PointWithData` is deprecated. Please switch to `GeomWithData`")]
40    pub fn new(data: T, point: P) -> Self {
41        PointWithData { data, point }
42    }
43
44    /// Returns this point's position.
45    pub fn position(&self) -> &P {
46        &self.point
47    }
48}
49
50impl<T, P> RTreeObject for PointWithData<T, P>
51where
52    P: Point,
53{
54    type Envelope = AABB<P>;
55
56    fn envelope(&self) -> Self::Envelope {
57        self.point.envelope()
58    }
59}
60
61impl<T, P> PointDistance for PointWithData<T, P>
62where
63    P: Point,
64{
65    fn distance_2(&self, point: &P) -> <P as Point>::Scalar {
66        self.point.distance_2(point)
67    }
68
69    fn contains_point(&self, point: &P) -> bool {
70        self.point.contains_point(point)
71    }
72}