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 Attributions = 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)]
400#[serde(default)]
401pub struct Metadata {
402    /// The version of the s2-tilejson spec
403    pub s2tilejson: String,
404    /// The version of the data
405    pub version: String,
406    /// The name of the data
407    pub name: String,
408    /// The scheme of the data
409    pub scheme: Scheme,
410    /// The description of the data
411    pub description: String,
412    /// The type of the data
413    #[serde(rename = "type")]
414    pub r#type: SourceType,
415    /// The extension to use when requesting a tile
416    pub extension: String,
417    /// The encoding of the data
418    pub encoding: Encoding,
419    /// List of faces that have data
420    pub faces: Vec<Face>,
421    /// WM Tile fetching bounds. Helpful to not make unecessary requests for tiles we know don't exist
422    pub bounds: WMBounds,
423    /// S2 Tile fetching bounds. Helpful to not make unecessary requests for tiles we know don't exist
424    pub facesbounds: FaceBounds,
425    /// minzoom at which to request tiles. [default=0]
426    pub minzoom: u8,
427    /// maxzoom at which to request tiles. [default=27]
428    pub maxzoom: u8,
429    /// The center of the data
430    pub center: Center,
431    /// { ['human readable string']: 'href' }
432    pub attributions: Attributions,
433    /// Track layer metadata
434    pub layers: LayersMetaData,
435    /// Track tile stats for each face and total overall
436    pub tilestats: TileStatsMetadata,
437    /// Old spec, track basic layer metadata
438    pub vector_layers: Vec<VectorLayer>,
439}
440impl Default for Metadata {
441    fn default() -> Self {
442        Self {
443            s2tilejson: "1.0.0".into(),
444            version: "1.0.0".into(),
445            name: "default".into(),
446            scheme: Scheme::default(),
447            description: "Built with s2maps-cli".into(),
448            r#type: SourceType::default(),
449            extension: "pbf".into(),
450            encoding: Encoding::default(),
451            faces: Vec::new(),
452            bounds: WMBounds::default(),
453            facesbounds: FaceBounds::default(),
454            minzoom: 0,
455            maxzoom: 27,
456            center: Center::default(),
457            attributions: BTreeMap::new(),
458            layers: LayersMetaData::default(),
459            tilestats: TileStatsMetadata::default(),
460            vector_layers: Vec::new(),
461        }
462    }
463}
464
465/// # TileJSON V3.0.0
466///
467/// ## NOTES
468/// You never have to use this. Parsing/conversion will be done for you. by using:
469///
470/// ```rs
471/// let meta: Metadata =
472///   serde_json::from_str(meta_str).unwrap_or_else(|e| panic!("ERROR: {}", e));
473/// ```
474///
475/// Represents a TileJSON metadata object for the old Mapbox spec.
476/// ## Links
477/// [TileJSON Spec](https://github.com/mapbox/tilejson-spec/blob/master/3.0.0/schema.json)
478#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq)]
479#[serde(default)]
480pub struct MapboxTileJSONMetadata {
481    /// Version of the TileJSON spec used.
482    /// Matches the pattern: `\d+\.\d+\.\d+\w?[\w\d]*`.
483    pub tilejson: String,
484    /// Array of tile URL templates.
485    pub tiles: Vec<String>,
486    /// Array of vector layer metadata.
487    pub vector_layers: Vec<VectorLayer>,
488    /// Attribution string.
489    pub attribution: Option<String>,
490    /// Bounding box array [west, south, east, north].
491    pub bounds: Option<BBox>,
492    /// Center coordinate array [longitude, latitude, zoom].
493    pub center: Option<[f64; 3]>,
494    /// Array of data source URLs.
495    pub data: Option<Vec<String>>,
496    /// Description string.
497    pub description: Option<String>,
498    /// Fill zoom level. Must be between 0 and 30.
499    pub fillzoom: Option<u8>,
500    /// Array of UTFGrid URL templates.
501    pub grids: Option<Vec<String>>,
502    /// Legend of the tileset.
503    pub legend: Option<String>,
504    /// Maximum zoom level. Must be between 0 and 30.
505    pub maxzoom: Option<u8>,
506    /// Minimum zoom level. Must be between 0 and 30.
507    pub minzoom: Option<u8>,
508    /// Name of the tileset.
509    pub name: Option<String>,
510    /// Tile scheme, e.g., `xyz` or `tms`.
511    pub scheme: Option<Scheme>,
512    /// Template for interactivity.
513    pub template: Option<String>,
514    /// Version of the tileset. Matches the pattern: `\d+\.\d+\.\d+\w?[\w\d]*`.
515    pub version: Option<String>,
516    // NEW SPEC variables hiding here incase UnknownMetadata parses to Mapbox instead
517    /// Added type because it may be included
518    pub r#type: Option<SourceType>,
519    /// Extension of the tileset.
520    pub extension: Option<String>,
521    /// Encoding of the tileset.
522    pub encoding: Option<Encoding>,
523}
524impl MapboxTileJSONMetadata {
525    /// Converts a MapboxTileJSONMetadata to a Metadata
526    pub fn to_metadata(&self) -> Metadata {
527        Metadata {
528            s2tilejson: "1.0.0".into(),
529            version: self.version.clone().unwrap_or("1.0.0".into()),
530            name: self.name.clone().unwrap_or("default".into()),
531            scheme: self.scheme.clone().unwrap_or_default(),
532            description: self.description.clone().unwrap_or("Built with s2maps-cli".into()),
533            r#type: self.r#type.clone().unwrap_or_default(),
534            extension: self.extension.clone().unwrap_or("pbf".into()),
535            faces: Vec::from([Face::Face0]),
536            bounds: WMBounds::default(),
537            facesbounds: FaceBounds::default(),
538            minzoom: self.minzoom.unwrap_or(0),
539            maxzoom: self.maxzoom.unwrap_or(27),
540            center: Center {
541                lon: self.center.unwrap_or([0.0, 0.0, 0.0])[0],
542                lat: self.center.unwrap_or([0.0, 0.0, 0.0])[1],
543                zoom: self.center.unwrap_or([0.0, 0.0, 0.0])[2] as u8,
544            },
545            attributions: extract_link_info(self.attribution.as_ref().unwrap_or(&"".into()))
546                .unwrap_or_default(),
547            layers: LayersMetaData::default(),
548            tilestats: TileStatsMetadata::default(),
549            vector_layers: self.vector_layers.clone(),
550            encoding: self.encoding.clone().unwrap_or(Encoding::None),
551        }
552    }
553}
554
555/// If we don't know which spec we are reading, we can treat the input as either
556#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
557#[serde(untagged)]
558pub enum UnknownMetadata {
559    /// New spec
560    Metadata(Box<Metadata>),
561    /// Old spec
562    Mapbox(Box<MapboxTileJSONMetadata>),
563}
564impl UnknownMetadata {
565    /// Converts a UnknownMetadata to a Metadata
566    pub fn to_metadata(&self) -> Metadata {
567        match self {
568            UnknownMetadata::Metadata(m) => *m.clone(),
569            UnknownMetadata::Mapbox(m) => m.to_metadata(),
570        }
571    }
572}
573
574/// Builder for the metadata
575#[derive(Debug, Clone)]
576pub struct MetadataBuilder {
577    lon_lat_bounds: LonLatBounds,
578    faces: BTreeSet<Face>,
579    metadata: Metadata,
580}
581impl Default for MetadataBuilder {
582    fn default() -> Self {
583        MetadataBuilder {
584            lon_lat_bounds: BBox {
585                left: f64::INFINITY,
586                bottom: f64::INFINITY,
587                right: -f64::INFINITY,
588                top: -f64::INFINITY,
589            },
590            faces: BTreeSet::new(),
591            metadata: Metadata { minzoom: 30, maxzoom: 0, ..Metadata::default() },
592        }
593    }
594}
595impl MetadataBuilder {
596    /// Commit the metadata and take ownership
597    pub fn commit(&mut self) -> Metadata {
598        // set the center
599        self.update_center();
600        // set the faces
601        for face in &self.faces {
602            self.metadata.faces.push(*face);
603        }
604        // return the result
605        self.metadata.to_owned()
606    }
607
608    /// Set the name
609    pub fn set_name(&mut self, name: String) {
610        self.metadata.name = name;
611    }
612
613    /// Set the scheme of the data. [default=fzxy]
614    pub fn set_scheme(&mut self, scheme: Scheme) {
615        self.metadata.scheme = scheme;
616    }
617
618    /// Set the extension of the data. [default=pbf]
619    pub fn set_extension(&mut self, extension: String) {
620        self.metadata.extension = extension;
621    }
622
623    /// Set the type of the data. [default=vector]
624    pub fn set_type(&mut self, r#type: SourceType) {
625        self.metadata.r#type = r#type;
626    }
627
628    /// Set the version of the data
629    pub fn set_version(&mut self, version: String) {
630        self.metadata.version = version;
631    }
632
633    /// Set the description of the data
634    pub fn set_description(&mut self, description: String) {
635        self.metadata.description = description;
636    }
637
638    /// Set the encoding of the data. [default=none]
639    pub fn set_encoding(&mut self, encoding: Encoding) {
640        self.metadata.encoding = encoding;
641    }
642
643    /// add an attribution
644    pub fn add_attribution(&mut self, display_name: &str, href: &str) {
645        self.metadata.attributions.insert(display_name.into(), href.into());
646    }
647
648    /// Add the layer metadata
649    pub fn add_layer(&mut self, name: &str, layer: &LayerMetaData) {
650        // Only insert if the key does not exist
651        if self.metadata.layers.entry(name.into()).or_insert(layer.clone()).eq(&layer) {
652            // Also add to vector_layers only if the key was not present and the insert was successful
653            self.metadata.vector_layers.push(VectorLayer {
654                id: name.into(), // No need to clone again; we use the moved value
655                description: layer.description.clone(),
656                minzoom: Some(layer.minzoom),
657                maxzoom: Some(layer.maxzoom),
658                fields: BTreeMap::new(),
659            });
660        }
661        // update minzoom and maxzoom
662        if layer.minzoom < self.metadata.minzoom {
663            self.metadata.minzoom = layer.minzoom;
664        }
665        if layer.maxzoom > self.metadata.maxzoom {
666            self.metadata.maxzoom = layer.maxzoom;
667        }
668    }
669
670    /// Add the WM tile metadata
671    pub fn add_tile_wm(&mut self, zoom: u8, x: u32, y: u32, ll_bounds: &LonLatBounds) {
672        self.metadata.tilestats.total += 1;
673        self.faces.insert(Face::Face0);
674        self.add_bounds_wm(zoom, x, y);
675        self.update_lon_lat_bounds(ll_bounds);
676    }
677
678    /// Add the S2 tile metadata
679    pub fn add_tile_s2(&mut self, face: Face, zoom: u8, x: u32, y: u32, ll_bounds: &LonLatBounds) {
680        self.metadata.tilestats.increment(face);
681        self.faces.insert(face);
682        self.add_bounds_s2(face, zoom, x, y);
683        self.update_lon_lat_bounds(ll_bounds);
684    }
685
686    /// Update the center now that all tiles have been added
687    fn update_center(&mut self) {
688        let Metadata { minzoom, maxzoom, .. } = self.metadata;
689        let BBox { left, bottom, right, top } = self.lon_lat_bounds;
690        self.metadata.center.lon = (left + right) / 2.0;
691        self.metadata.center.lat = (bottom + top) / 2.0;
692        self.metadata.center.zoom = (minzoom + maxzoom) >> 1;
693    }
694
695    /// Add the bounds of the tile for WM data
696    fn add_bounds_wm(&mut self, zoom: u8, x: u32, y: u32) {
697        let x = x as u64;
698        let y = y as u64;
699        let bbox = self.metadata.bounds.entry(zoom).or_insert(BBox {
700            left: u64::MAX,
701            bottom: u64::MAX,
702            right: 0,
703            top: 0,
704        });
705
706        bbox.left = bbox.left.min(x);
707        bbox.bottom = bbox.bottom.min(y);
708        bbox.right = bbox.right.max(x);
709        bbox.top = bbox.top.max(y);
710    }
711
712    /// Add the bounds of the tile for S2 data
713    fn add_bounds_s2(&mut self, face: Face, zoom: u8, x: u32, y: u32) {
714        let x = x as u64;
715        let y = y as u64;
716        let bbox = self.metadata.facesbounds.get_mut(face).entry(zoom).or_insert(BBox {
717            left: u64::MAX,
718            bottom: u64::MAX,
719            right: 0,
720            top: 0,
721        });
722
723        bbox.left = bbox.left.min(x);
724        bbox.bottom = bbox.bottom.min(y);
725        bbox.right = bbox.right.max(x);
726        bbox.top = bbox.top.max(y);
727    }
728
729    /// Update the lon-lat bounds so eventually we can find the center point of the data
730    fn update_lon_lat_bounds(&mut self, ll_bounds: &LonLatBounds) {
731        self.lon_lat_bounds.left = ll_bounds.left.min(self.lon_lat_bounds.left);
732        self.lon_lat_bounds.bottom = ll_bounds.bottom.min(self.lon_lat_bounds.bottom);
733        self.lon_lat_bounds.right = ll_bounds.right.max(self.lon_lat_bounds.right);
734        self.lon_lat_bounds.top = ll_bounds.top.max(self.lon_lat_bounds.top);
735    }
736}
737
738/// Extract the link info from the HTML
739fn extract_link_info(html_string: &str) -> Option<Attributions> {
740    // Find the start and end of the 'href' attribute
741    let href_start = html_string.find("href='")?;
742    let href_value_start = href_start + "href='".len();
743    let href_end = html_string[href_value_start..].find("'")?;
744    let href_value = &html_string[href_value_start..href_value_start + href_end];
745
746    // Find the start and end of the link text
747    let text_start = html_string.find(">")?;
748    let text_value_start = text_start + 1;
749    let text_end = html_string.find("</a>")?;
750    let text_value = &html_string[text_value_start..text_end];
751
752    let mut map = BTreeMap::new();
753    map.insert(text_value.into(), href_value.into());
754
755    Some(map)
756}
757
758#[cfg(test)]
759mod tests {
760    use super::*;
761    use alloc::vec;
762    use s2json::{PrimitiveShape, ShapeType};
763
764    #[test]
765    fn it_works() {
766        let mut meta_builder = MetadataBuilder::default();
767
768        // on initial use be sure to update basic metadata:
769        meta_builder.set_name("OSM".into());
770        meta_builder.set_description("A free editable map of the whole world.".into());
771        meta_builder.set_version("1.0.0".into());
772        meta_builder.set_scheme("fzxy".into()); // 'fzxy' | 'tfzxy' | 'xyz' | 'txyz' | 'tms'
773        meta_builder.set_type("vector".into()); // 'vector' | 'json' | 'raster' | 'raster-dem' | 'grid' | 'markers'
774        meta_builder.set_encoding("none".into()); // 'gz' | 'br' | 'none'
775        meta_builder.set_extension("pbf".into());
776        meta_builder.add_attribution("OpenStreetMap", "https://www.openstreetmap.org/copyright/");
777
778        // Vector Specific: add layers based on how you want to parse data from a source:
779        let shape_str = r#"
780        {
781            "class": "string",
782            "offset": "f64",
783            "info": {
784                "name": "string",
785                "value": "i64"
786            }
787        }
788        "#;
789        let shape: Shape =
790            serde_json::from_str(shape_str).unwrap_or_else(|e| panic!("ERROR: {}", e));
791        let layer = LayerMetaData {
792            minzoom: 0,
793            maxzoom: 13,
794            description: Some("water_lines".into()),
795            draw_types: Vec::from(&[DrawType::Lines]),
796            shape: shape.clone(),
797            m_shape: None,
798        };
799        meta_builder.add_layer("water_lines", &layer);
800
801        // as you build tiles, add the tiles metadata:
802        // WM:
803        meta_builder.add_tile_wm(
804            0,
805            0,
806            0,
807            &LonLatBounds { left: -60.0, bottom: -20.0, right: 5.0, top: 60.0 },
808        );
809        // S2:
810        meta_builder.add_tile_s2(
811            Face::Face1,
812            5,
813            22,
814            37,
815            &LonLatBounds { left: -120.0, bottom: -7.0, right: 44.0, top: 72.0 },
816        );
817
818        // finally to get the resulting metadata:
819        let resulting_metadata: Metadata = meta_builder.commit();
820
821        assert_eq!(
822            resulting_metadata,
823            Metadata {
824                name: "OSM".into(),
825                description: "A free editable map of the whole world.".into(),
826                version: "1.0.0".into(),
827                scheme: "fzxy".into(),
828                r#type: "vector".into(),
829                encoding: "none".into(),
830                extension: "pbf".into(),
831                attributions: BTreeMap::from([(
832                    "OpenStreetMap".into(),
833                    "https://www.openstreetmap.org/copyright/".into()
834                ),]),
835                bounds: BTreeMap::from([(0, TileBounds { left: 0, bottom: 0, right: 0, top: 0 }),]),
836                faces: Vec::from(&[Face::Face0, Face::Face1]),
837                facesbounds: FaceBounds {
838                    face0: BTreeMap::new(),
839                    face1: BTreeMap::from([(
840                        5,
841                        TileBounds { left: 22, bottom: 37, right: 22, top: 37 }
842                    ),]),
843                    face2: BTreeMap::new(),
844                    face3: BTreeMap::new(),
845                    face4: BTreeMap::new(),
846                    face5: BTreeMap::new(),
847                },
848                minzoom: 0,
849                maxzoom: 13,
850                center: Center { lon: -38.0, lat: 26.0, zoom: 6 },
851                tilestats: TileStatsMetadata {
852                    total: 2,
853                    total_0: 0,
854                    total_1: 1,
855                    total_2: 0,
856                    total_3: 0,
857                    total_4: 0,
858                    total_5: 0,
859                },
860                layers: BTreeMap::from([(
861                    "water_lines".into(),
862                    LayerMetaData {
863                        description: Some("water_lines".into()),
864                        minzoom: 0,
865                        maxzoom: 13,
866                        draw_types: Vec::from(&[DrawType::Lines]),
867                        shape: Shape::from([
868                            ("class".into(), ShapeType::Primitive(PrimitiveShape::String)),
869                            ("offset".into(), ShapeType::Primitive(PrimitiveShape::F64)),
870                            (
871                                "info".into(),
872                                ShapeType::Nested(Shape::from([
873                                    ("name".into(), ShapeType::Primitive(PrimitiveShape::String)),
874                                    ("value".into(), ShapeType::Primitive(PrimitiveShape::I64)),
875                                ]))
876                            ),
877                        ]),
878                        m_shape: None,
879                    }
880                )]),
881                s2tilejson: "1.0.0".into(),
882                vector_layers: Vec::from([VectorLayer {
883                    id: "water_lines".into(),
884                    description: Some("water_lines".into()),
885                    minzoom: Some(0),
886                    maxzoom: Some(13),
887                    fields: BTreeMap::new()
888                }]),
889            }
890        );
891
892        let meta_str = serde_json::to_string(&resulting_metadata).unwrap();
893
894        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},\"attributions\":{\"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\":{}}]}");
895
896        let meta_reparsed: Metadata =
897            serde_json::from_str(&meta_str).unwrap_or_else(|e| panic!("ERROR: {}", e));
898        assert_eq!(meta_reparsed, resulting_metadata);
899    }
900
901    #[test]
902    fn test_face() {
903        assert_eq!(Face::Face0, Face::from(0));
904        assert_eq!(Face::Face1, Face::from(1));
905        assert_eq!(Face::Face2, Face::from(2));
906        assert_eq!(Face::Face3, Face::from(3));
907        assert_eq!(Face::Face4, Face::from(4));
908        assert_eq!(Face::Face5, Face::from(5));
909
910        assert_eq!(0, u8::from(Face::Face0));
911        assert_eq!(1, u8::from(Face::Face1));
912        assert_eq!(2, u8::from(Face::Face2));
913        assert_eq!(3, u8::from(Face::Face3));
914        assert_eq!(4, u8::from(Face::Face4));
915        assert_eq!(5, u8::from(Face::Face5));
916    }
917
918    #[test]
919    fn test_bbox() {
920        let bbox: BBox = BBox { left: 0.0, bottom: 0.0, right: 0.0, top: 0.0 };
921        // serialize to JSON and back
922        let json = serde_json::to_string(&bbox).unwrap();
923        assert_eq!(json, r#"[0.0,0.0,0.0,0.0]"#);
924        let bbox2: BBox = serde_json::from_str(&json).unwrap();
925        assert_eq!(bbox, bbox2);
926    }
927
928    // TileStatsMetadata
929    #[test]
930    fn test_tilestats() {
931        let mut tilestats = TileStatsMetadata {
932            total: 2,
933            total_0: 0,
934            total_1: 1,
935            total_2: 0,
936            total_3: 0,
937            total_4: 0,
938            total_5: 0,
939        };
940        // serialize to JSON and back
941        let json = serde_json::to_string(&tilestats).unwrap();
942        assert_eq!(json, r#"{"total":2,"0":0,"1":1,"2":0,"3":0,"4":0,"5":0}"#);
943        let tilestats2: TileStatsMetadata = serde_json::from_str(&json).unwrap();
944        assert_eq!(tilestats, tilestats2);
945
946        // get0
947        assert_eq!(tilestats.get(0.into()), 0);
948        // increment0
949        tilestats.increment(0.into());
950        assert_eq!(tilestats.get(0.into()), 1);
951
952        // get 1
953        assert_eq!(tilestats.get(1.into()), 1);
954        // increment 1
955        tilestats.increment(1.into());
956        assert_eq!(tilestats.get(1.into()), 2);
957
958        // get 2
959        assert_eq!(tilestats.get(2.into()), 0);
960        // increment 2
961        tilestats.increment(2.into());
962        assert_eq!(tilestats.get(2.into()), 1);
963
964        // get 3
965        assert_eq!(tilestats.get(3.into()), 0);
966        // increment 3
967        tilestats.increment(3.into());
968        assert_eq!(tilestats.get(3.into()), 1);
969
970        // get 4
971        assert_eq!(tilestats.get(4.into()), 0);
972        // increment 4
973        tilestats.increment(4.into());
974        assert_eq!(tilestats.get(4.into()), 1);
975
976        // get 5
977        assert_eq!(tilestats.get(5.into()), 0);
978        // increment 5
979        tilestats.increment(5.into());
980        assert_eq!(tilestats.get(5.into()), 1);
981    }
982
983    // FaceBounds
984    #[test]
985    fn test_facebounds() {
986        let mut facebounds = FaceBounds::default();
987        // get mut
988        let face0 = facebounds.get_mut(0.into());
989        face0.insert(0, TileBounds { left: 0, bottom: 0, right: 0, top: 0 });
990        // get mut 1
991        let face1 = facebounds.get_mut(1.into());
992        face1.insert(0, TileBounds { left: 0, bottom: 0, right: 1, top: 1 });
993        // get mut 2
994        let face2 = facebounds.get_mut(2.into());
995        face2.insert(0, TileBounds { left: 0, bottom: 0, right: 2, top: 2 });
996        // get mut 3
997        let face3 = facebounds.get_mut(3.into());
998        face3.insert(0, TileBounds { left: 0, bottom: 0, right: 3, top: 3 });
999        // get mut 4
1000        let face4 = facebounds.get_mut(4.into());
1001        face4.insert(0, TileBounds { left: 0, bottom: 0, right: 4, top: 4 });
1002        // get mut 5
1003        let face5 = facebounds.get_mut(5.into());
1004        face5.insert(0, TileBounds { left: 0, bottom: 0, right: 5, top: 5 });
1005
1006        // now get for all 5:
1007        // get 0
1008        assert_eq!(
1009            facebounds.get(0.into()).get(&0).unwrap(),
1010            &TileBounds { left: 0, bottom: 0, right: 0, top: 0 }
1011        );
1012        // get 1
1013        assert_eq!(
1014            facebounds.get(1.into()).get(&0).unwrap(),
1015            &TileBounds { left: 0, bottom: 0, right: 1, top: 1 }
1016        );
1017        // get 2
1018        assert_eq!(
1019            facebounds.get(2.into()).get(&0).unwrap(),
1020            &TileBounds { left: 0, bottom: 0, right: 2, top: 2 }
1021        );
1022        // get 3
1023        assert_eq!(
1024            facebounds.get(3.into()).get(&0).unwrap(),
1025            &TileBounds { left: 0, bottom: 0, right: 3, top: 3 }
1026        );
1027        // get 4
1028        assert_eq!(
1029            facebounds.get(4.into()).get(&0).unwrap(),
1030            &TileBounds { left: 0, bottom: 0, right: 4, top: 4 }
1031        );
1032        // get 5
1033        assert_eq!(
1034            facebounds.get(5.into()).get(&0).unwrap(),
1035            &TileBounds { left: 0, bottom: 0, right: 5, top: 5 }
1036        );
1037
1038        // serialize to JSON and back
1039        let json = serde_json::to_string(&facebounds).unwrap();
1040        assert_eq!(
1041            json,
1042            "{\"0\":{\"0\":[0,0,0,0]},\"1\":{\"0\":[0,0,1,1]},\"2\":{\"0\":[0,0,2,2]},\"3\":{\"0\"\
1043             :[0,0,3,3]},\"4\":{\"0\":[0,0,4,4]},\"5\":{\"0\":[0,0,5,5]}}"
1044        );
1045        let facebounds2 = serde_json::from_str(&json).unwrap();
1046        assert_eq!(facebounds, facebounds2);
1047    }
1048
1049    // DrawType
1050    #[test]
1051    fn test_drawtype() {
1052        assert_eq!(DrawType::from(1), DrawType::Points);
1053        assert_eq!(DrawType::from(2), DrawType::Lines);
1054        assert_eq!(DrawType::from(3), DrawType::Polygons);
1055        assert_eq!(DrawType::from(4), DrawType::Points3D);
1056        assert_eq!(DrawType::from(5), DrawType::Lines3D);
1057        assert_eq!(DrawType::from(6), DrawType::Polygons3D);
1058        assert_eq!(DrawType::from(7), DrawType::Raster);
1059        assert_eq!(DrawType::from(8), DrawType::Grid);
1060
1061        assert_eq!(1, u8::from(DrawType::Points));
1062        assert_eq!(2, u8::from(DrawType::Lines));
1063        assert_eq!(3, u8::from(DrawType::Polygons));
1064        assert_eq!(4, u8::from(DrawType::Points3D));
1065        assert_eq!(5, u8::from(DrawType::Lines3D));
1066        assert_eq!(6, u8::from(DrawType::Polygons3D));
1067        assert_eq!(7, u8::from(DrawType::Raster));
1068        assert_eq!(8, u8::from(DrawType::Grid));
1069
1070        // check json is the number value
1071        let json = serde_json::to_string(&DrawType::Points).unwrap();
1072        assert_eq!(json, "1");
1073        let drawtype: DrawType = serde_json::from_str(&json).unwrap();
1074        assert_eq!(drawtype, DrawType::Points);
1075
1076        let drawtype: DrawType = serde_json::from_str("2").unwrap();
1077        assert_eq!(drawtype, DrawType::Lines);
1078
1079        let drawtype: DrawType = serde_json::from_str("3").unwrap();
1080        assert_eq!(drawtype, DrawType::Polygons);
1081
1082        let drawtype: DrawType = serde_json::from_str("4").unwrap();
1083        assert_eq!(drawtype, DrawType::Points3D);
1084
1085        let drawtype: DrawType = serde_json::from_str("5").unwrap();
1086        assert_eq!(drawtype, DrawType::Lines3D);
1087
1088        let drawtype: DrawType = serde_json::from_str("6").unwrap();
1089        assert_eq!(drawtype, DrawType::Polygons3D);
1090
1091        let drawtype: DrawType = serde_json::from_str("7").unwrap();
1092        assert_eq!(drawtype, DrawType::Raster);
1093
1094        let drawtype: DrawType = serde_json::from_str("8").unwrap();
1095        assert_eq!(drawtype, DrawType::Grid);
1096
1097        assert!(serde_json::from_str::<DrawType>("9").is_err());
1098    }
1099
1100    // SourceType
1101    #[test]
1102    fn test_sourcetype() {
1103        // from string
1104        assert_eq!(SourceType::from("vector"), SourceType::Vector);
1105        assert_eq!(SourceType::from("json"), SourceType::Json);
1106        assert_eq!(SourceType::from("raster"), SourceType::Raster);
1107        assert_eq!(SourceType::from("raster-dem"), SourceType::RasterDem);
1108        assert_eq!(SourceType::from("grid"), SourceType::Grid);
1109        assert_eq!(SourceType::from("markers"), SourceType::Markers);
1110        assert_eq!(SourceType::from("overlay"), SourceType::Unknown);
1111
1112        // json vector
1113        let json = serde_json::to_string(&SourceType::Vector).unwrap();
1114        assert_eq!(json, "\"vector\"");
1115        let sourcetype: SourceType = serde_json::from_str(&json).unwrap();
1116        assert_eq!(sourcetype, SourceType::Vector);
1117
1118        // json json
1119        let json = serde_json::to_string(&SourceType::Json).unwrap();
1120        assert_eq!(json, "\"json\"");
1121        let sourcetype: SourceType = serde_json::from_str(&json).unwrap();
1122        assert_eq!(sourcetype, SourceType::Json);
1123
1124        // json raster
1125        let json = serde_json::to_string(&SourceType::Raster).unwrap();
1126        assert_eq!(json, "\"raster\"");
1127        let sourcetype: SourceType = serde_json::from_str(&json).unwrap();
1128        assert_eq!(sourcetype, SourceType::Raster);
1129
1130        // json raster-dem
1131        let json = serde_json::to_string(&SourceType::RasterDem).unwrap();
1132        assert_eq!(json, "\"raster-dem\"");
1133        let sourcetype: SourceType = serde_json::from_str(&json).unwrap();
1134        assert_eq!(sourcetype, SourceType::RasterDem);
1135
1136        // json grid
1137        let json = serde_json::to_string(&SourceType::Grid).unwrap();
1138        assert_eq!(json, "\"grid\"");
1139        let sourcetype: SourceType = serde_json::from_str(&json).unwrap();
1140        assert_eq!(sourcetype, SourceType::Grid);
1141
1142        // json markers
1143        let json = serde_json::to_string(&SourceType::Markers).unwrap();
1144        assert_eq!(json, "\"markers\"");
1145        let sourcetype: SourceType = serde_json::from_str(&json).unwrap();
1146        assert_eq!(sourcetype, SourceType::Markers);
1147
1148        // json unknown
1149        let json = serde_json::to_string(&SourceType::Unknown).unwrap();
1150        assert_eq!(json, "\"unknown\"");
1151        let sourcetype: SourceType = serde_json::from_str(r#""overlay""#).unwrap();
1152        assert_eq!(sourcetype, SourceType::Unknown);
1153    }
1154
1155    // Encoding
1156    #[test]
1157    fn test_encoding() {
1158        // from string
1159        assert_eq!(Encoding::from("none"), Encoding::None);
1160        assert_eq!(Encoding::from("gzip"), Encoding::Gzip);
1161        assert_eq!(Encoding::from("br"), Encoding::Brotli);
1162        assert_eq!(Encoding::from("zstd"), Encoding::Zstd);
1163
1164        // to string
1165        assert_eq!(core::convert::Into::<&str>::into(Encoding::None), "none");
1166        assert_eq!(core::convert::Into::<&str>::into(Encoding::Gzip), "gzip");
1167        assert_eq!(core::convert::Into::<&str>::into(Encoding::Brotli), "br");
1168        assert_eq!(core::convert::Into::<&str>::into(Encoding::Zstd), "zstd");
1169
1170        // from u8
1171        assert_eq!(Encoding::from(0), Encoding::None);
1172        assert_eq!(Encoding::from(1), Encoding::Gzip);
1173        assert_eq!(Encoding::from(2), Encoding::Brotli);
1174        assert_eq!(Encoding::from(3), Encoding::Zstd);
1175
1176        // to u8
1177        assert_eq!(u8::from(Encoding::None), 0);
1178        assert_eq!(u8::from(Encoding::Gzip), 1);
1179        assert_eq!(u8::from(Encoding::Brotli), 2);
1180        assert_eq!(u8::from(Encoding::Zstd), 3);
1181
1182        // json gzip
1183        let json = serde_json::to_string(&Encoding::Gzip).unwrap();
1184        assert_eq!(json, "\"gzip\"");
1185        let encoding: Encoding = serde_json::from_str(&json).unwrap();
1186        assert_eq!(encoding, Encoding::Gzip);
1187
1188        // json br
1189        let json = serde_json::to_string(&Encoding::Brotli).unwrap();
1190        assert_eq!(json, "\"br\"");
1191        let encoding: Encoding = serde_json::from_str(&json).unwrap();
1192        assert_eq!(encoding, Encoding::Brotli);
1193
1194        // json none
1195        let json = serde_json::to_string(&Encoding::None).unwrap();
1196        assert_eq!(json, "\"none\"");
1197        let encoding: Encoding = serde_json::from_str(&json).unwrap();
1198        assert_eq!(encoding, Encoding::None);
1199
1200        // json zstd
1201        let json = serde_json::to_string(&Encoding::Zstd).unwrap();
1202        assert_eq!(json, "\"zstd\"");
1203        let encoding: Encoding = serde_json::from_str(&json).unwrap();
1204        assert_eq!(encoding, Encoding::Zstd);
1205    }
1206
1207    // Scheme
1208    #[test]
1209    fn test_scheme() {
1210        // from string
1211        assert_eq!(Scheme::from("fzxy"), Scheme::Fzxy);
1212        assert_eq!(Scheme::from("tfzxy"), Scheme::Tfzxy);
1213        assert_eq!(Scheme::from("xyz"), Scheme::Xyz);
1214        assert_eq!(Scheme::from("txyz"), Scheme::Txyz);
1215        assert_eq!(Scheme::from("tms"), Scheme::Tms);
1216
1217        // to string
1218        assert_eq!(core::convert::Into::<&str>::into(Scheme::Fzxy), "fzxy");
1219        assert_eq!(core::convert::Into::<&str>::into(Scheme::Tfzxy), "tfzxy");
1220        assert_eq!(core::convert::Into::<&str>::into(Scheme::Xyz), "xyz");
1221        assert_eq!(core::convert::Into::<&str>::into(Scheme::Txyz), "txyz");
1222        assert_eq!(core::convert::Into::<&str>::into(Scheme::Tms), "tms");
1223    }
1224
1225    #[test]
1226    fn test_tippecanoe_metadata() {
1227        let meta_str = r#"{
1228            "name": "test_fixture_1.pmtiles",
1229            "description": "test_fixture_1.pmtiles",
1230            "version": "2",
1231            "type": "overlay",
1232            "generator": "tippecanoe v2.5.0",
1233            "generator_options": "./tippecanoe -zg -o test_fixture_1.pmtiles --force",
1234            "vector_layers": [
1235                {
1236                    "id": "test_fixture_1pmtiles",
1237                    "description": "",
1238                    "minzoom": 0,
1239                    "maxzoom": 0,
1240                    "fields": {}
1241                }
1242            ],
1243            "tilestats": {
1244                "layerCount": 1,
1245                "layers": [
1246                    {
1247                        "layer": "test_fixture_1pmtiles",
1248                        "count": 1,
1249                        "geometry": "Polygon",
1250                        "attributeCount": 0,
1251                        "attributes": []
1252                    }
1253                ]
1254            }
1255        }"#;
1256
1257        let _meta: Metadata =
1258            serde_json::from_str(meta_str).unwrap_or_else(|e| panic!("ERROR: {}", e));
1259    }
1260
1261    #[test]
1262    fn test_mapbox_metadata() {
1263        let meta_str = r#"{
1264            "tilejson": "3.0.0",
1265            "name": "OpenStreetMap",
1266            "description": "A free editable map of the whole world.",
1267            "version": "1.0.0",
1268            "attribution": "<a href='https://openstreetmap.org'>OSM contributors</a>",
1269            "scheme": "xyz",
1270            "tiles": [
1271                "https://a.tile.custom-osm-tiles.org/{z}/{x}/{y}.mvt",
1272                "https://b.tile.custom-osm-tiles.org/{z}/{x}/{y}.mvt",
1273                "https://c.tile.custom-osm-tiles.org/{z}/{x}/{y}.mvt"
1274            ],
1275            "minzoom": 0,
1276            "maxzoom": 18,
1277            "bounds": [-180, -85, 180, 85],
1278            "fillzoom": 6,
1279            "something_custom": "this is my unique field",
1280            "vector_layers": [
1281                {
1282                    "id": "telephone",
1283                    "fields": {
1284                        "phone_number": "the phone number",
1285                        "payment": "how to pay"
1286                    }
1287                },
1288                {
1289                    "id": "bicycle_parking",
1290                    "fields": {
1291                        "type": "the type of bike parking",
1292                        "year_installed": "the year the bike parking was installed"
1293                    }
1294                },
1295                {
1296                    "id": "showers",
1297                    "fields": {
1298                        "water_temperature": "the maximum water temperature",
1299                        "wear_sandles": "whether you should wear sandles or not",
1300                        "wheelchair": "is the shower wheelchair friendly?"
1301                    }
1302                }
1303            ]
1304        }"#;
1305
1306        let meta_mapbox: MapboxTileJSONMetadata =
1307            serde_json::from_str(meta_str).unwrap_or_else(|e| panic!("ERROR: {}", e));
1308        let meta_new = meta_mapbox.to_metadata();
1309        assert_eq!(
1310            meta_new,
1311            Metadata {
1312                name: "OpenStreetMap".into(),
1313                description: "A free editable map of the whole world.".into(),
1314                version: "1.0.0".into(),
1315                scheme: Scheme::Xyz,
1316                r#type: "vector".into(),
1317                encoding: "none".into(),
1318                extension: "pbf".into(),
1319                attributions: BTreeMap::from([(
1320                    "OSM contributors".into(),
1321                    "https://openstreetmap.org".into()
1322                )]),
1323                vector_layers: meta_mapbox.vector_layers.clone(),
1324                maxzoom: 18,
1325                minzoom: 0,
1326                center: Center { lat: 0.0, lon: 0.0, zoom: 0 },
1327                bounds: WMBounds::default(),
1328                faces: vec![Face::Face0],
1329                facesbounds: FaceBounds::default(),
1330                tilestats: TileStatsMetadata::default(),
1331                layers: LayersMetaData::default(),
1332                s2tilejson: "1.0.0".into(),
1333            },
1334        );
1335
1336        let meta_mapbox_from_unknown: UnknownMetadata =
1337            serde_json::from_str(meta_str).unwrap_or_else(|e| panic!("ERROR: {}", e));
1338        let meta_new = meta_mapbox_from_unknown.to_metadata();
1339        assert_eq!(
1340            meta_new,
1341            Metadata {
1342                name: "OpenStreetMap".into(),
1343                description: "A free editable map of the whole world.".into(),
1344                version: "1.0.0".into(),
1345                scheme: Scheme::Xyz,
1346                r#type: "vector".into(),
1347                encoding: "none".into(),
1348                extension: "pbf".into(),
1349                attributions: BTreeMap::from([(
1350                    "OSM contributors".into(),
1351                    "https://openstreetmap.org".into()
1352                )]),
1353                vector_layers: meta_mapbox.vector_layers.clone(),
1354                maxzoom: 18,
1355                minzoom: 0,
1356                center: Center { lat: 0.0, lon: 0.0, zoom: 0 },
1357                bounds: WMBounds::default(),
1358                faces: vec![Face::Face0],
1359                facesbounds: FaceBounds::default(),
1360                tilestats: TileStatsMetadata::default(),
1361                layers: LayersMetaData::default(),
1362                s2tilejson: "1.0.0".into(),
1363            },
1364        );
1365    }
1366
1367    #[test]
1368    fn test_malformed_metadata() {
1369        let meta_str = r#"{
1370            "s2tilejson": "1.0.0",
1371            "bounds": [
1372                -180,
1373                -85,
1374                180,
1375                85
1376            ],
1377            "name": "Mapbox Satellite",
1378            "scheme": "xyz",
1379            "format": "zxy",
1380            "type": "raster",
1381            "extension": "webp",
1382            "encoding": "gzip",
1383            "minzoom": 0,
1384            "maxzoom": 3
1385        }
1386        "#;
1387
1388        let malformed_success: UnknownMetadata =
1389            serde_json::from_str(meta_str).unwrap_or_else(|e| panic!("ERROR: {}", e));
1390
1391        let meta: Metadata = malformed_success.to_metadata();
1392        assert_eq!(
1393            meta,
1394            Metadata {
1395                s2tilejson: "1.0.0".into(),
1396                version: "1.0.0".into(),
1397                name: "Mapbox Satellite".into(),
1398                scheme: Scheme::Xyz,
1399                description: "Built with s2maps-cli".into(),
1400                r#type: SourceType::Raster,
1401                extension: "webp".into(),
1402                encoding: Encoding::Gzip,
1403                faces: vec![Face::Face0],
1404                bounds: BTreeMap::default(),
1405                facesbounds: FaceBounds {
1406                    face0: BTreeMap::default(),
1407                    face1: BTreeMap::default(),
1408                    face2: BTreeMap::default(),
1409                    face3: BTreeMap::default(),
1410                    face4: BTreeMap::default(),
1411                    face5: BTreeMap::default()
1412                },
1413                minzoom: 0,
1414                maxzoom: 3,
1415                center: Center { lon: 0.0, lat: 0.0, zoom: 0 },
1416                attributions: BTreeMap::default(),
1417                layers: BTreeMap::default(),
1418                tilestats: TileStatsMetadata {
1419                    total: 0,
1420                    total_0: 0,
1421                    total_1: 0,
1422                    total_2: 0,
1423                    total_3: 0,
1424                    total_4: 0,
1425                    total_5: 0
1426                },
1427                vector_layers: vec![]
1428            }
1429        );
1430    }
1431
1432    #[test]
1433    fn test_faces() {
1434        let meta = Metadata {
1435            faces: vec![Face::Face0, Face::Face1, Face::Face4, Face::Face5],
1436            ..Default::default()
1437        };
1438
1439        let to_string: String = serde_json::to_string(&meta).unwrap();
1440        let from_string: Metadata = serde_json::from_str(&to_string).unwrap();
1441        assert_eq!(meta, from_string);
1442
1443        let from_string_unknown: UnknownMetadata = serde_json::from_str(&to_string).unwrap();
1444        let from_string: Metadata = from_string_unknown.to_metadata();
1445        assert_eq!(meta, from_string);
1446    }
1447}