mln-rs-style 0.0.21

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
//! The canonical tile id: a tile of the tile pyramid, by zoom level and
//! column and row.

// Arithmetic on the coordinates wraps, and shifts mask their count, so an id
// outside the pyramid gives a wrong id rather than a panic; `new` checks the
// id in debug builds. The derived `Ord` compares z, then x, then y.

use std::fmt;

/// Has integer z/x/y coordinates. All tiles must be derived from 0/0/0 (no
/// tiles outside of the main tile pyramid). Used for requesting data;
/// represents data tiles that exist out there. z is never larger than the
/// source's maxzoom.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, mln_wire::Wire)]
pub struct CanonicalTileID {
    pub z: u8,
    pub x: u32,
    pub y: u32,
}

impl CanonicalTileID {
    #[must_use]
    pub fn new(z: u8, x: u32, y: u32) -> Self {
        debug_assert!(z <= 32);
        debug_assert!(u64::from(x) < (1u64 << z));
        debug_assert!(u64::from(y) < (1u64 << z));
        CanonicalTileID { z, x, y }
    }

    #[must_use]
    pub fn is_child_of(&self, parent: &CanonicalTileID) -> bool {
        // Every tile is a child of 0/0/0, which a tile at z 32 couldn't shift
        // its coordinates to.
        parent.z == 0
            || (parent.z < self.z
                && parent.x == self.x.wrapping_shr(u32::from(self.z - parent.z))
                && parent.y == self.y.wrapping_shr(u32::from(self.z - parent.z)))
    }

    /// The tile at zoom level `target_z` that holds this one, or the
    /// top-left of the tiles this one holds there.
    #[must_use]
    pub fn scaled_to(&self, target_z: u8) -> CanonicalTileID {
        if target_z <= self.z {
            // parent or same
            let shift = (i32::from(self.z) - i32::from(target_z)) as u32;
            CanonicalTileID::new(target_z, self.x.wrapping_shr(shift), self.y.wrapping_shr(shift))
        } else {
            // child
            let shift = (i32::from(target_z) - i32::from(self.z)) as u32;
            CanonicalTileID::new(target_z, self.x.wrapping_shl(shift), self.y.wrapping_shl(shift))
        }
    }

    #[must_use]
    pub fn children(&self) -> [CanonicalTileID; 4] {
        let child_z = self.z.wrapping_add(1);
        let child_x = self.x.wrapping_mul(2);
        let child_y = self.y.wrapping_mul(2);
        [
            CanonicalTileID::new(child_z, child_x, child_y),
            CanonicalTileID::new(child_z, child_x, child_y.wrapping_add(1)),
            CanonicalTileID::new(child_z, child_x.wrapping_add(1), child_y),
            CanonicalTileID::new(child_z, child_x.wrapping_add(1), child_y.wrapping_add(1)),
        ]
    }
}

/// `z/x/y`.
impl fmt::Display for CanonicalTileID {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}/{}/{}", self.z, self.x, self.y)
    }
}

#[cfg(test)]
#[path = "tile_id_test.rs"]
mod tile_id_test;