1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
use crate::LatLng;
use core::{fmt, ops::Deref};

/// Maximum number of cell boundary vertices.
///
/// Worst case is pentagon: 5 original verts + 5 edge crossings.
const MAX_BNDRY_VERTS: usize = 10;

/// Boundary in latitude/longitude.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Default)]
pub struct Boundary {
    /// Vertices in CCW order.
    points: [LatLng; MAX_BNDRY_VERTS],
    /// Number of vertices.
    count: u8,
}

impl Boundary {
    /// Initializes a new empty cell boundary (test only)
    #[must_use]
    #[doc(hidden)]
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a vertices to the boundary (test only).
    #[doc(hidden)]
    pub fn push(&mut self, ll: LatLng) {
        self.points[usize::from(self.count)] = ll;
        self.count += 1;
    }
}

impl Deref for Boundary {
    type Target = [LatLng];

    /// Dereference to the slice of filled elements.
    fn deref(&self) -> &Self::Target {
        &self.points[..self.count.into()]
    }
}

impl fmt::Display for Boundary {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "[",)?;
        for (i, ll) in self.iter().enumerate() {
            if i != 0 {
                write!(f, "-")?;
            }
            write!(f, "{ll}")?;
        }
        write!(f, "]",)
    }
}

#[cfg(feature = "geo")]
impl From<Boundary> for geo::LineString {
    fn from(value: Boundary) -> Self {
        Self::new(value.iter().copied().map(geo::Coord::from).collect())
    }
}