geolith 0.1.6

Shared library of the geolith builders: source readers, conflation, admin areas, tile encoding and the PMTiles and MBTiles writers
Documentation
//! Sort key encoding for external sort — `(tile_id, layer, sort_key)`.
//!
//! The sort key packs tile identity, layer ordinal, and feature ordering
//! into a single `u64` for efficient comparison during external merge sort.
//!
//! # Layout (MSB → LSB)
//!
//! ```text
//! [4 bits zoom][30 bits tile_id][5 bits layer][25 bits feature_sort]
//! ```
//!
//! - **zoom** (4 bits): 0–15 (`max_zoom=15` is the project default)
//! - **`tile_id`** (30 bits): Row-major `y * (1 << z) + x`. At z15, max value
//!   is `32768 * 32768 - 1 ≈ 1.07B`, which fits in 30 bits (max 1.07B).
//!   The previous 29-bit layout silently overflowed at z15.
//! - **layer** (5 bits): 0–31 (supports up to 31 layers for configurable schemas)
//! - **`feature_sort`** (25 bits): Biased signed value (±16M range)
//!
//! This creates a total ordering: tiles grouped together → layers within a
//! tile → features within a layer.

use crate::geometry::mercator::TileCoord;
use crate::layer::Layer;

/// Encode a tile coordinate + layer + feature sort key into a single `u64`.
///
/// Creates a total ordering where tiles are grouped together, then
/// layers within a tile, then features within a layer.
///
/// # Panics
///
/// Does not panic. Zoom values > 15 are silently masked to 4 bits.
#[inline]
#[must_use]
pub const fn encode(tile: TileCoord, layer: Layer, feature_sort: i32) -> u64 {
    let z = (tile.z as u64) & 0xF; // 4 bits (0–15)
    let tile_id = tile_xy_to_id(tile.x, tile.y, tile.z);
    let tid = tile_id & 0x3FFF_FFFF; // 30 bits
    let lay = (layer as u64) & 0x1F; // 5 bits (0–31)
    // Bias the signed sort key to unsigned for correct ordering.
    // Range: [-2^24, 2^24 - 1] → [0, 2^25 - 1]
    let fs = ((feature_sort as i64 + (1i64 << 24)) as u64) & 0x1FF_FFFF; // 25 bits

    (z << 60) | (tid << 30) | (lay << 25) | fs
}

/// Decode the zoom level and tile ID from a sort key.
///
/// Returns `(zoom, tile_id)` where `tile_id` is the row-major linear ID.
/// Use [`tile_id_to_xy()`] to convert back to `(x, y)`.
#[inline]
#[must_use]
pub const fn decode_tile_id(key: u64) -> (u8, u64) {
    let z = ((key >> 60) & 0xF) as u8;
    let tid = (key >> 30) & 0x3FFF_FFFF;
    (z, tid)
}

/// Decode the layer ordinal from a sort key.
#[inline]
#[must_use]
pub const fn decode_layer(key: u64) -> u8 {
    ((key >> 25) & 0x1F) as u8
}

/// Convert tile (x, y) to a linear tile ID using row-major order.
///
/// For a given zoom level, `tile_id = y * num_tiles + x`.
#[inline]
const fn tile_xy_to_id(x: u32, y: u32, z: u8) -> u64 {
    let n = 1u64 << z;
    (y as u64) * n + (x as u64)
}

/// Convert a linear tile ID back to (x, y) at a given zoom level.
#[inline]
#[must_use]
pub const fn tile_id_to_xy(tile_id: u64, z: u8) -> (u32, u32) {
    let n = 1u64 << z;
    let y = (tile_id / n) as u32;
    let x = (tile_id % n) as u32;
    (x, y)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn roundtrip_encoding() {
        let tile = TileCoord::new(10, 512, 340);
        let layer = Layer::Buildings;
        let sort_key = -100;

        let encoded = encode(tile, layer, sort_key);
        let (z, tid) = decode_tile_id(encoded);
        let lay = decode_layer(encoded);

        assert_eq!(z, 10);
        let (x, y) = tile_id_to_xy(tid, z);
        assert_eq!(x, 512);
        assert_eq!(y, 340);
        assert_eq!(lay, Layer::Buildings as u8);
    }

    #[test]
    fn ordering_tiles_before_layers() {
        let tile_a = TileCoord::new(5, 0, 0);
        let tile_b = TileCoord::new(5, 0, 1);

        let key_a = encode(tile_a, Layer::Water, 0);
        let key_b = encode(tile_b, Layer::Earth, 0);

        // tile_a (y=0) should sort before tile_b (y=1) regardless of layer
        assert!(key_a < key_b);
    }

    #[test]
    fn ordering_layers_within_tile() {
        let tile = TileCoord::new(5, 10, 10);

        let key_earth = encode(tile, Layer::Earth, 0);
        let key_water = encode(tile, Layer::Water, 0);
        let key_buildings = encode(tile, Layer::Buildings, 0);

        assert!(key_earth < key_water);
        assert!(key_water < key_buildings);
    }

    #[test]
    fn ordering_features_within_layer() {
        let tile = TileCoord::new(5, 10, 10);

        let key_low = encode(tile, Layer::Buildings, -100);
        let key_mid = encode(tile, Layer::Buildings, 0);
        let key_high = encode(tile, Layer::Buildings, 100);

        assert!(key_low < key_mid);
        assert!(key_mid < key_high);
    }

    #[test]
    fn z15_max_tile_id_no_overflow() {
        // At z15: max tile_id = 32768 * 32768 - 1 = 1,073,741,823
        // This needs 30 bits (2^30 = 1,073,741,824 > 1,073,741,823)
        let tile = TileCoord::new(15, 32767, 32767);
        let key = encode(tile, Layer::Earth, 0);
        let (z, tid) = decode_tile_id(key);
        assert_eq!(z, 15);
        let (x, y) = tile_id_to_xy(tid, z);
        assert_eq!(x, 32767);
        assert_eq!(y, 32767);
    }

    #[test]
    fn z15_corner_tiles_round_trip() {
        // Test all 4 corners at z15
        let corners = [(0u32, 0u32), (32767, 0), (0, 32767), (32767, 32767)];
        for (x, y) in corners {
            let tile = TileCoord::new(15, x, y);
            let key = encode(tile, Layer::Buildings, 0);
            let (z, tid) = decode_tile_id(key);
            assert_eq!(z, 15);
            let (rx, ry) = tile_id_to_xy(tid, z);
            assert_eq!(rx, x, "x mismatch for ({x},{y})");
            assert_eq!(ry, y, "y mismatch for ({x},{y})");
        }
    }

    #[test]
    fn feature_sort_range() {
        let tile = TileCoord::new(5, 0, 0);
        // Test extreme values within 25-bit biased range: ±2^24
        let key_min = encode(tile, Layer::Earth, -(1 << 24));
        let key_zero = encode(tile, Layer::Earth, 0);
        let key_max = encode(tile, Layer::Earth, (1 << 24) - 1);
        assert!(key_min < key_zero);
        assert!(key_zero < key_max);
    }

    #[test]
    fn zoom_ordering() {
        // Lower zoom should sort before higher zoom (same tile position)
        let tile_z5 = TileCoord::new(5, 0, 0);
        let tile_z10 = TileCoord::new(10, 0, 0);
        let key_z5 = encode(tile_z5, Layer::Earth, 0);
        let key_z10 = encode(tile_z10, Layer::Earth, 0);
        assert!(key_z5 < key_z10);
    }
}