geolith-tiles-builder 0.4.2

Builds tiles from OpenStreetMap and Overture Maps: protomaps-schema vector PMTiles, Terrain-RGB, raster archives and 3D Tiles from Gaussian splats
Documentation
//! Sort entry — the unit of data in the external merge sort.

use std::cmp::Ordering;

use serde::{Deserialize, Serialize};

use geolith::tile::feature::{PropValue, TileFeature};

/// A single entry in the external sort.
///
/// Pairs a composite sort key (see `tile::sort_key`) with the serialized
/// tile feature. The sort key enables comparison without deserializing
/// the feature payload.
///
/// Ordering is total: entries with equal keys are ordered by their feature
/// content, so the merged stream, and the feature order inside every tile,
/// is a function of the input alone, never of which worker thread wrote
/// which chunk.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SortEntry {
    /// Composite sort key: `(zoom, tile_id, layer, feature_sort)` packed into `u64`.
    pub key: u64,
    /// The tile feature to be written into the MVT tile.
    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))
    }
}

/// Total order over feature content, used only to break sort-key ties.
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)
            })
        })
}

/// Total order over property values: variant first, then value (`f64` by
/// `total_cmp`, so NaN has a place too).
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 {
    /// Create a new sort entry.
    #[inline]
    #[must_use]
    pub const fn new(key: u64, feature: TileFeature) -> Self {
        Self { key, feature }
    }

    /// Serialize this entry to bytes using postcard.
    ///
    /// # Errors
    ///
    /// Returns an error if postcard serialization fails.
    pub fn to_bytes(&self) -> Result<Vec<u8>, postcard::Error> {
        postcard::to_allocvec(self)
    }

    /// Deserialize a sort entry from bytes.
    ///
    /// # Errors
    ///
    /// Returns an error if postcard deserialization fails.
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, postcard::Error> {
        postcard::from_bytes(bytes)
    }
}