Skip to main content

mln_engine/storage/
resource.rs

1use std::str::FromStr;
2use std::sync::Arc;
3use std::sync::atomic::{AtomicU32, Ordering};
4use std::time::Duration;
5
6use mln_style::crs::TileMatrixSet;
7use mln_style::string::to_string_double;
8use mln_style::tileset::Scheme;
9
10use crate::storage::chrono::Timestamp;
11use crate::storage::response::{Caching, Data, Response};
12use crate::storage::token::replace_tokens;
13use crate::text::font_stack::{FontStack, font_stack_to_string};
14
15/// Token that may appear in a tile URL template.
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17enum TileTemplateToken {
18    Z,
19    X,
20    Y,
21    Quadkey,
22    Bbox,
23    BboxEpsg3857,
24    Prefix,
25    Ratio,
26}
27
28impl FromStr for TileTemplateToken {
29    type Err = ();
30
31    fn from_str(s: &str) -> Result<Self, Self::Err> {
32        match s {
33            "z" => Ok(Self::Z),
34            "x" => Ok(Self::X),
35            "y" => Ok(Self::Y),
36            "quadkey" => Ok(Self::Quadkey),
37            "bbox" => Ok(Self::Bbox),
38            "bbox-epsg-3857" => Ok(Self::BboxEpsg3857),
39            "prefix" => Ok(Self::Prefix),
40            "ratio" => Ok(Self::Ratio),
41            _ => Err(()),
42        }
43    }
44}
45
46/// The kind of a resource. The values are stored in the offline database.
47#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
48#[repr(u8)]
49pub enum Kind {
50    Unknown = 0,
51    Style,
52    Source,
53    Tile,
54    Glyphs,
55    SpriteImage,
56    SpriteJSON,
57    Image,
58}
59
60#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
61pub enum Priority {
62    #[default]
63    Regular,
64    Low,
65}
66
67/// Where a request stands among the waiting requests of its [`Priority`]:
68/// a file source that makes requests wait starts the one with the lowest
69/// value first, and those with the same value in the order they came.
70///
71/// A clone shares the value, so whoever made a request can change where it
72/// stands while it waits, through the [`Resource`] it kept. A request that
73/// has started isn't affected.
74#[derive(Clone, Debug, Default)]
75pub struct RequestOrder(Arc<AtomicU32>);
76
77impl RequestOrder {
78    #[must_use]
79    pub fn get(&self) -> u32 {
80        self.0.load(Ordering::Relaxed)
81    }
82
83    pub(crate) fn set(&self, order: u32) {
84        self.0.store(order, Ordering::Relaxed);
85    }
86}
87
88#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
89pub enum Usage {
90    #[default]
91    Online,
92    Offline,
93}
94
95#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
96pub enum StoragePolicy {
97    #[default]
98    Permanent,
99    Volatile,
100}
101
102#[derive(Clone, Debug, PartialEq, Eq)]
103pub struct TileData {
104    pub url_template: String,
105    pub(crate) pixel_ratio: u8,
106    pub x: i32,
107    pub y: i32,
108    pub z: i8,
109    pub format: TileFormat,
110}
111
112/// What a tile's data is, which decides the media types that an HTTP
113/// request for it accepts.
114#[derive(Clone, Copy, Debug, PartialEq, Eq)]
115pub enum TileFormat {
116    /// A Mapbox Vector Tile.
117    Mvt,
118    /// A MapLibre Tile.
119    Mlt,
120    /// An image: a raster or raster-dem tile.
121    Image,
122}
123
124/// A bitmask of the ways a resource may be loaded.
125#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
126pub struct LoadingMethod(pub u8);
127
128impl LoadingMethod {
129    #[cfg(test)]
130    pub(crate) const NONE: LoadingMethod = LoadingMethod(0b00);
131    /// From the cache only.
132    pub const CACHE: LoadingMethod = LoadingMethod(0b01);
133    /// From the network only.
134    pub const NETWORK: LoadingMethod = LoadingMethod(0b10);
135    /// From the cache or the network.
136    pub const ALL: LoadingMethod = LoadingMethod(0b01 | 0b10);
137}
138
139/// A request for a resource: what to load, from where, and how.
140#[derive(Clone, Debug)]
141pub struct Resource {
142    pub kind: Kind,
143    pub loading_method: LoadingMethod,
144    pub usage: Usage,
145    pub priority: Priority,
146    /// Zero, ahead of every request that sets it, unless the requester says
147    /// otherwise.
148    pub order: RequestOrder,
149    pub url: String,
150
151    /// Includes auxiliary data if this is a tile request.
152    pub tile_data: Option<TileData>,
153
154    pub data_range: Option<(u64, u64)>,
155    /// The copy of the resource the requester has or the cache holds, which
156    /// a request revalidates: its validators and caching rules, and its data
157    /// if the requester waits for it (see [`Resource::deliver`]).
158    pub prior_modified: Option<Timestamp>,
159    pub prior_etag: Option<String>,
160    pub prior_caching: Caching,
161    pub prior_data: Option<Data>,
162    pub minimum_update_interval: Duration,
163    pub storage_policy: StoragePolicy,
164}
165
166fn quad_key(x: i32, y: i32, z: i8) -> String {
167    let mut quad_key = String::with_capacity(z.max(0) as usize);
168    let mut i = z;
169    while i > 0 {
170        let mask: i32 = 1 << (i - 1);
171        quad_key.push((b'0' + u8::from(x & mask != 0) + (if y & mask != 0 { 2 } else { 0 })) as char);
172        i -= 1;
173    }
174    quad_key
175}
176
177/// The box of the tile in column `x` and row `y`, counted from the top, at
178/// zoom `z` of `tile_matrix_set`, in its units, y up: `minX,minY,maxX,maxY`.
179fn tile_bbox_in(tile_matrix_set: &TileMatrixSet, x: i32, y: i32, z: i8) -> String {
180    let tiles = 2f64.powi(i32::from(z));
181    let tile_extent = tile_matrix_set.extent_at_zoom0 / tiles;
182    let [grid_min_x, grid_max_y] = tile_matrix_set.origin;
183    let grid_min_y = grid_max_y - tile_matrix_set.extent_at_zoom0;
184    let row_from_bottom = tiles - f64::from(y) - 1.0;
185    [
186        grid_min_x + f64::from(x) * tile_extent,
187        grid_min_y + row_from_bottom * tile_extent,
188        grid_min_x + (f64::from(x) + 1.0) * tile_extent,
189        grid_min_y + (row_from_bottom + 1.0) * tile_extent,
190    ]
191    .map(to_string_double)
192    .join(",")
193}
194
195/// How the tokens of a tile URL template address a tile: the scheme its
196/// `{y}` counts rows in, and the tile matrix set of the map's world, whose
197/// units its `{bbox}` is in. A [`Scheme`] converts to the addressing in
198/// [`TileMatrixSet::WEB_MERCATOR`], the grid of Mercator and the globe.
199#[derive(Clone, Copy, Debug, PartialEq)]
200pub struct TileAddressing {
201    pub scheme: Scheme,
202    pub tile_matrix_set: TileMatrixSet,
203}
204
205impl From<Scheme> for TileAddressing {
206    fn from(scheme: Scheme) -> Self {
207        TileAddressing { scheme, tile_matrix_set: TileMatrixSet::WEB_MERCATOR }
208    }
209}
210
211fn sprite_url(base: &str, pixel_ratio: f32, extension: &str) -> String {
212    let fragment = base.find('#').unwrap_or(base.len());
213    let query = base.find('?').filter(|&query| query < fragment);
214    let path_end = query.unwrap_or(fragment);
215    let suffix = if pixel_ratio > 1.0 { "@2x" } else { "" };
216    format!("{}{suffix}{extension}{}", &base[..path_end], query.map_or("", |query| &base[query..fragment]))
217}
218
219fn encode_font_stack(font_stack: &FontStack) -> String {
220    let hex = b"0123456789abcdef";
221    let mut encoded = String::new();
222    for byte in font_stack_to_string(font_stack).bytes() {
223        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') {
224            encoded.push(byte as char);
225        } else {
226            encoded.push('%');
227            encoded.push(hex[(byte >> 4) as usize] as char);
228            encoded.push(hex[(byte & 0x0f) as usize] as char);
229        }
230    }
231    encoded
232}
233
234impl Resource {
235    pub(crate) fn new(kind: Kind, url: impl Into<String>) -> Self {
236        Self::with_tile_data(kind, url, None, LoadingMethod::ALL)
237    }
238
239    pub(crate) fn with_tile_data(
240        kind: Kind,
241        url: impl Into<String>,
242        tile_data: Option<TileData>,
243        loading_method: LoadingMethod,
244    ) -> Self {
245        Resource {
246            kind,
247            loading_method,
248            usage: Usage::Online,
249            priority: Priority::Regular,
250            order: RequestOrder::default(),
251            url: url.into(),
252            tile_data,
253            data_range: None,
254            prior_modified: None,
255            prior_etag: None,
256            prior_caching: Caching::default(),
257            prior_data: None,
258            minimum_update_interval: Duration::ZERO,
259            storage_policy: StoragePolicy::Permanent,
260        }
261    }
262
263    /// Takes the validators and caching rules of `response`, a copy of the
264    /// resource, as the prior copy's. The requester has that copy, so no data
265    /// waits for it.
266    pub fn set_prior(&mut self, response: &Response) {
267        self.prior_data = None;
268        self.prior_modified = response.modified;
269        self.prior_etag.clone_from(&response.etag);
270        self.prior_caching = response.caching;
271    }
272
273    /// What a revalidation's answer `response` delivers: a 304 keeps the
274    /// prior copy's validators it lacks, and to a requester that waits for
275    /// that copy in `prior_data`, delivers it. Any other answer as it is.
276    #[must_use]
277    pub fn deliver(&self, mut response: Response) -> Response {
278        if !response.not_modified {
279            return response;
280        }
281        response.modified = response.modified.or(self.prior_modified);
282        if response.etag.is_none() {
283            response.etag.clone_from(&self.prior_etag);
284        }
285        if let Some(data) = &self.prior_data {
286            response.data = Some(Arc::clone(data));
287            response.not_modified = false;
288            response.prior = true;
289        }
290        response
291    }
292
293    #[cfg(any(test, feature = "sqlite"))]
294    pub(crate) fn set_priority(&mut self, p: Priority) {
295        self.priority = p;
296    }
297
298    #[cfg(feature = "sqlite")]
299    pub(crate) fn set_usage(&mut self, u: Usage) {
300        self.usage = u;
301    }
302
303    #[must_use]
304    pub fn has_loading_method(&self, method: LoadingMethod) -> bool {
305        (self.loading_method.0 & method.0) != 0
306    }
307
308    #[must_use]
309    pub fn style(url: &str) -> Resource {
310        Resource::new(Kind::Style, url)
311    }
312
313    #[must_use]
314    pub fn source(url: &str) -> Resource {
315        Resource::new(Kind::Source, url)
316    }
317
318    #[must_use]
319    pub fn image(url: &str) -> Resource {
320        Resource::new(Kind::Image, url)
321    }
322
323    #[must_use]
324    pub fn sprite_image(base: &str, pixel_ratio: f32) -> Resource {
325        Resource::new(Kind::SpriteImage, sprite_url(base, pixel_ratio, ".png"))
326    }
327
328    #[must_use]
329    pub fn sprite_json(base: &str, pixel_ratio: f32) -> Resource {
330        Resource::new(Kind::SpriteJSON, sprite_url(base, pixel_ratio, ".json"))
331    }
332
333    #[must_use]
334    pub fn glyphs(url_template: &str, font_stack: &FontStack, glyph_range: (u16, u16)) -> Resource {
335        Resource::new(
336            Kind::Glyphs,
337            replace_tokens(url_template, |token: &str| -> Option<String> {
338                if token == "fontstack" {
339                    Some(encode_font_stack(font_stack))
340                } else if token == "range" {
341                    Some(glyph_range.0.to_string() + "-" + &glyph_range.1.to_string())
342                } else {
343                    None
344                }
345            }),
346        )
347    }
348
349    #[must_use]
350    pub(crate) fn font_face(url: &str) -> Resource {
351        Resource::new(Kind::Glyphs, url)
352    }
353
354    /// The request of tile `x`, `y` at zoom `z` of a tileset whose URL
355    /// template is `url_template`. `addressing` is the tileset's
356    /// [`Scheme`], or a [`TileAddressing`] that also names the tile matrix
357    /// set of the map's world, which `{bbox}` gives the tile's box in, as
358    /// `{bbox-epsg-3857}` gives it in [`TileMatrixSet::WEB_MERCATOR`]. The
359    /// TMS scheme flips `{y}`; both boxes stay the box of the tile that `y`
360    /// names.
361    #[must_use]
362    #[expect(
363        clippy::too_many_arguments,
364        reason = "the tileset's template, the tile and its tileset's addressing and format"
365    )]
366    pub fn tile(
367        url_template: &str,
368        pixel_ratio: f32,
369        x: i32,
370        y: i32,
371        z: i8,
372        addressing: impl Into<TileAddressing>,
373        format: TileFormat,
374        loading_method: LoadingMethod,
375    ) -> Resource {
376        let TileAddressing { scheme, tile_matrix_set } = addressing.into();
377        let supports_ratio = url_template.contains("{ratio}");
378        let row = y;
379        let mut y = y;
380        if scheme == Scheme::TMS {
381            y = (1i32 << z).wrapping_sub(y).wrapping_sub(1);
382        }
383        let hex = b"0123456789abcdef";
384        let url = replace_tokens(url_template, |token: &str| -> Option<String> {
385            token.parse::<TileTemplateToken>().ok().map(|token| match token {
386                TileTemplateToken::Z => z.to_string(),
387                TileTemplateToken::X => x.to_string(),
388                TileTemplateToken::Y => y.to_string(),
389                TileTemplateToken::Quadkey => quad_key(x, y, z),
390                TileTemplateToken::Bbox => tile_bbox_in(&tile_matrix_set, x, row, z),
391                TileTemplateToken::BboxEpsg3857 => tile_bbox_in(&TileMatrixSet::WEB_MERCATOR, x, row, z),
392                TileTemplateToken::Prefix => {
393                    [hex[x.rem_euclid(16) as usize] as char, hex[y.rem_euclid(16) as usize] as char].iter().collect()
394                }
395                TileTemplateToken::Ratio => {
396                    if pixel_ratio > 1.0 {
397                        "@2x".to_owned()
398                    } else {
399                        String::new()
400                    }
401                }
402            })
403        });
404        Resource::with_tile_data(
405            Kind::Tile,
406            url,
407            Some(TileData {
408                url_template: url_template.to_owned(),
409                pixel_ratio: if supports_ratio && pixel_ratio > 1.0 { 2 } else { 1 },
410                x,
411                y,
412                z,
413                format,
414            }),
415            loading_method,
416        )
417    }
418}
419
420#[cfg(test)]
421mod tests {
422    use approx::assert_abs_diff_eq;
423
424    use super::*;
425
426    mod deliver {
427        use super::super::*;
428
429        fn at(secs: i64) -> Timestamp {
430            Timestamp::from_secs(1000 + secs)
431        }
432
433        fn waiting(caching: Caching) -> Resource {
434            let mut resource = Resource::style("https://example.com/style.json");
435            resource.prior_data = Some(Arc::new(b"cached".to_vec()));
436            resource.prior_etag = Some("a".to_owned());
437            resource.prior_caching = caching;
438            resource
439        }
440
441        #[test]
442        fn a_304_delivers_the_copy_with_its_caching_rules() {
443            let resource = waiting(Caching { expires: Some(at(-10)), ..Caching::default() });
444            let renewed = Response {
445                not_modified: true,
446                caching: Caching { expires: Some(at(100)), ..Caching::default() },
447                ..Response::default()
448            };
449            let delivered = resource.deliver(renewed);
450            assert!(!delivered.not_modified);
451            assert_eq!(Some(b"cached".as_slice()), delivered.data.as_deref().map(Vec::as_slice));
452            assert_eq!((Some(at(100)), Some("a")), (delivered.caching.expires, delivered.etag.as_deref()));
453        }
454    }
455
456    fn tile(url: &str, ratio: f32, x: i32, y: i32, z: i8, scheme: Scheme) -> Resource {
457        Resource::tile(url, ratio, x, y, z, scheme, TileFormat::Mvt, LoadingMethod::ALL)
458    }
459
460    fn check_tile(r: &Resource, url: &str, template: &str, pixel_ratio: u8, x: i32, y: i32, z: i8) {
461        assert_eq!(Kind::Tile, r.kind);
462        assert_eq!(url, r.url);
463        let tile_data = r.tile_data.as_ref().unwrap();
464        assert_eq!(template, tile_data.url_template);
465        assert_eq!(pixel_ratio, tile_data.pixel_ratio);
466        assert_eq!(x, tile_data.x);
467        assert_eq!(y, tile_data.y);
468        assert_eq!(z, tile_data.z);
469    }
470
471    // gtest: Resource.Style
472    #[test]
473    fn style() {
474        let resource = Resource::style("http://example.com");
475        assert_eq!(Kind::Style, resource.kind);
476        assert_eq!("http://example.com", resource.url);
477    }
478
479    // gtest: Resource.Source
480    #[test]
481    fn source() {
482        let resource = Resource::source("http://example.com");
483        assert_eq!(Kind::Source, resource.kind);
484        assert_eq!("http://example.com", resource.url);
485    }
486
487    // gtest: Resource.Tile
488    #[test]
489    fn tile_test() {
490        let t = "http://example.com/{z}/{x}/{y}{ratio}.png";
491        check_tile(&tile(t, 2.0, 1, 2, 3, Scheme::XYZ), "http://example.com/3/1/2@2x.png", t, 2, 1, 2, 3);
492
493        let t = "http://example.com/{prefix}/{z}/{x}/{y}.mvt";
494        check_tile(&tile(t, 2.0, 1, 2, 3, Scheme::XYZ), "http://example.com/12/3/1/2.mvt", t, 1, 1, 2, 3);
495
496        let t = "http://example.com/{quadkey}.png";
497        check_tile(&tile(t, 2.0, 0, 0, 1, Scheme::XYZ), "http://example.com/0.png", t, 1, 0, 0, 1);
498        check_tile(&tile(t, 2.0, 0, 0, 2, Scheme::XYZ), "http://example.com/00.png", t, 1, 0, 0, 2);
499        check_tile(&tile(t, 2.0, 1, 1, 2, Scheme::XYZ), "http://example.com/03.png", t, 1, 1, 1, 2);
500        check_tile(
501            &tile(t, 2.0, 22914, 52870, 17, Scheme::XYZ),
502            "http://example.com/02301322130000230.png",
503            t,
504            1,
505            22914,
506            52870,
507            17,
508        );
509        // Test case confirmed by quadkeytools package
510        check_tile(&tile(t, 2.0, 29, 3, 6, Scheme::XYZ), "http://example.com/011123.png", t, 1, 29, 3, 6);
511
512        let t = "http://example.com/?bbox={bbox-epsg-3857}";
513        check_tile(
514            &tile(t, 2.0, 0, 0, 1, Scheme::XYZ),
515            "http://example.com/?bbox=-20037508.342789244,0,0,20037508.342789244",
516            t,
517            1,
518            0,
519            0,
520            1,
521        );
522
523        let t = "http://example.com/{z}/{x}/{y}{ratio}.png";
524        check_tile(&tile(t, 1.0, 1, 2, 3, Scheme::TMS), "http://example.com/3/1/5.png", t, 1, 1, 5, 3);
525    }
526
527    #[test]
528    fn tile_bbox_matches_epsg_3857() {
529        let t = "http://example.com/?bbox={bbox}";
530        check_tile(
531            &tile(t, 1.0, 0, 0, 1, Scheme::XYZ),
532            "http://example.com/?bbox=-20037508.342789244,0,0,20037508.342789244",
533            t,
534            1,
535            0,
536            0,
537            1,
538        );
539    }
540
541    /// The URL of tile `x`, `y` at zoom `z` of `url` in the identity
542    /// projection's tile matrix set, whose root tile spans -90 to 90.
543    fn identity_tile_url(url: &str, x: i32, y: i32, z: i8, scheme: Scheme) -> String {
544        let tile_matrix_set = TileMatrixSet { origin: [-90.0, 90.0], extent_at_zoom0: 180.0 };
545        let addressing = TileAddressing { scheme, tile_matrix_set };
546        Resource::tile(url, 1.0, x, y, z, addressing, TileFormat::Image, LoadingMethod::ALL).url
547    }
548
549    // gtest: Resource.Tile, in a registered projection
550    // GL JS: CanonicalTileID .url replaces {bbox} with the tile bounds in a
551    // tile matrix set whose root tile spans -90..90.
552    // https://github.com/maplibre/maplibre-gl-js/blob/8a0091c64a25265a5c3883aeedcea96687c00d52/src/tile/tile_id.test.ts#L59-L64
553    #[test]
554    fn tile_bbox_in_a_registered_projections_tile_matrix_set() {
555        let t = "http://example.com/?bbox={bbox}";
556        assert_eq!("http://example.com/?bbox=0,0,90,90", identity_tile_url(t, 1, 0, 1, Scheme::XYZ));
557        assert_eq!("http://example.com/?bbox=-90,-90,0,0", identity_tile_url(t, 0, 1, 1, Scheme::XYZ));
558        assert_eq!("http://example.com/?bbox=45,-90,90,-45", identity_tile_url(t, 3, 3, 2, Scheme::XYZ));
559        // `{bbox-epsg-3857}` is in EPSG:3857 meters in any projection.
560        assert_eq!(
561            "http://example.com/?bbox=-20037508.342789244,0,0,20037508.342789244",
562            identity_tile_url("http://example.com/?bbox={bbox-epsg-3857}", 0, 0, 1, Scheme::XYZ)
563        );
564    }
565
566    // gtest: Resource.Tile, under the TMS scheme in a registered projection
567    // GL JS: CanonicalTileID .url keeps {bbox} on the tile the ID names under
568    // the tms scheme, which flips only {y}.
569    // https://github.com/maplibre/maplibre-gl-js/blob/8a0091c64a25265a5c3883aeedcea96687c00d52/src/tile/tile_id.test.ts#L66-L69
570    #[test]
571    fn tms_flips_only_y_and_bbox_stays_the_box_of_the_tile() {
572        let url = identity_tile_url("http://example.com/{y}?bbox={bbox}", 1, 0, 1, Scheme::TMS);
573        assert_eq!("http://example.com/1?bbox=0,0,90,90", url);
574    }
575
576    // gtest: Resource.TileBBox
577    // `{bbox}` is the tile's box in the tile matrix set of the map's world,
578    // Web Mercator's on Mercator, from the tile's own row in either scheme:
579    // each expected box is the one GL JS's `CanonicalTileID.url` makes for
580    // the same tile, scheme and tile matrix set. A box whose numbers aren't
581    // exact in binary may differ from GL JS's in its last bits, as a fused
582    // multiply-add rounds once where two operations round twice: the
583    // tolerance scales with the zoom 0 extent.
584    // https://github.com/maplibre/maplibre-gl-js/blob/8a0091c64a25265a5c3883aeedcea96687c00d52/src/tile/tile_id.ts#L41-L53
585    #[test]
586    fn tile_bbox_is_gl_jss_box() {
587        let expect_bbox = |tile_matrix_set: TileMatrixSet, (x, y, z), scheme, path: &str, box_: [f64; 4]| {
588            let addressing = TileAddressing { scheme, tile_matrix_set };
589            let template = "http://example.com/{z}/{x}/{y}?bbox={bbox}";
590            let url = Resource::tile(template, 1.0, x, y, z, addressing, TileFormat::Image, LoadingMethod::ALL).url;
591            let prefix = format!("http://example.com/{path}?bbox=");
592            let numbers = url.strip_prefix(&prefix).unwrap_or_else(|| panic!("{url}"));
593            let numbers: Vec<f64> = numbers.split(',').map(|number| number.parse().unwrap()).collect();
594            let extent = tile_matrix_set.extent_at_zoom0;
595            assert_eq!(4, numbers.len(), "{url}");
596            for (expected, actual) in box_.iter().zip(&numbers) {
597                assert_abs_diff_eq!(expected, actual, epsilon = extent * 1e-15);
598            }
599        };
600        let (xyz, tms) = (Scheme::XYZ, Scheme::TMS);
601
602        let mercator = TileMatrixSet::WEB_MERCATOR;
603        expect_bbox(mercator, (0, 0, 1), xyz, "1/0/0", [-20_037_508.342_789_244, 0.0, 0.0, 20_037_508.342_789_244]);
604        let box_ = [-9_783.939_620_502_293, 6_721_566.519_285_258, 0.0, 6_731_350.458_905_76];
605        expect_bbox(mercator, (2047, 1360, 12), xyz, "12/2047/1360", box_);
606        expect_bbox(mercator, (2047, 1360, 12), tms, "12/2047/2735", box_);
607
608        // NZTM2000Quad's corners are not whole meters.
609        let nztm2000_quad =
610            TileMatrixSet { origin: [-3_260_586.728_4, 10_438_190.165_2], extent_at_zoom0: 10_018_754.171_4 };
611        let box_ = [1_122_618.221_587_5, 4_176_468.808_075_001, 1_748_790.357_299_999_8, 4_802_640.943_787_501];
612        expect_bbox(nztm2000_quad, (7, 9, 4), xyz, "4/7/9", box_);
613        expect_bbox(nztm2000_quad, (7, 9, 4), tms, "4/7/6", box_);
614
615        // Every number here is exact in binary, so the strings are GL JS's.
616        let identity = TileMatrixSet { origin: [-90.0, 90.0], extent_at_zoom0: 180.0 };
617        let url = |tile_matrix_set, (x, y, z), scheme| {
618            let addressing = TileAddressing { scheme, tile_matrix_set };
619            let template = "http://example.com/{z}/{x}/{y}?bbox={bbox}";
620            Resource::tile(template, 1.0, x, y, z, addressing, TileFormat::Image, LoadingMethod::ALL).url
621        };
622        assert_eq!("http://example.com/1/1/0?bbox=0,0,90,90", url(identity, (1, 0, 1), xyz));
623        assert_eq!("http://example.com/1/1/1?bbox=0,0,90,90", url(identity, (1, 0, 1), tms));
624        let epsg3413 = TileMatrixSet { origin: [-4_194_304.0, 4_194_304.0], extent_at_zoom0: 8_388_608.0 };
625        assert_eq!("http://example.com/4/7/6?bbox=-524288,-1048576,0,-524288", url(epsg3413, (7, 9, 4), tms));
626    }
627
628    // gtest: Resource.Glyphs
629    #[test]
630    fn glyphs() {
631        let resource = Resource::glyphs("http://example.com/{fontstack}/{range}", &vec!["stack".to_owned()], (0, 255));
632        assert_eq!(Kind::Glyphs, resource.kind);
633        assert_eq!("http://example.com/stack/0-255", resource.url);
634
635        let resource = Resource::glyphs(
636            "http://example.com/{fontstack}/{range}",
637            &vec!["Open Sans".to_owned(), "cø".to_owned()],
638            (0, 255),
639        );
640        assert_eq!("http://example.com/Open%20Sans%2cc%c3%b8/0-255", resource.url);
641    }
642
643    // gtest: Resource.SpriteImage
644    #[test]
645    fn sprite_image() {
646        let resource = Resource::sprite_image("http://example.com/sprite", 2.0);
647        assert_eq!(Kind::SpriteImage, resource.kind);
648        assert_eq!("http://example.com/sprite@2x.png", resource.url);
649
650        let param_resource = Resource::sprite_image("http://example.com/sprite?query=true", 2.0);
651        assert_eq!(Kind::SpriteImage, param_resource.kind);
652        assert_eq!("http://example.com/sprite@2x.png?query=true", param_resource.url);
653
654        let fragment_resource = Resource::sprite_image("http://example.com/sprite?query=true#fragment", 2.0);
655        assert_eq!("http://example.com/sprite@2x.png?query=true", fragment_resource.url);
656    }
657
658    // gtest: Resource.Image
659    #[test]
660    fn image() {
661        let resource = Resource::image("http://example.com/sprite.jpg");
662        assert_eq!(Kind::Image, resource.kind);
663        assert_eq!("http://example.com/sprite.jpg", resource.url);
664    }
665
666    // gtest: Resource.SpriteJSON
667    #[test]
668    fn sprite_json() {
669        let resource = Resource::sprite_json("http://example.com/sprite", 2.0);
670        assert_eq!(Kind::SpriteJSON, resource.kind);
671        assert_eq!("http://example.com/sprite@2x.json", resource.url);
672
673        let param_resource = Resource::sprite_json("http://example.com/sprite?query=true", 2.0);
674        assert_eq!(Kind::SpriteJSON, param_resource.kind);
675        assert_eq!("http://example.com/sprite@2x.json?query=true", param_resource.url);
676
677        let fragment_resource = Resource::sprite_json("http://example.com/sprite#fragment?ignored=true", 2.0);
678        assert_eq!("http://example.com/sprite@2x.json", fragment_resource.url);
679    }
680}