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