use geolith::error::{GeolithError, Result};
use geolith::geometry::mercator::TileCoord;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UrlTemplate {
template: String,
}
impl UrlTemplate {
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(),
})
}
#[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}"
);
}
}