geolith_tiles_builder/sort/
entry.rs1use std::cmp::Ordering;
4
5use serde::{Deserialize, Serialize};
6
7use geolith::tile::feature::{PropValue, TileFeature};
8
9#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
20pub struct SortEntry {
21 pub key: u64,
23 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
43fn 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
62fn 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 #[inline]
88 #[must_use]
89 pub const fn new(key: u64, feature: TileFeature) -> Self {
90 Self { key, feature }
91 }
92
93 pub fn to_bytes(&self) -> Result<Vec<u8>, postcard::Error> {
99 postcard::to_allocvec(self)
100 }
101
102 pub fn from_bytes(bytes: &[u8]) -> Result<Self, postcard::Error> {
108 postcard::from_bytes(bytes)
109 }
110}