Skip to main content

mln_style/feature/
item.rs

1use geo_types::{CoordNum, Geometry};
2
3use super::value::{Value, ValueObject};
4
5/// A feature's id: none, a number or a string.
6#[derive(Clone, Debug, Default, PartialEq, mln_wire::Wire)]
7pub enum Identifier {
8    #[default]
9    Null,
10    Uint(u64),
11    Int(i64),
12    Double(f64),
13    String(String),
14}
15
16impl Identifier {
17    /// The id a feature takes from the value of its property that a source's
18    /// `promoteId` names: a string or a number as it is, a boolean as 1 or 0,
19    /// and none for anything else.
20    #[must_use]
21    pub fn promoted(value: Option<&Value>) -> Identifier {
22        match value {
23            Some(Value::String(s)) => Identifier::String(s.clone()),
24            Some(Value::Uint(u)) => Identifier::Uint(*u),
25            Some(Value::Int(i)) => Identifier::Int(*i),
26            Some(Value::Double(d)) => Identifier::Double(*d),
27            Some(Value::Bool(b)) => Identifier::Uint(u64::from(*b)),
28            Some(Value::Null | Value::Array(_) | Value::Object(_)) | None => Identifier::Null,
29        }
30    }
31}
32
33pub type PropertyMap = ValueObject;
34
35/// A feature: its geometry, properties and id.
36///
37/// `geometry` is `None` for a feature without one, as for a GeoJSON feature
38/// whose geometry is `null`.
39///
40/// `P` holds the properties. Features that share one property map, as the
41/// features a GeoJSON source's tiles cut from one source feature do, hold it
42/// as an [`Arc<PropertyMap>`](std::sync::Arc).
43#[derive(Clone, Debug, PartialEq, mln_wire::Wire)]
44pub struct Feature<T: CoordNum = f64, P = PropertyMap> {
45    pub geometry: Option<Geometry<T>>,
46    pub properties: P,
47    pub id: Identifier,
48}
49
50impl<T: CoordNum, P: Default> Default for Feature<T, P> {
51    fn default() -> Self {
52        Feature { geometry: None, properties: P::default(), id: Identifier::Null }
53    }
54}
55
56impl<T: CoordNum> Feature<T> {
57    pub fn new(geometry: impl Into<Geometry<T>>) -> Self {
58        Feature { geometry: Some(geometry.into()), properties: PropertyMap::new(), id: Identifier::Null }
59    }
60}