Skip to main content

geolith_tiles_builder/raster/
template.rs

1//! XYZ/WMTS URL template expansion.
2//!
3//! Templates carry `{z}`, `{x}`, and `{y}` placeholders in any order, so
4//! both XYZ endpoints (`.../{z}/{x}/{y}.jpg`) and ArcGIS/WMTS row-major
5//! endpoints (`.../tile/{z}/{y}/{x}`) expand with the same machinery.
6
7use geolith::error::{GeolithError, Result};
8use geolith::geometry::mercator::TileCoord;
9
10/// A validated tile URL template.
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub struct UrlTemplate {
13    template: String,
14}
15
16impl UrlTemplate {
17    /// Parse and validate a template string.
18    ///
19    /// # Errors
20    ///
21    /// Returns [`GeolithError::RasterSource`] when the template is not
22    /// `http(s)://` or does not contain all of `{z}`, `{x}`, and `{y}`.
23    pub fn parse(template: &str) -> Result<Self> {
24        if !template.starts_with("http://") && !template.starts_with("https://") {
25            return Err(GeolithError::RasterSource(format!(
26                "url template must start with http:// or https://, got {template}"
27            )));
28        }
29        for placeholder in ["{z}", "{x}", "{y}"] {
30            if !template.contains(placeholder) {
31                return Err(GeolithError::RasterSource(format!(
32                    "url template is missing the {placeholder} placeholder: {template}"
33                )));
34            }
35        }
36        Ok(Self {
37            template: template.to_owned(),
38        })
39    }
40
41    /// Expand the template for one tile coordinate.
42    #[must_use]
43    pub fn expand(&self, tile: TileCoord) -> String {
44        self.template
45            .replace("{z}", &tile.z.to_string())
46            .replace("{x}", &tile.x.to_string())
47            .replace("{y}", &tile.y.to_string())
48    }
49}
50
51#[cfg(test)]
52mod tests {
53    use super::*;
54
55    #[test]
56    fn expands_arcgis_row_major_order() {
57        let t = UrlTemplate::parse("https://server.example.com/tile/{z}/{y}/{x}")
58            .expect("valid template");
59        let url = t.expand(TileCoord { z: 4, x: 11, y: 6 });
60        assert_eq!(url, "https://server.example.com/tile/4/6/11");
61        let xyz = UrlTemplate::parse("https://tiles.example.com/{z}/{x}/{y}.jpg")
62            .expect("valid template");
63        assert_eq!(
64            xyz.expand(TileCoord { z: 3, x: 5, y: 2 }),
65            "https://tiles.example.com/3/5/2.jpg"
66        );
67    }
68
69    #[test]
70    fn rejects_missing_placeholder() {
71        let err = UrlTemplate::parse("https://tiles.example.com/{z}/{x}.jpg")
72            .expect_err("missing {y} must fail");
73        assert!(format!("{err}").contains("{y}"), "names the gap: {err}");
74    }
75
76    #[test]
77    fn rejects_non_http_scheme() {
78        let err = UrlTemplate::parse("ftp://tiles.example.com/{z}/{x}/{y}.jpg")
79            .expect_err("ftp must fail");
80        assert!(
81            format!("{err}").contains("http"),
82            "names the scheme rule: {err}"
83        );
84    }
85}