use std::borrow::Cow;
use std::ops::{Deref, DerefMut, Range};
use std::sync::Arc;
use geometry::Point;
use crate::error::Error;
use crate::feature::{Identifier, PropertyMap, Value};
use crate::geometry::FeatureType;
pub type GeometryCoordinate = Point<i16>;
pub type GeometryCoordinates = Vec<GeometryCoordinate>;
#[derive(Clone, Debug, Default)]
pub struct GeometryCollection {
rings: Vec<GeometryCoordinates>,
triangles: Option<(Arc<[u32]>, Range<usize>)>,
}
impl GeometryCollection {
#[must_use]
pub const fn new() -> Self {
GeometryCollection { rings: Vec::new(), triangles: None }
}
#[must_use]
pub fn triangles(&self) -> &[u32] {
match &self.triangles {
Some((owner, range)) => &owner[range.clone()],
None => &[],
}
}
pub fn set_triangles(&mut self, owner: Arc<[u32]>, range: Range<usize>) {
assert!(range.start <= range.end && range.end <= owner.len());
self.triangles = Some((owner, range));
}
}
impl PartialEq for GeometryCollection {
fn eq(&self, other: &Self) -> bool {
self.rings == other.rings
}
}
impl From<Vec<GeometryCoordinates>> for GeometryCollection {
fn from(rings: Vec<GeometryCoordinates>) -> Self {
GeometryCollection { rings, triangles: None }
}
}
impl Deref for GeometryCollection {
type Target = Vec<GeometryCoordinates>;
fn deref(&self) -> &Self::Target {
&self.rings
}
}
impl DerefMut for GeometryCollection {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.rings
}
}
static EMPTY_PROPERTIES: PropertyMap = PropertyMap::new();
static EMPTY_GEOMETRIES: GeometryCollection = GeometryCollection::new();
pub trait GeometryTileFeature {
fn feature_type(&self) -> FeatureType;
fn value(&self, key: &str) -> Option<Value>;
fn properties(&self) -> Cow<'_, PropertyMap> {
Cow::Borrowed(&EMPTY_PROPERTIES)
}
fn id(&self) -> Identifier {
Identifier::Null
}
fn geometries(&self) -> Result<Cow<'_, GeometryCollection>, Error> {
Ok(Cow::Borrowed(&EMPTY_GEOMETRIES))
}
}
#[cfg(test)]
mod tests {
use super::*;
struct Feature;
impl GeometryTileFeature for Feature {
fn feature_type(&self) -> FeatureType {
FeatureType::Point
}
fn value(&self, _key: &str) -> Option<Value> {
None
}
}
#[test]
fn defaults() {
let f = Feature;
assert!(f.properties().is_empty());
assert_eq!(f.id(), Identifier::Null);
assert!(f.geometries().unwrap().is_empty());
let mut c = GeometryCollection::new();
c.push(vec![Point::new(1, 2)]);
assert_eq!(c.clone()[0][0], Point::new(1, 2));
}
#[test]
fn triangles() {
let mut c = GeometryCollection::from(vec![vec![Point::new(0, 0), Point::new(1, 0), Point::new(0, 1)]]);
assert_eq!(c.triangles(), <&[u32]>::default());
let owner: Arc<[u32]> = Arc::from(vec![9, 9, 0, 1, 2, 9]);
c.set_triangles(owner, 2..5);
assert_eq!(c.triangles(), &[0, 1, 2]);
assert_eq!(c.clone().triangles(), &[0, 1, 2]);
assert_eq!(c, GeometryCollection::from(c.to_vec()));
}
}