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
//! XYZ/WMTS URL template expansion.
//!
//! Templates carry `{z}`, `{x}`, and `{y}` placeholders in any order, so
//! both XYZ endpoints (`.../{z}/{x}/{y}.jpg`) and ArcGIS/WMTS row-major
//! endpoints (`.../tile/{z}/{y}/{x}`) expand with the same machinery.

use geolith::error::{GeolithError, Result};
use geolith::geometry::mercator::TileCoord;

/// A validated tile URL template.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UrlTemplate {
    template: String,
}

impl UrlTemplate {
    /// Parse and validate a template string.
    ///
    /// # Errors
    ///
    /// Returns [`GeolithError::RasterSource`] when the template is not
    /// `http(s)://` or does not contain all of `{z}`, `{x}`, and `{y}`.
    pub fn parse(template: &str) -> Result<Self> {
        if !template.starts_with("http://") && !template.starts_with("https://") {
            return Err(GeolithError::RasterSource(format!(
                "url template must start with http:// or https://, got {template}"
            )));
        }
        for placeholder in ["{z}", "{x}", "{y}"] {
            if !template.contains(placeholder) {
                return Err(GeolithError::RasterSource(format!(
                    "url template is missing the {placeholder} placeholder: {template}"
                )));
            }
        }
        Ok(Self {
            template: template.to_owned(),
        })
    }

    /// Expand the template for one tile coordinate.
    #[must_use]
    pub fn expand(&self, tile: TileCoord) -> String {
        self.template
            .replace("{z}", &tile.z.to_string())
            .replace("{x}", &tile.x.to_string())
            .replace("{y}", &tile.y.to_string())
    }
}

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

    #[test]
    fn expands_arcgis_row_major_order() {
        let t = UrlTemplate::parse("https://server.example.com/tile/{z}/{y}/{x}")
            .expect("valid template");
        let url = t.expand(TileCoord { z: 4, x: 11, y: 6 });
        assert_eq!(url, "https://server.example.com/tile/4/6/11");
        let xyz = UrlTemplate::parse("https://tiles.example.com/{z}/{x}/{y}.jpg")
            .expect("valid template");
        assert_eq!(
            xyz.expand(TileCoord { z: 3, x: 5, y: 2 }),
            "https://tiles.example.com/3/5/2.jpg"
        );
    }

    #[test]
    fn rejects_missing_placeholder() {
        let err = UrlTemplate::parse("https://tiles.example.com/{z}/{x}.jpg")
            .expect_err("missing {y} must fail");
        assert!(format!("{err}").contains("{y}"), "names the gap: {err}");
    }

    #[test]
    fn rejects_non_http_scheme() {
        let err = UrlTemplate::parse("ftp://tiles.example.com/{z}/{x}/{y}.jpg")
            .expect_err("ftp must fail");
        assert!(
            format!("{err}").contains("http"),
            "names the scheme rule: {err}"
        );
    }
}