Skip to main content

geolith_tiles_builder/sort/
entry.rs

1//! Sort entry — the unit of data in the external merge sort.
2
3use std::cmp::Ordering;
4
5use serde::{Deserialize, Serialize};
6
7use geolith::tile::feature::{PropValue, TileFeature};
8
9/// A single entry in the external sort.
10///
11/// Pairs a composite sort key (see `tile::sort_key`) with the serialized
12/// tile feature. The sort key enables comparison without deserializing
13/// the feature payload.
14///
15/// Ordering is total: entries with equal keys are ordered by their feature
16/// content, so the merged stream, and the feature order inside every tile,
17/// is a function of the input alone, never of which worker thread wrote
18/// which chunk.
19#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
20pub struct SortEntry {
21    /// Composite sort key: `(zoom, tile_id, layer, feature_sort)` packed into `u64`.
22    pub key: u64,
23    /// The tile feature to be written into the MVT tile.
24    pub feature: TileFeature,
25}
26
27impl Eq for SortEntry {}
28
29impl PartialOrd for SortEntry {
30    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
31        Some(self.cmp(other))
32    }
33}
34
35impl Ord for SortEntry {
36    fn cmp(&self, other: &Self) -> Ordering {
37        self.key
38            .cmp(&other.key)
39            .then_with(|| cmp_feature(&self.feature, &other.feature))
40    }
41}
42
43/// Total order over feature content, used only to break sort-key ties.
44fn cmp_feature(a: &TileFeature, b: &TileFeature) -> Ordering {
45    a.id.cmp(&b.id)
46        .then_with(|| (a.layer as u8).cmp(&(b.layer as u8)))
47        .then_with(|| a.sort_key.cmp(&b.sort_key))
48        .then_with(|| (a.geom_type as u8).cmp(&(b.geom_type as u8)))
49        .then_with(|| a.geometry.cmp(&b.geometry))
50        .then_with(|| {
51            let (pa, pb) = (a.properties.as_slice(), b.properties.as_slice());
52            pa.len().cmp(&pb.len()).then_with(|| {
53                pa.iter()
54                    .zip(pb)
55                    .map(|((ka, va), (kb, vb))| ka.cmp(kb).then_with(|| cmp_value(va, vb)))
56                    .find(|o| o.is_ne())
57                    .unwrap_or(Ordering::Equal)
58            })
59        })
60}
61
62/// Total order over property values: variant first, then value (`f64` by
63/// `total_cmp`, so NaN has a place too).
64fn cmp_value(a: &PropValue, b: &PropValue) -> Ordering {
65    const fn rank(v: &PropValue) -> u8 {
66        match v {
67            PropValue::Str(_) => 0,
68            PropValue::F64(_) => 1,
69            PropValue::I64(_) => 2,
70            PropValue::U64(_) => 3,
71            PropValue::Bool(_) => 4,
72            _ => 5,
73        }
74    }
75    match (a, b) {
76        (PropValue::Str(x), PropValue::Str(y)) => x.cmp(y),
77        (PropValue::F64(x), PropValue::F64(y)) => x.total_cmp(y),
78        (PropValue::I64(x), PropValue::I64(y)) => x.cmp(y),
79        (PropValue::U64(x), PropValue::U64(y)) => x.cmp(y),
80        (PropValue::Bool(x), PropValue::Bool(y)) => x.cmp(y),
81        _ => rank(a).cmp(&rank(b)),
82    }
83}
84
85impl SortEntry {
86    /// Create a new sort entry.
87    #[inline]
88    #[must_use]
89    pub const fn new(key: u64, feature: TileFeature) -> Self {
90        Self { key, feature }
91    }
92
93    /// Serialize this entry to bytes using postcard.
94    ///
95    /// # Errors
96    ///
97    /// Returns an error if postcard serialization fails.
98    pub fn to_bytes(&self) -> Result<Vec<u8>, postcard::Error> {
99        postcard::to_allocvec(self)
100    }
101
102    /// Deserialize a sort entry from bytes.
103    ///
104    /// # Errors
105    ///
106    /// Returns an error if postcard deserialization fails.
107    pub fn from_bytes(bytes: &[u8]) -> Result<Self, postcard::Error> {
108        postcard::from_bytes(bytes)
109    }
110}