s2_tilejson/
lib.rs

1#![no_std]
2#![forbid(unsafe_code)]
3#![deny(missing_docs)]
4//! The `s2-tilejson` Rust crate... TODO
5
6extern crate alloc;
7
8use alloc::{
9    borrow::ToOwned,
10    boxed::Box,
11    collections::{BTreeMap, BTreeSet},
12    format,
13    string::String,
14    vec::Vec,
15};
16pub use s2json::*;
17use serde::{Deserialize, Deserializer, Serialize, Serializer};
18
19/// Use bounds as floating point numbers for longitude and latitude
20pub type LonLatBounds = BBox<f64>;
21
22/// Use bounds as u64 for the tile index range
23pub type TileBounds = BBox<u64>;
24
25/// 1: points, 2: lines, 3: polys, 4: points3D, 5: lines3D, 6: polys3D
26#[derive(Copy, Clone, Debug, PartialEq)]
27pub enum DrawType {
28    /// Collection of points
29    Points = 1,
30    /// Collection of lines
31    Lines = 2,
32    /// Collection of polygons
33    Polygons = 3,
34    /// Collection of 3D points
35    Points3D = 4,
36    /// Collection of 3D lines
37    Lines3D = 5,
38    /// Collection of 3D polygons
39    Polygons3D = 6,
40    /// Raster data
41    Raster = 7,
42    /// Collection of points
43    Grid = 8,
44}
45impl From<DrawType> for u8 {
46    fn from(draw_type: DrawType) -> Self {
47        draw_type as u8
48    }
49}
50impl From<u8> for DrawType {
51    fn from(draw_type: u8) -> Self {
52        match draw_type {
53            2 => DrawType::Lines,
54            3 => DrawType::Polygons,
55            4 => DrawType::Points3D,
56            5 => DrawType::Lines3D,
57            6 => DrawType::Polygons3D,
58            7 => DrawType::Raster,
59            8 => DrawType::Grid,
60            _ => DrawType::Points, // 1 and default
61        }
62    }
63}
64impl Serialize for DrawType {
65    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
66    where
67        S: Serializer,
68    {
69        // Serialize as u8
70        serializer.serialize_u8(*self as u8)
71    }
72}
73
74impl<'de> Deserialize<'de> for DrawType {
75    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
76    where
77        D: Deserializer<'de>,
78    {
79        // Deserialize from u8 or string
80        let value: u8 = Deserialize::deserialize(deserializer)?;
81        match value {
82            1 => Ok(DrawType::Points),
83            2 => Ok(DrawType::Lines),
84            3 => Ok(DrawType::Polygons),
85            4 => Ok(DrawType::Points3D),
86            5 => Ok(DrawType::Lines3D),
87            6 => Ok(DrawType::Polygons3D),
88            7 => Ok(DrawType::Raster),
89            8 => Ok(DrawType::Grid),
90            _ => Err(serde::de::Error::custom(format!("unknown DrawType variant: {}", value))),
91        }
92    }
93}
94
95/// Each layer has metadata associated with it. Defined as blueprints pre-construction of vector data.
96#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)]
97pub struct LayerMetaData {
98    /// The description of the layer
99    #[serde(skip_serializing_if = "Option::is_none")]
100    pub description: Option<String>,
101    /// the lowest zoom level at which the layer is available
102    pub minzoom: u8,
103    /// the highest zoom level at which the layer is available
104    pub maxzoom: u8,
105    /// The draw types that can be found in this layer
106    pub draw_types: Vec<DrawType>,
107    /// The shape that can be found in this layer
108    pub shape: Shape,
109    /// The shape used inside features that can be found in this layer
110    #[serde(skip_serializing_if = "Option::is_none", rename = "mShape")]
111    pub m_shape: Option<Shape>,
112}
113
114/// Each layer has metadata associated with it. Defined as blueprints pre-construction of vector data.
115pub type LayersMetaData = BTreeMap<String, LayerMetaData>;
116
117/// Tilestats is simply a tracker to see where most of the tiles live
118#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)]
119pub struct TileStatsMetadata {
120    /// total number of tiles
121    #[serde(default)]
122    pub total: u64,
123    /// number of tiles for face 0
124    #[serde(rename = "0", default)]
125    pub total_0: u64,
126    /// number of tiles for face 1
127    #[serde(rename = "1", default)]
128    pub total_1: u64,
129    /// number of tiles for face 2
130    #[serde(rename = "2", default)]
131    pub total_2: u64,
132    /// number of tiles for face 3
133    #[serde(rename = "3", default)]
134    pub total_3: u64,
135    /// number of tiles for face 4
136    #[serde(rename = "4", default)]
137    pub total_4: u64,
138    /// number of tiles for face 5
139    #[serde(rename = "5", default)]
140    pub total_5: u64,
141}
142impl TileStatsMetadata {
143    /// Access the total number of tiles for a given face
144    pub fn get(&self, face: Face) -> u64 {
145        match face {
146            Face::Face0 => self.total_0,
147            Face::Face1 => self.total_1,
148            Face::Face2 => self.total_2,
149            Face::Face3 => self.total_3,
150            Face::Face4 => self.total_4,
151            Face::Face5 => self.total_5,
152        }
153    }
154
155    /// Increment the total number of tiles for a given face and also the grand total
156    pub fn increment(&mut self, face: Face) {
157        match face {
158            Face::Face0 => self.total_0 += 1,
159            Face::Face1 => self.total_1 += 1,
160            Face::Face2 => self.total_2 += 1,
161            Face::Face3 => self.total_3 += 1,
162            Face::Face4 => self.total_4 += 1,
163            Face::Face5 => self.total_5 += 1,
164        }
165        self.total += 1;
166    }
167}
168
169/// Attribution data is stored in an object.
170/// The key is the name of the attribution, and the value is the link
171pub type Attribution = BTreeMap<String, String>;
172
173/// Track the S2 tile bounds of each face and zoom
174#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)]
175pub struct FaceBounds {
176    // facesbounds[face][zoom] = [...]
177    /// Tile bounds for face 0 at each zoom
178    #[serde(rename = "0")]
179    pub face0: BTreeMap<u8, TileBounds>,
180    /// Tile bounds for face 1 at each zoom
181    #[serde(rename = "1")]
182    pub face1: BTreeMap<u8, TileBounds>,
183    /// Tile bounds for face 2 at each zoom
184    #[serde(rename = "2")]
185    pub face2: BTreeMap<u8, TileBounds>,
186    /// Tile bounds for face 3 at each zoom
187    #[serde(rename = "3")]
188    pub face3: BTreeMap<u8, TileBounds>,
189    /// Tile bounds for face 4 at each zoom
190    #[serde(rename = "4")]
191    pub face4: BTreeMap<u8, TileBounds>,
192    /// Tile bounds for face 5 at each zoom
193    #[serde(rename = "5")]
194    pub face5: BTreeMap<u8, TileBounds>,
195}
196impl FaceBounds {
197    /// Access the tile bounds for a given face and zoom
198    pub fn get(&self, face: Face) -> &BTreeMap<u8, TileBounds> {
199        match face {
200            Face::Face0 => &self.face0,
201            Face::Face1 => &self.face1,
202            Face::Face2 => &self.face2,
203            Face::Face3 => &self.face3,
204            Face::Face4 => &self.face4,
205            Face::Face5 => &self.face5,
206        }
207    }
208
209    /// Access the mutable tile bounds for a given face and zoom
210    pub fn get_mut(&mut self, face: Face) -> &mut BTreeMap<u8, TileBounds> {
211        match face {
212            Face::Face0 => &mut self.face0,
213            Face::Face1 => &mut self.face1,
214            Face::Face2 => &mut self.face2,
215            Face::Face3 => &mut self.face3,
216            Face::Face4 => &mut self.face4,
217            Face::Face5 => &mut self.face5,
218        }
219    }
220}
221
222/// Track the WM tile bounds of each zoom
223/// `[zoom: number]: BBox`
224pub type WMBounds = BTreeMap<u8, TileBounds>;
225
226/// Check the source type of the layer
227#[derive(Serialize, Debug, Default, Clone, PartialEq)]
228#[serde(rename_all = "lowercase")]
229pub enum SourceType {
230    /// Vector data
231    #[default]
232    Vector,
233    /// Json data
234    Json,
235    /// Raster data
236    Raster,
237    /// Raster DEM data
238    #[serde(rename = "raster-dem")]
239    RasterDem,
240    /// Grid data
241    Grid,
242    /// Marker data
243    Markers,
244    /// Unknown source type
245    Unknown,
246}
247impl From<&str> for SourceType {
248    fn from(source_type: &str) -> Self {
249        match source_type {
250            "vector" => SourceType::Vector,
251            "json" => SourceType::Json,
252            "raster" => SourceType::Raster,
253            "raster-dem" => SourceType::RasterDem,
254            "grid" => SourceType::Grid,
255            "markers" => SourceType::Markers,
256            _ => SourceType::Unknown,
257        }
258    }
259}
260impl<'de> Deserialize<'de> for SourceType {
261    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
262    where
263        D: Deserializer<'de>,
264    {
265        // Deserialize from a string
266        let s: String = Deserialize::deserialize(deserializer)?;
267        Ok(SourceType::from(s.as_str()))
268    }
269}
270
271/// Store the encoding of the data
272#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)]
273#[serde(rename_all = "lowercase")]
274pub enum Encoding {
275    /// No encoding
276    #[default]
277    None = 0,
278    /// Gzip encoding
279    Gzip = 1,
280    /// Brotli encoding
281    #[serde(rename = "br")]
282    Brotli = 2,
283    /// Zstd encoding
284    Zstd = 3,
285}
286impl From<u8> for Encoding {
287    fn from(encoding: u8) -> Self {
288        match encoding {
289            1 => Encoding::Gzip,
290            2 => Encoding::Brotli,
291            3 => Encoding::Zstd,
292            _ => Encoding::None,
293        }
294    }
295}
296impl From<Encoding> for u8 {
297    fn from(encoding: Encoding) -> Self {
298        match encoding {
299            Encoding::Gzip => 1,
300            Encoding::Brotli => 2,
301            Encoding::Zstd => 3,
302            Encoding::None => 0,
303        }
304    }
305}
306impl From<Encoding> for &str {
307    fn from(encoding: Encoding) -> Self {
308        match encoding {
309            Encoding::Gzip => "gzip",
310            Encoding::Brotli => "br",
311            Encoding::Zstd => "zstd",
312            Encoding::None => "none",
313        }
314    }
315}
316impl From<&str> for Encoding {
317    fn from(encoding: &str) -> Self {
318        match encoding {
319            "gzip" => Encoding::Gzip,
320            "br" => Encoding::Brotli,
321            "zstd" => Encoding::Zstd,
322            _ => Encoding::None,
323        }
324    }
325}
326
327/// Old spec tracks basic vector data
328#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)]
329pub struct VectorLayer {
330    /// The id of the layer
331    pub id: String,
332    /// The description of the layer
333    #[serde(skip_serializing_if = "Option::is_none")]
334    pub description: Option<String>,
335    /// The min zoom of the layer
336    #[serde(skip_serializing_if = "Option::is_none")]
337    pub minzoom: Option<u8>,
338    /// The max zoom of the layer
339    #[serde(skip_serializing_if = "Option::is_none")]
340    pub maxzoom: Option<u8>,
341    /// Information about each field property
342    pub fields: BTreeMap<String, String>,
343}
344
345/// Default S2 tile scheme is `fzxy`
346/// Default Web Mercator tile scheme is `xyz`
347/// Adding a t prefix to the scheme will change the request to be time sensitive
348/// TMS is an oudated version that is not supported by s2maps-gpu
349#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)]
350#[serde(rename_all = "lowercase")]
351pub enum Scheme {
352    /// The default scheme with faces (S2)
353    #[default]
354    Fzxy,
355    /// The time sensitive scheme with faces (S2)
356    Tfzxy,
357    /// The basic scheme (Web Mercator)
358    Xyz,
359    /// The time sensitive basic scheme (Web Mercator)
360    Txyz,
361    /// The TMS scheme
362    Tms,
363}
364impl From<&str> for Scheme {
365    fn from(scheme: &str) -> Self {
366        match scheme {
367            "fzxy" => Scheme::Fzxy,
368            "tfzxy" => Scheme::Tfzxy,
369            "xyz" => Scheme::Xyz,
370            "txyz" => Scheme::Txyz,
371            _ => Scheme::Tms,
372        }
373    }
374}
375impl From<Scheme> for &str {
376    fn from(scheme: Scheme) -> Self {
377        match scheme {
378            Scheme::Fzxy => "fzxy",
379            Scheme::Tfzxy => "tfzxy",
380            Scheme::Xyz => "xyz",
381            Scheme::Txyz => "txyz",
382            Scheme::Tms => "tms",
383        }
384    }
385}
386
387/// Store where the center of the data lives
388#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)]
389pub struct Center {
390    /// The longitude of the center
391    pub lon: f64,
392    /// The latitude of the center
393    pub lat: f64,
394    /// The zoom of the center
395    pub zoom: u8,
396}
397
398/// S2 TileJSON Metadata for the tile data
399#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
400pub struct Metadata {
401    /// The version of the s2-tilejson spec
402    #[serde(default)]
403    pub s2tilejson: String,
404    /// The version of the data
405    #[serde(default)]
406    pub version: String,
407    /// The name of the data
408    #[serde(default)]
409    pub name: String,
410    /// The scheme of the data
411    #[serde(default)]
412    pub scheme: Scheme,
413    /// The description of the data
414    #[serde(default)]
415    pub description: String,
416    /// The type of the data
417    #[serde(rename = "type", default)]
418    pub type_: SourceType,
419    /// The extension to use when requesting a tile
420    #[serde(default)]
421    pub extension: String,
422    /// The encoding of the data
423    #[serde(default)]
424    pub encoding: Encoding,
425    /// List of faces that have data
426    #[serde(default)]
427    pub faces: Vec<Face>,
428    /// WM Tile fetching bounds. Helpful to not make unecessary requests for tiles we know don't exist
429    #[serde(default)]
430    pub bounds: WMBounds,
431    /// S2 Tile fetching bounds. Helpful to not make unecessary requests for tiles we know don't exist
432    #[serde(default)]
433    pub facesbounds: FaceBounds,
434    /// minzoom at which to request tiles. [default=0]
435    #[serde(default)]
436    pub minzoom: u8,
437    /// maxzoom at which to request tiles. [default=27]
438    #[serde(default)]
439    pub maxzoom: u8,
440    /// The center of the data
441    #[serde(default)]
442    pub center: Center,
443    /// { ['human readable string']: 'href' }
444    #[serde(default)]
445    pub attribution: Attribution,
446    /// Track layer metadata
447    #[serde(default)]
448    pub layers: LayersMetaData,
449    /// Track tile stats for each face and total overall
450    #[serde(default)]
451    pub tilestats: TileStatsMetadata,
452    /// Old spec, track basic layer metadata
453    #[serde(default)]
454    pub vector_layers: Vec<VectorLayer>,
455}
456impl Default for Metadata {
457    fn default() -> Self {
458        Self {
459            s2tilejson: "1.0.0".into(),
460            version: "1.0.0".into(),
461            name: "default".into(),
462            scheme: Scheme::default(),
463            description: "Built with s2maps-cli".into(),
464            type_: SourceType::default(),
465            extension: "pbf".into(),
466            encoding: Encoding::default(),
467            faces: Vec::new(),
468            bounds: WMBounds::default(),
469            facesbounds: FaceBounds::default(),
470            minzoom: 0,
471            maxzoom: 27,
472            center: Center::default(),
473            attribution: BTreeMap::new(),
474            layers: LayersMetaData::default(),
475            tilestats: TileStatsMetadata::default(),
476            vector_layers: Vec::new(),
477        }
478    }
479}
480
481/// # TileJSON V3.0.0
482///
483/// ## NOTES
484/// You never have to use this. Parsing/conversion will be done for you. by using:
485///
486/// ```rs
487/// let meta: Metadata =
488///   serde_json::from_str(meta_str).unwrap_or_else(|e| panic!("ERROR: {}", e));
489/// ```
490///
491/// Represents a TileJSON metadata object for the old Mapbox spec.
492/// ## Links
493/// [TileJSON Spec](https://github.com/mapbox/tilejson-spec/blob/master/3.0.0/schema.json)
494#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
495pub struct MapboxTileJSONMetadata {
496    /// Version of the TileJSON spec used.
497    /// Matches the pattern: `\d+\.\d+\.\d+\w?[\w\d]*`.
498    pub tilejson: String,
499    /// Array of tile URL templates.
500    pub tiles: Vec<String>,
501    /// Array of vector layer metadata.
502    pub vector_layers: Vec<VectorLayer>,
503    /// Attribution string.
504    pub attribution: Option<String>,
505    /// Bounding box array [west, south, east, north].
506    pub bounds: Option<BBox>,
507    /// Center coordinate array [longitude, latitude, zoom].
508    pub center: Option<[f64; 3]>,
509    /// Array of data source URLs.
510    pub data: Option<Vec<String>>,
511    /// Description string.
512    pub description: Option<String>,
513    /// Fill zoom level. Must be between 0 and 30.
514    pub fillzoom: Option<u8>,
515    /// Array of UTFGrid URL templates.
516    pub grids: Option<Vec<String>>,
517    /// Legend of the tileset.
518    pub legend: Option<String>,
519    /// Maximum zoom level. Must be between 0 and 30.
520    pub maxzoom: Option<u8>,
521    /// Minimum zoom level. Must be between 0 and 30.
522    pub minzoom: Option<u8>,
523    /// Name of the tileset.
524    pub name: Option<String>,
525    /// Tile scheme, e.g., `xyz` or `tms`.
526    pub scheme: Option<Scheme>,
527    /// Template for interactivity.
528    pub template: Option<String>,
529    /// Version of the tileset. Matches the pattern: `\d+\.\d+\.\d+\w?[\w\d]*`.
530    pub version: Option<String>,
531}
532impl MapboxTileJSONMetadata {
533    /// Converts a MapboxTileJSONMetadata to a Metadata
534    pub fn to_metadata(&self) -> Metadata {
535        Metadata {
536            s2tilejson: "1.0.0".into(),
537            version: self.version.clone().unwrap_or("1.0.0".into()),
538            name: self.name.clone().unwrap_or("default".into()),
539            scheme: self.scheme.clone().unwrap_or_default(),
540            description: self.description.clone().unwrap_or("Built with s2maps-cli".into()),
541            type_: SourceType::default(),
542            extension: "pbf".into(),
543            faces: Vec::from([Face::Face0]),
544            bounds: WMBounds::default(),
545            facesbounds: FaceBounds::default(),
546            minzoom: self.minzoom.unwrap_or(0),
547            maxzoom: self.maxzoom.unwrap_or(27),
548            center: Center {
549                lon: self.center.unwrap_or([0.0, 0.0, 0.0])[0],
550                lat: self.center.unwrap_or([0.0, 0.0, 0.0])[1],
551                zoom: self.center.unwrap_or([0.0, 0.0, 0.0])[2] as u8,
552            },
553            attribution: BTreeMap::new(),
554            layers: LayersMetaData::default(),
555            tilestats: TileStatsMetadata::default(),
556            vector_layers: self.vector_layers.clone(),
557            encoding: Encoding::default(),
558        }
559    }
560}
561
562/// If we don't know which spec we are reading, we can treat the input as either
563#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
564#[serde(untagged)]
565pub enum UnknownMetadata {
566    /// New spec
567    Metadata(Box<Metadata>),
568    /// Old spec
569    Mapbox(Box<MapboxTileJSONMetadata>),
570}
571impl UnknownMetadata {
572    /// Converts a UnknownMetadata to a Metadata
573    pub fn to_metadata(&self) -> Metadata {
574        match self {
575            UnknownMetadata::Metadata(m) => *m.clone(),
576            UnknownMetadata::Mapbox(m) => m.to_metadata(),
577        }
578    }
579}
580
581/// Builder for the metadata
582#[derive(Debug, Clone)]
583pub struct MetadataBuilder {
584    lon_lat_bounds: LonLatBounds,
585    faces: BTreeSet<Face>,
586    metadata: Metadata,
587}
588impl Default for MetadataBuilder {
589    fn default() -> Self {
590        MetadataBuilder {
591            lon_lat_bounds: BBox {
592                left: f64::INFINITY,
593                bottom: f64::INFINITY,
594                right: -f64::INFINITY,
595                top: -f64::INFINITY,
596            },
597            faces: BTreeSet::new(),
598            metadata: Metadata { minzoom: 30, maxzoom: 0, ..Metadata::default() },
599        }
600    }
601}
602impl MetadataBuilder {
603    /// Commit the metadata and take ownership
604    pub fn commit(&mut self) -> Metadata {
605        // set the center
606        self.update_center();
607        // set the faces
608        for face in &self.faces {
609            self.metadata.faces.push(*face);
610        }
611        // return the result
612        self.metadata.to_owned()
613    }
614
615    /// Set the name
616    pub fn set_name(&mut self, name: String) {
617        self.metadata.name = name;
618    }
619
620    /// Set the scheme of the data. [default=fzxy]
621    pub fn set_scheme(&mut self, scheme: Scheme) {
622        self.metadata.scheme = scheme;
623    }
624
625    /// Set the extension of the data. [default=pbf]
626    pub fn set_extension(&mut self, extension: String) {
627        self.metadata.extension = extension;
628    }
629
630    /// Set the type of the data. [default=vector]
631    pub fn set_type(&mut self, type_: SourceType) {
632        self.metadata.type_ = type_;
633    }
634
635    /// Set the version of the data
636    pub fn set_version(&mut self, version: String) {
637        self.metadata.version = version;
638    }
639
640    /// Set the description of the data
641    pub fn set_description(&mut self, description: String) {
642        self.metadata.description = description;
643    }
644
645    /// Set the encoding of the data. [default=none]
646    pub fn set_encoding(&mut self, encoding: Encoding) {
647        self.metadata.encoding = encoding;
648    }
649
650    /// add an attribution
651    pub fn add_attribution(&mut self, display_name: &str, href: &str) {
652        self.metadata.attribution.insert(display_name.into(), href.into());
653    }
654
655    /// Add the layer metadata
656    pub fn add_layer(&mut self, name: &str, layer: &LayerMetaData) {
657        // Only insert if the key does not exist
658        if self.metadata.layers.entry(name.into()).or_insert(layer.clone()).eq(&layer) {
659            // Also add to vector_layers only if the key was not present and the insert was successful
660            self.metadata.vector_layers.push(VectorLayer {
661                id: name.into(), // No need to clone again; we use the moved value
662                description: layer.description.clone(),
663                minzoom: Some(layer.minzoom),
664                maxzoom: Some(layer.maxzoom),
665                fields: BTreeMap::new(),
666            });
667        }
668        // update minzoom and maxzoom
669        if layer.minzoom < self.metadata.minzoom {
670            self.metadata.minzoom = layer.minzoom;
671        }
672        if layer.maxzoom > self.metadata.maxzoom {
673            self.metadata.maxzoom = layer.maxzoom;
674        }
675    }
676
677    /// Add the WM tile metadata
678    pub fn add_tile_wm(&mut self, zoom: u8, x: u32, y: u32, ll_bounds: &LonLatBounds) {
679        self.metadata.tilestats.total += 1;
680        self.faces.insert(Face::Face0);
681        self.add_bounds_wm(zoom, x, y);
682        self.update_lon_lat_bounds(ll_bounds);
683    }
684
685    /// Add the S2 tile metadata
686    pub fn add_tile_s2(&mut self, face: Face, zoom: u8, x: u32, y: u32, ll_bounds: &LonLatBounds) {
687        self.metadata.tilestats.increment(face);
688        self.faces.insert(face);
689        self.add_bounds_s2(face, zoom, x, y);
690        self.update_lon_lat_bounds(ll_bounds);
691    }
692
693    /// Update the center now that all tiles have been added
694    fn update_center(&mut self) {
695        let Metadata { minzoom, maxzoom, .. } = self.metadata;
696        let BBox { left, bottom, right, top } = self.lon_lat_bounds;
697        self.metadata.center.lon = (left + right) / 2.0;
698        self.metadata.center.lat = (bottom + top) / 2.0;
699        self.metadata.center.zoom = (minzoom + maxzoom) >> 1;
700    }
701
702    /// Add the bounds of the tile for WM data
703    fn add_bounds_wm(&mut self, zoom: u8, x: u32, y: u32) {
704        let x = x as u64;
705        let y = y as u64;
706        let bbox = self.metadata.bounds.entry(zoom).or_insert(BBox {
707            left: u64::MAX,
708            bottom: u64::MAX,
709            right: 0,
710            top: 0,
711        });
712
713        bbox.left = bbox.left.min(x);
714        bbox.bottom = bbox.bottom.min(y);
715        bbox.right = bbox.right.max(x);
716        bbox.top = bbox.top.max(y);
717    }
718
719    /// Add the bounds of the tile for S2 data
720    fn add_bounds_s2(&mut self, face: Face, zoom: u8, x: u32, y: u32) {
721        let x = x as u64;
722        let y = y as u64;
723        let bbox = self.metadata.facesbounds.get_mut(face).entry(zoom).or_insert(BBox {
724            left: u64::MAX,
725            bottom: u64::MAX,
726            right: 0,
727            top: 0,
728        });
729
730        bbox.left = bbox.left.min(x);
731        bbox.bottom = bbox.bottom.min(y);
732        bbox.right = bbox.right.max(x);
733        bbox.top = bbox.top.max(y);
734    }
735
736    /// Update the lon-lat bounds so eventually we can find the center point of the data
737    fn update_lon_lat_bounds(&mut self, ll_bounds: &LonLatBounds) {
738        self.lon_lat_bounds.left = ll_bounds.left.min(self.lon_lat_bounds.left);
739        self.lon_lat_bounds.bottom = ll_bounds.bottom.min(self.lon_lat_bounds.bottom);
740        self.lon_lat_bounds.right = ll_bounds.right.max(self.lon_lat_bounds.right);
741        self.lon_lat_bounds.top = ll_bounds.top.max(self.lon_lat_bounds.top);
742    }
743}
744
745#[cfg(test)]
746mod tests {
747    use super::*;
748    use alloc::vec;
749    use s2json::{PrimitiveShape, ShapeType};
750
751    #[test]
752    fn it_works() {
753        let mut meta_builder = MetadataBuilder::default();
754
755        // on initial use be sure to update basic metadata:
756        meta_builder.set_name("OSM".into());
757        meta_builder.set_description("A free editable map of the whole world.".into());
758        meta_builder.set_version("1.0.0".into());
759        meta_builder.set_scheme("fzxy".into()); // 'fzxy' | 'tfzxy' | 'xyz' | 'txyz' | 'tms'
760        meta_builder.set_type("vector".into()); // 'vector' | 'json' | 'raster' | 'raster-dem' | 'grid' | 'markers'
761        meta_builder.set_encoding("none".into()); // 'gz' | 'br' | 'none'
762        meta_builder.set_extension("pbf".into());
763        meta_builder.add_attribution("OpenStreetMap", "https://www.openstreetmap.org/copyright/");
764
765        // Vector Specific: add layers based on how you want to parse data from a source:
766        let shape_str = r#"
767        {
768            "class": "string",
769            "offset": "f64",
770            "info": {
771                "name": "string",
772                "value": "i64"
773            }
774        }
775        "#;
776        let shape: Shape =
777            serde_json::from_str(shape_str).unwrap_or_else(|e| panic!("ERROR: {}", e));
778        let layer = LayerMetaData {
779            minzoom: 0,
780            maxzoom: 13,
781            description: Some("water_lines".into()),
782            draw_types: Vec::from(&[DrawType::Lines]),
783            shape: shape.clone(),
784            m_shape: None,
785        };
786        meta_builder.add_layer("water_lines", &layer);
787
788        // as you build tiles, add the tiles metadata:
789        // WM:
790        meta_builder.add_tile_wm(
791            0,
792            0,
793            0,
794            &LonLatBounds { left: -60.0, bottom: -20.0, right: 5.0, top: 60.0 },
795        );
796        // S2:
797        meta_builder.add_tile_s2(
798            Face::Face1,
799            5,
800            22,
801            37,
802            &LonLatBounds { left: -120.0, bottom: -7.0, right: 44.0, top: 72.0 },
803        );
804
805        // finally to get the resulting metadata:
806        let resulting_metadata: Metadata = meta_builder.commit();
807
808        assert_eq!(
809            resulting_metadata,
810            Metadata {
811                name: "OSM".into(),
812                description: "A free editable map of the whole world.".into(),
813                version: "1.0.0".into(),
814                scheme: "fzxy".into(),
815                type_: "vector".into(),
816                encoding: "none".into(),
817                extension: "pbf".into(),
818                attribution: BTreeMap::from([(
819                    "OpenStreetMap".into(),
820                    "https://www.openstreetmap.org/copyright/".into()
821                ),]),
822                bounds: BTreeMap::from([(0, TileBounds { left: 0, bottom: 0, right: 0, top: 0 }),]),
823                faces: Vec::from(&[Face::Face0, Face::Face1]),
824                facesbounds: FaceBounds {
825                    face0: BTreeMap::new(),
826                    face1: BTreeMap::from([(
827                        5,
828                        TileBounds { left: 22, bottom: 37, right: 22, top: 37 }
829                    ),]),
830                    face2: BTreeMap::new(),
831                    face3: BTreeMap::new(),
832                    face4: BTreeMap::new(),
833                    face5: BTreeMap::new(),
834                },
835                minzoom: 0,
836                maxzoom: 13,
837                center: Center { lon: -38.0, lat: 26.0, zoom: 6 },
838                tilestats: TileStatsMetadata {
839                    total: 2,
840                    total_0: 0,
841                    total_1: 1,
842                    total_2: 0,
843                    total_3: 0,
844                    total_4: 0,
845                    total_5: 0,
846                },
847                layers: BTreeMap::from([(
848                    "water_lines".into(),
849                    LayerMetaData {
850                        description: Some("water_lines".into()),
851                        minzoom: 0,
852                        maxzoom: 13,
853                        draw_types: Vec::from(&[DrawType::Lines]),
854                        shape: Shape::from([
855                            ("class".into(), ShapeType::Primitive(PrimitiveShape::String)),
856                            ("offset".into(), ShapeType::Primitive(PrimitiveShape::F64)),
857                            (
858                                "info".into(),
859                                ShapeType::Nested(Shape::from([
860                                    ("name".into(), ShapeType::Primitive(PrimitiveShape::String)),
861                                    ("value".into(), ShapeType::Primitive(PrimitiveShape::I64)),
862                                ]))
863                            ),
864                        ]),
865                        m_shape: None,
866                    }
867                )]),
868                s2tilejson: "1.0.0".into(),
869                vector_layers: Vec::from([VectorLayer {
870                    id: "water_lines".into(),
871                    description: Some("water_lines".into()),
872                    minzoom: Some(0),
873                    maxzoom: Some(13),
874                    fields: BTreeMap::new()
875                }]),
876            }
877        );
878
879        let meta_str = serde_json::to_string(&resulting_metadata).unwrap();
880
881        assert_eq!(meta_str, "{\"s2tilejson\":\"1.0.0\",\"version\":\"1.0.0\",\"name\":\"OSM\",\"scheme\":\"fzxy\",\"description\":\"A free editable map of the whole world.\",\"type\":\"vector\",\"extension\":\"pbf\",\"encoding\":\"none\",\"faces\":[0,1],\"bounds\":{\"0\":[0,0,0,0]},\"facesbounds\":{\"0\":{},\"1\":{\"5\":[22,37,22,37]},\"2\":{},\"3\":{},\"4\":{},\"5\":{}},\"minzoom\":0,\"maxzoom\":13,\"center\":{\"lon\":-38.0,\"lat\":26.0,\"zoom\":6},\"attribution\":{\"OpenStreetMap\":\"https://www.openstreetmap.org/copyright/\"},\"layers\":{\"water_lines\":{\"description\":\"water_lines\",\"minzoom\":0,\"maxzoom\":13,\"draw_types\":[2],\"shape\":{\"class\":\"string\",\"info\":{\"name\":\"string\",\"value\":\"i64\"},\"offset\":\"f64\"}}},\"tilestats\":{\"total\":2,\"0\":0,\"1\":1,\"2\":0,\"3\":0,\"4\":0,\"5\":0},\"vector_layers\":[{\"id\":\"water_lines\",\"description\":\"water_lines\",\"minzoom\":0,\"maxzoom\":13,\"fields\":{}}]}");
882
883        let meta_reparsed: Metadata =
884            serde_json::from_str(&meta_str).unwrap_or_else(|e| panic!("ERROR: {}", e));
885        assert_eq!(meta_reparsed, resulting_metadata);
886    }
887
888    #[test]
889    fn test_face() {
890        assert_eq!(Face::Face0, Face::from(0));
891        assert_eq!(Face::Face1, Face::from(1));
892        assert_eq!(Face::Face2, Face::from(2));
893        assert_eq!(Face::Face3, Face::from(3));
894        assert_eq!(Face::Face4, Face::from(4));
895        assert_eq!(Face::Face5, Face::from(5));
896
897        assert_eq!(0, u8::from(Face::Face0));
898        assert_eq!(1, u8::from(Face::Face1));
899        assert_eq!(2, u8::from(Face::Face2));
900        assert_eq!(3, u8::from(Face::Face3));
901        assert_eq!(4, u8::from(Face::Face4));
902        assert_eq!(5, u8::from(Face::Face5));
903    }
904
905    #[test]
906    fn test_bbox() {
907        let bbox: BBox = BBox { left: 0.0, bottom: 0.0, right: 0.0, top: 0.0 };
908        // serialize to JSON and back
909        let json = serde_json::to_string(&bbox).unwrap();
910        assert_eq!(json, r#"[0.0,0.0,0.0,0.0]"#);
911        let bbox2: BBox = serde_json::from_str(&json).unwrap();
912        assert_eq!(bbox, bbox2);
913    }
914
915    // TileStatsMetadata
916    #[test]
917    fn test_tilestats() {
918        let mut tilestats = TileStatsMetadata {
919            total: 2,
920            total_0: 0,
921            total_1: 1,
922            total_2: 0,
923            total_3: 0,
924            total_4: 0,
925            total_5: 0,
926        };
927        // serialize to JSON and back
928        let json = serde_json::to_string(&tilestats).unwrap();
929        assert_eq!(json, r#"{"total":2,"0":0,"1":1,"2":0,"3":0,"4":0,"5":0}"#);
930        let tilestats2: TileStatsMetadata = serde_json::from_str(&json).unwrap();
931        assert_eq!(tilestats, tilestats2);
932
933        // get0
934        assert_eq!(tilestats.get(0.into()), 0);
935        // increment0
936        tilestats.increment(0.into());
937        assert_eq!(tilestats.get(0.into()), 1);
938
939        // get 1
940        assert_eq!(tilestats.get(1.into()), 1);
941        // increment 1
942        tilestats.increment(1.into());
943        assert_eq!(tilestats.get(1.into()), 2);
944
945        // get 2
946        assert_eq!(tilestats.get(2.into()), 0);
947        // increment 2
948        tilestats.increment(2.into());
949        assert_eq!(tilestats.get(2.into()), 1);
950
951        // get 3
952        assert_eq!(tilestats.get(3.into()), 0);
953        // increment 3
954        tilestats.increment(3.into());
955        assert_eq!(tilestats.get(3.into()), 1);
956
957        // get 4
958        assert_eq!(tilestats.get(4.into()), 0);
959        // increment 4
960        tilestats.increment(4.into());
961        assert_eq!(tilestats.get(4.into()), 1);
962
963        // get 5
964        assert_eq!(tilestats.get(5.into()), 0);
965        // increment 5
966        tilestats.increment(5.into());
967        assert_eq!(tilestats.get(5.into()), 1);
968    }
969
970    // FaceBounds
971    #[test]
972    fn test_facebounds() {
973        let mut facebounds = FaceBounds::default();
974        // get mut
975        let face0 = facebounds.get_mut(0.into());
976        face0.insert(0, TileBounds { left: 0, bottom: 0, right: 0, top: 0 });
977        // get mut 1
978        let face1 = facebounds.get_mut(1.into());
979        face1.insert(0, TileBounds { left: 0, bottom: 0, right: 1, top: 1 });
980        // get mut 2
981        let face2 = facebounds.get_mut(2.into());
982        face2.insert(0, TileBounds { left: 0, bottom: 0, right: 2, top: 2 });
983        // get mut 3
984        let face3 = facebounds.get_mut(3.into());
985        face3.insert(0, TileBounds { left: 0, bottom: 0, right: 3, top: 3 });
986        // get mut 4
987        let face4 = facebounds.get_mut(4.into());
988        face4.insert(0, TileBounds { left: 0, bottom: 0, right: 4, top: 4 });
989        // get mut 5
990        let face5 = facebounds.get_mut(5.into());
991        face5.insert(0, TileBounds { left: 0, bottom: 0, right: 5, top: 5 });
992
993        // now get for all 5:
994        // get 0
995        assert_eq!(
996            facebounds.get(0.into()).get(&0).unwrap(),
997            &TileBounds { left: 0, bottom: 0, right: 0, top: 0 }
998        );
999        // get 1
1000        assert_eq!(
1001            facebounds.get(1.into()).get(&0).unwrap(),
1002            &TileBounds { left: 0, bottom: 0, right: 1, top: 1 }
1003        );
1004        // get 2
1005        assert_eq!(
1006            facebounds.get(2.into()).get(&0).unwrap(),
1007            &TileBounds { left: 0, bottom: 0, right: 2, top: 2 }
1008        );
1009        // get 3
1010        assert_eq!(
1011            facebounds.get(3.into()).get(&0).unwrap(),
1012            &TileBounds { left: 0, bottom: 0, right: 3, top: 3 }
1013        );
1014        // get 4
1015        assert_eq!(
1016            facebounds.get(4.into()).get(&0).unwrap(),
1017            &TileBounds { left: 0, bottom: 0, right: 4, top: 4 }
1018        );
1019        // get 5
1020        assert_eq!(
1021            facebounds.get(5.into()).get(&0).unwrap(),
1022            &TileBounds { left: 0, bottom: 0, right: 5, top: 5 }
1023        );
1024
1025        // serialize to JSON and back
1026        let json = serde_json::to_string(&facebounds).unwrap();
1027        assert_eq!(
1028            json,
1029            "{\"0\":{\"0\":[0,0,0,0]},\"1\":{\"0\":[0,0,1,1]},\"2\":{\"0\":[0,0,2,2]},\"3\":{\"0\"\
1030             :[0,0,3,3]},\"4\":{\"0\":[0,0,4,4]},\"5\":{\"0\":[0,0,5,5]}}"
1031        );
1032        let facebounds2 = serde_json::from_str(&json).unwrap();
1033        assert_eq!(facebounds, facebounds2);
1034    }
1035
1036    // DrawType
1037    #[test]
1038    fn test_drawtype() {
1039        assert_eq!(DrawType::from(1), DrawType::Points);
1040        assert_eq!(DrawType::from(2), DrawType::Lines);
1041        assert_eq!(DrawType::from(3), DrawType::Polygons);
1042        assert_eq!(DrawType::from(4), DrawType::Points3D);
1043        assert_eq!(DrawType::from(5), DrawType::Lines3D);
1044        assert_eq!(DrawType::from(6), DrawType::Polygons3D);
1045        assert_eq!(DrawType::from(7), DrawType::Raster);
1046        assert_eq!(DrawType::from(8), DrawType::Grid);
1047
1048        assert_eq!(1, u8::from(DrawType::Points));
1049        assert_eq!(2, u8::from(DrawType::Lines));
1050        assert_eq!(3, u8::from(DrawType::Polygons));
1051        assert_eq!(4, u8::from(DrawType::Points3D));
1052        assert_eq!(5, u8::from(DrawType::Lines3D));
1053        assert_eq!(6, u8::from(DrawType::Polygons3D));
1054        assert_eq!(7, u8::from(DrawType::Raster));
1055        assert_eq!(8, u8::from(DrawType::Grid));
1056
1057        // check json is the number value
1058        let json = serde_json::to_string(&DrawType::Points).unwrap();
1059        assert_eq!(json, "1");
1060        let drawtype: DrawType = serde_json::from_str(&json).unwrap();
1061        assert_eq!(drawtype, DrawType::Points);
1062
1063        let drawtype: DrawType = serde_json::from_str("2").unwrap();
1064        assert_eq!(drawtype, DrawType::Lines);
1065
1066        let drawtype: DrawType = serde_json::from_str("3").unwrap();
1067        assert_eq!(drawtype, DrawType::Polygons);
1068
1069        let drawtype: DrawType = serde_json::from_str("4").unwrap();
1070        assert_eq!(drawtype, DrawType::Points3D);
1071
1072        let drawtype: DrawType = serde_json::from_str("5").unwrap();
1073        assert_eq!(drawtype, DrawType::Lines3D);
1074
1075        let drawtype: DrawType = serde_json::from_str("6").unwrap();
1076        assert_eq!(drawtype, DrawType::Polygons3D);
1077
1078        let drawtype: DrawType = serde_json::from_str("7").unwrap();
1079        assert_eq!(drawtype, DrawType::Raster);
1080
1081        let drawtype: DrawType = serde_json::from_str("8").unwrap();
1082        assert_eq!(drawtype, DrawType::Grid);
1083
1084        assert!(serde_json::from_str::<DrawType>("9").is_err());
1085    }
1086
1087    // SourceType
1088    #[test]
1089    fn test_sourcetype() {
1090        // from string
1091        assert_eq!(SourceType::from("vector"), SourceType::Vector);
1092        assert_eq!(SourceType::from("json"), SourceType::Json);
1093        assert_eq!(SourceType::from("raster"), SourceType::Raster);
1094        assert_eq!(SourceType::from("raster-dem"), SourceType::RasterDem);
1095        assert_eq!(SourceType::from("grid"), SourceType::Grid);
1096        assert_eq!(SourceType::from("markers"), SourceType::Markers);
1097        assert_eq!(SourceType::from("overlay"), SourceType::Unknown);
1098
1099        // json vector
1100        let json = serde_json::to_string(&SourceType::Vector).unwrap();
1101        assert_eq!(json, "\"vector\"");
1102        let sourcetype: SourceType = serde_json::from_str(&json).unwrap();
1103        assert_eq!(sourcetype, SourceType::Vector);
1104
1105        // json json
1106        let json = serde_json::to_string(&SourceType::Json).unwrap();
1107        assert_eq!(json, "\"json\"");
1108        let sourcetype: SourceType = serde_json::from_str(&json).unwrap();
1109        assert_eq!(sourcetype, SourceType::Json);
1110
1111        // json raster
1112        let json = serde_json::to_string(&SourceType::Raster).unwrap();
1113        assert_eq!(json, "\"raster\"");
1114        let sourcetype: SourceType = serde_json::from_str(&json).unwrap();
1115        assert_eq!(sourcetype, SourceType::Raster);
1116
1117        // json raster-dem
1118        let json = serde_json::to_string(&SourceType::RasterDem).unwrap();
1119        assert_eq!(json, "\"raster-dem\"");
1120        let sourcetype: SourceType = serde_json::from_str(&json).unwrap();
1121        assert_eq!(sourcetype, SourceType::RasterDem);
1122
1123        // json grid
1124        let json = serde_json::to_string(&SourceType::Grid).unwrap();
1125        assert_eq!(json, "\"grid\"");
1126        let sourcetype: SourceType = serde_json::from_str(&json).unwrap();
1127        assert_eq!(sourcetype, SourceType::Grid);
1128
1129        // json markers
1130        let json = serde_json::to_string(&SourceType::Markers).unwrap();
1131        assert_eq!(json, "\"markers\"");
1132        let sourcetype: SourceType = serde_json::from_str(&json).unwrap();
1133        assert_eq!(sourcetype, SourceType::Markers);
1134
1135        // json unknown
1136        let json = serde_json::to_string(&SourceType::Unknown).unwrap();
1137        assert_eq!(json, "\"unknown\"");
1138        let sourcetype: SourceType = serde_json::from_str(r#""overlay""#).unwrap();
1139        assert_eq!(sourcetype, SourceType::Unknown);
1140    }
1141
1142    // Encoding
1143    #[test]
1144    fn test_encoding() {
1145        // from string
1146        assert_eq!(Encoding::from("none"), Encoding::None);
1147        assert_eq!(Encoding::from("gzip"), Encoding::Gzip);
1148        assert_eq!(Encoding::from("br"), Encoding::Brotli);
1149        assert_eq!(Encoding::from("zstd"), Encoding::Zstd);
1150
1151        // to string
1152        assert_eq!(core::convert::Into::<&str>::into(Encoding::None), "none");
1153        assert_eq!(core::convert::Into::<&str>::into(Encoding::Gzip), "gzip");
1154        assert_eq!(core::convert::Into::<&str>::into(Encoding::Brotli), "br");
1155        assert_eq!(core::convert::Into::<&str>::into(Encoding::Zstd), "zstd");
1156
1157        // from u8
1158        assert_eq!(Encoding::from(0), Encoding::None);
1159        assert_eq!(Encoding::from(1), Encoding::Gzip);
1160        assert_eq!(Encoding::from(2), Encoding::Brotli);
1161        assert_eq!(Encoding::from(3), Encoding::Zstd);
1162
1163        // to u8
1164        assert_eq!(u8::from(Encoding::None), 0);
1165        assert_eq!(u8::from(Encoding::Gzip), 1);
1166        assert_eq!(u8::from(Encoding::Brotli), 2);
1167        assert_eq!(u8::from(Encoding::Zstd), 3);
1168
1169        // json gzip
1170        let json = serde_json::to_string(&Encoding::Gzip).unwrap();
1171        assert_eq!(json, "\"gzip\"");
1172        let encoding: Encoding = serde_json::from_str(&json).unwrap();
1173        assert_eq!(encoding, Encoding::Gzip);
1174
1175        // json br
1176        let json = serde_json::to_string(&Encoding::Brotli).unwrap();
1177        assert_eq!(json, "\"br\"");
1178        let encoding: Encoding = serde_json::from_str(&json).unwrap();
1179        assert_eq!(encoding, Encoding::Brotli);
1180
1181        // json none
1182        let json = serde_json::to_string(&Encoding::None).unwrap();
1183        assert_eq!(json, "\"none\"");
1184        let encoding: Encoding = serde_json::from_str(&json).unwrap();
1185        assert_eq!(encoding, Encoding::None);
1186
1187        // json zstd
1188        let json = serde_json::to_string(&Encoding::Zstd).unwrap();
1189        assert_eq!(json, "\"zstd\"");
1190        let encoding: Encoding = serde_json::from_str(&json).unwrap();
1191        assert_eq!(encoding, Encoding::Zstd);
1192    }
1193
1194    // Scheme
1195    #[test]
1196    fn test_scheme() {
1197        // from string
1198        assert_eq!(Scheme::from("fzxy"), Scheme::Fzxy);
1199        assert_eq!(Scheme::from("tfzxy"), Scheme::Tfzxy);
1200        assert_eq!(Scheme::from("xyz"), Scheme::Xyz);
1201        assert_eq!(Scheme::from("txyz"), Scheme::Txyz);
1202        assert_eq!(Scheme::from("tms"), Scheme::Tms);
1203
1204        // to string
1205        assert_eq!(core::convert::Into::<&str>::into(Scheme::Fzxy), "fzxy");
1206        assert_eq!(core::convert::Into::<&str>::into(Scheme::Tfzxy), "tfzxy");
1207        assert_eq!(core::convert::Into::<&str>::into(Scheme::Xyz), "xyz");
1208        assert_eq!(core::convert::Into::<&str>::into(Scheme::Txyz), "txyz");
1209        assert_eq!(core::convert::Into::<&str>::into(Scheme::Tms), "tms");
1210    }
1211
1212    #[test]
1213    fn test_tippecanoe_metadata() {
1214        let meta_str = r#"{
1215            "name": "test_fixture_1.pmtiles",
1216            "description": "test_fixture_1.pmtiles",
1217            "version": "2",
1218            "type": "overlay",
1219            "generator": "tippecanoe v2.5.0",
1220            "generator_options": "./tippecanoe -zg -o test_fixture_1.pmtiles --force",
1221            "vector_layers": [
1222                {
1223                    "id": "test_fixture_1pmtiles",
1224                    "description": "",
1225                    "minzoom": 0,
1226                    "maxzoom": 0,
1227                    "fields": {}
1228                }
1229            ],
1230            "tilestats": {
1231                "layerCount": 1,
1232                "layers": [
1233                    {
1234                        "layer": "test_fixture_1pmtiles",
1235                        "count": 1,
1236                        "geometry": "Polygon",
1237                        "attributeCount": 0,
1238                        "attributes": []
1239                    }
1240                ]
1241            }
1242        }"#;
1243
1244        let _meta: Metadata =
1245            serde_json::from_str(meta_str).unwrap_or_else(|e| panic!("ERROR: {}", e));
1246    }
1247
1248    #[test]
1249    fn test_mapbox_metadata() {
1250        let meta_str = r#"{
1251            "tilejson": "3.0.0",
1252            "name": "OpenStreetMap",
1253            "description": "A free editable map of the whole world.",
1254            "version": "1.0.0",
1255            "attribution": "(c) OpenStreetMap contributors, CC-BY-SA",
1256            "scheme": "xyz",
1257            "tiles": [
1258                "https://a.tile.custom-osm-tiles.org/{z}/{x}/{y}.mvt",
1259                "https://b.tile.custom-osm-tiles.org/{z}/{x}/{y}.mvt",
1260                "https://c.tile.custom-osm-tiles.org/{z}/{x}/{y}.mvt"
1261            ],
1262            "minzoom": 0,
1263            "maxzoom": 18,
1264            "bounds": [-180, -85, 180, 85],
1265            "fillzoom": 6,
1266            "something_custom": "this is my unique field",
1267            "vector_layers": [
1268                {
1269                    "id": "telephone",
1270                    "fields": {
1271                        "phone_number": "the phone number",
1272                        "payment": "how to pay"
1273                    }
1274                },
1275                {
1276                    "id": "bicycle_parking",
1277                    "fields": {
1278                        "type": "the type of bike parking",
1279                        "year_installed": "the year the bike parking was installed"
1280                    }
1281                },
1282                {
1283                    "id": "showers",
1284                    "fields": {
1285                        "water_temperature": "the maximum water temperature",
1286                        "wear_sandles": "whether you should wear sandles or not",
1287                        "wheelchair": "is the shower wheelchair friendly?"
1288                    }
1289                }
1290            ]
1291        }"#;
1292
1293        let meta_mapbox: MapboxTileJSONMetadata =
1294            serde_json::from_str(meta_str).unwrap_or_else(|e| panic!("ERROR: {}", e));
1295        let meta_new = meta_mapbox.to_metadata();
1296        assert_eq!(
1297            meta_new,
1298            Metadata {
1299                name: "OpenStreetMap".into(),
1300                description: "A free editable map of the whole world.".into(),
1301                version: "1.0.0".into(),
1302                scheme: Scheme::Xyz,
1303                type_: "vector".into(),
1304                encoding: "none".into(),
1305                extension: "pbf".into(),
1306                attribution: BTreeMap::new(),
1307                vector_layers: meta_mapbox.vector_layers.clone(),
1308                maxzoom: 18,
1309                minzoom: 0,
1310                center: Center { lat: 0.0, lon: 0.0, zoom: 0 },
1311                bounds: WMBounds::default(),
1312                faces: vec![Face::Face0],
1313                facesbounds: FaceBounds::default(),
1314                tilestats: TileStatsMetadata::default(),
1315                layers: LayersMetaData::default(),
1316                s2tilejson: "1.0.0".into(),
1317            },
1318        );
1319
1320        let meta_mapbox_from_unknown: UnknownMetadata =
1321            serde_json::from_str(meta_str).unwrap_or_else(|e| panic!("ERROR: {}", e));
1322        let meta_new = meta_mapbox_from_unknown.to_metadata();
1323        assert_eq!(
1324            meta_new,
1325            Metadata {
1326                name: "OpenStreetMap".into(),
1327                description: "A free editable map of the whole world.".into(),
1328                version: "1.0.0".into(),
1329                scheme: Scheme::Xyz,
1330                type_: "vector".into(),
1331                encoding: "none".into(),
1332                extension: "pbf".into(),
1333                attribution: BTreeMap::new(),
1334                vector_layers: meta_mapbox.vector_layers.clone(),
1335                maxzoom: 18,
1336                minzoom: 0,
1337                center: Center { lat: 0.0, lon: 0.0, zoom: 0 },
1338                bounds: WMBounds::default(),
1339                faces: vec![Face::Face0],
1340                facesbounds: FaceBounds::default(),
1341                tilestats: TileStatsMetadata::default(),
1342                layers: LayersMetaData::default(),
1343                s2tilejson: "1.0.0".into(),
1344            },
1345        );
1346    }
1347}