use std::cmp::Ordering;
use serde::{Deserialize, Serialize};
use geolith::tile::feature::{PropValue, TileFeature};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SortEntry {
pub key: u64,
pub feature: TileFeature,
}
impl Eq for SortEntry {}
impl PartialOrd for SortEntry {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for SortEntry {
fn cmp(&self, other: &Self) -> Ordering {
self.key
.cmp(&other.key)
.then_with(|| cmp_feature(&self.feature, &other.feature))
}
}
fn cmp_feature(a: &TileFeature, b: &TileFeature) -> Ordering {
a.id.cmp(&b.id)
.then_with(|| (a.layer as u8).cmp(&(b.layer as u8)))
.then_with(|| a.sort_key.cmp(&b.sort_key))
.then_with(|| (a.geom_type as u8).cmp(&(b.geom_type as u8)))
.then_with(|| a.geometry.cmp(&b.geometry))
.then_with(|| {
let (pa, pb) = (a.properties.as_slice(), b.properties.as_slice());
pa.len().cmp(&pb.len()).then_with(|| {
pa.iter()
.zip(pb)
.map(|((ka, va), (kb, vb))| ka.cmp(kb).then_with(|| cmp_value(va, vb)))
.find(|o| o.is_ne())
.unwrap_or(Ordering::Equal)
})
})
}
fn cmp_value(a: &PropValue, b: &PropValue) -> Ordering {
const fn rank(v: &PropValue) -> u8 {
match v {
PropValue::Str(_) => 0,
PropValue::F64(_) => 1,
PropValue::I64(_) => 2,
PropValue::U64(_) => 3,
PropValue::Bool(_) => 4,
_ => 5,
}
}
match (a, b) {
(PropValue::Str(x), PropValue::Str(y)) => x.cmp(y),
(PropValue::F64(x), PropValue::F64(y)) => x.total_cmp(y),
(PropValue::I64(x), PropValue::I64(y)) => x.cmp(y),
(PropValue::U64(x), PropValue::U64(y)) => x.cmp(y),
(PropValue::Bool(x), PropValue::Bool(y)) => x.cmp(y),
_ => rank(a).cmp(&rank(b)),
}
}
impl SortEntry {
#[inline]
#[must_use]
pub const fn new(key: u64, feature: TileFeature) -> Self {
Self { key, feature }
}
pub fn to_bytes(&self) -> Result<Vec<u8>, postcard::Error> {
postcard::to_allocvec(self)
}
pub fn from_bytes(bytes: &[u8]) -> Result<Self, postcard::Error> {
postcard::from_bytes(bytes)
}
}