1#![no_std]
2#![forbid(unsafe_code)]
3#![deny(missing_docs)]
4extern 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
19pub type LonLatBounds = BBox<f64>;
21
22pub type TileBounds = BBox<u64>;
24
25#[derive(Copy, Clone, Debug, PartialEq)]
27pub enum DrawType {
28 Points = 1,
30 Lines = 2,
32 Polygons = 3,
34 Points3D = 4,
36 Lines3D = 5,
38 Polygons3D = 6,
40 Raster = 7,
42 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, }
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 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 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#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)]
97pub struct LayerMetaData {
98 #[serde(skip_serializing_if = "Option::is_none")]
100 pub description: Option<String>,
101 pub minzoom: u8,
103 pub maxzoom: u8,
105 pub draw_types: Vec<DrawType>,
107 pub shape: Shape,
109 #[serde(skip_serializing_if = "Option::is_none", rename = "mShape")]
111 pub m_shape: Option<Shape>,
112}
113
114pub type LayersMetaData = BTreeMap<String, LayerMetaData>;
116
117#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)]
119pub struct TileStatsMetadata {
120 #[serde(default)]
122 pub total: u64,
123 #[serde(rename = "0", default)]
125 pub total_0: u64,
126 #[serde(rename = "1", default)]
128 pub total_1: u64,
129 #[serde(rename = "2", default)]
131 pub total_2: u64,
132 #[serde(rename = "3", default)]
134 pub total_3: u64,
135 #[serde(rename = "4", default)]
137 pub total_4: u64,
138 #[serde(rename = "5", default)]
140 pub total_5: u64,
141}
142impl TileStatsMetadata {
143 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 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
169pub type Attribution = BTreeMap<String, String>;
172
173#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)]
175pub struct FaceBounds {
176 #[serde(rename = "0")]
179 pub face0: BTreeMap<u8, TileBounds>,
180 #[serde(rename = "1")]
182 pub face1: BTreeMap<u8, TileBounds>,
183 #[serde(rename = "2")]
185 pub face2: BTreeMap<u8, TileBounds>,
186 #[serde(rename = "3")]
188 pub face3: BTreeMap<u8, TileBounds>,
189 #[serde(rename = "4")]
191 pub face4: BTreeMap<u8, TileBounds>,
192 #[serde(rename = "5")]
194 pub face5: BTreeMap<u8, TileBounds>,
195}
196impl FaceBounds {
197 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 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
222pub type WMBounds = BTreeMap<u8, TileBounds>;
225
226#[derive(Serialize, Debug, Default, Clone, PartialEq)]
228#[serde(rename_all = "lowercase")]
229pub enum SourceType {
230 #[default]
232 Vector,
233 Json,
235 Raster,
237 #[serde(rename = "raster-dem")]
239 RasterDem,
240 Grid,
242 Markers,
244 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 let s: String = Deserialize::deserialize(deserializer)?;
267 Ok(SourceType::from(s.as_str()))
268 }
269}
270
271#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)]
273#[serde(rename_all = "lowercase")]
274pub enum Encoding {
275 #[default]
277 None = 0,
278 Gzip = 1,
280 #[serde(rename = "br")]
282 Brotli = 2,
283 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#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)]
329pub struct VectorLayer {
330 pub id: String,
332 #[serde(skip_serializing_if = "Option::is_none")]
334 pub description: Option<String>,
335 #[serde(skip_serializing_if = "Option::is_none")]
337 pub minzoom: Option<u8>,
338 #[serde(skip_serializing_if = "Option::is_none")]
340 pub maxzoom: Option<u8>,
341 pub fields: BTreeMap<String, String>,
343}
344
345#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)]
350#[serde(rename_all = "lowercase")]
351pub enum Scheme {
352 #[default]
354 Fzxy,
355 Tfzxy,
357 Xyz,
359 Txyz,
361 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#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)]
389pub struct Center {
390 pub lon: f64,
392 pub lat: f64,
394 pub zoom: u8,
396}
397
398#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
400#[serde(default)]
401pub struct Metadata {
402 pub s2tilejson: String,
404 pub version: String,
406 pub name: String,
408 pub scheme: Scheme,
410 pub description: String,
412 #[serde(rename = "type")]
414 pub r#type: SourceType,
415 pub extension: String,
417 pub encoding: Encoding,
419 pub faces: Vec<Face>,
421 pub bounds: WMBounds,
423 pub facesbounds: FaceBounds,
425 pub minzoom: u8,
427 pub maxzoom: u8,
429 pub center: Center,
431 pub attribution: Attribution,
433 pub layers: LayersMetaData,
435 pub tilestats: TileStatsMetadata,
437 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#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq)]
479#[serde(default)]
480pub struct MapboxTileJSONMetadata {
481 pub tilejson: String,
484 pub tiles: Vec<String>,
486 pub vector_layers: Vec<VectorLayer>,
488 pub attribution: Option<String>,
490 pub bounds: Option<BBox>,
492 pub center: Option<[f64; 3]>,
494 pub data: Option<Vec<String>>,
496 pub description: Option<String>,
498 pub fillzoom: Option<u8>,
500 pub grids: Option<Vec<String>>,
502 pub legend: Option<String>,
504 pub maxzoom: Option<u8>,
506 pub minzoom: Option<u8>,
508 pub name: Option<String>,
510 pub scheme: Option<Scheme>,
512 pub template: Option<String>,
514 pub version: Option<String>,
516 pub r#type: Option<SourceType>,
519 pub extension: Option<String>,
521 pub encoding: Option<Encoding>,
523}
524impl MapboxTileJSONMetadata {
525 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#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
556#[serde(untagged)]
557pub enum UnknownMetadata {
558 Metadata(Box<Metadata>),
560 Mapbox(Box<MapboxTileJSONMetadata>),
562}
563impl UnknownMetadata {
564 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#[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 pub fn commit(&mut self) -> Metadata {
597 self.update_center();
599 for face in &self.faces {
601 self.metadata.faces.push(*face);
602 }
603 self.metadata.to_owned()
605 }
606
607 pub fn set_name(&mut self, name: String) {
609 self.metadata.name = name;
610 }
611
612 pub fn set_scheme(&mut self, scheme: Scheme) {
614 self.metadata.scheme = scheme;
615 }
616
617 pub fn set_extension(&mut self, extension: String) {
619 self.metadata.extension = extension;
620 }
621
622 pub fn set_type(&mut self, r#type: SourceType) {
624 self.metadata.r#type = r#type;
625 }
626
627 pub fn set_version(&mut self, version: String) {
629 self.metadata.version = version;
630 }
631
632 pub fn set_description(&mut self, description: String) {
634 self.metadata.description = description;
635 }
636
637 pub fn set_encoding(&mut self, encoding: Encoding) {
639 self.metadata.encoding = encoding;
640 }
641
642 pub fn add_attribution(&mut self, display_name: &str, href: &str) {
644 self.metadata.attribution.insert(display_name.into(), href.into());
645 }
646
647 pub fn add_layer(&mut self, name: &str, layer: &LayerMetaData) {
649 if self.metadata.layers.entry(name.into()).or_insert(layer.clone()).eq(&layer) {
651 self.metadata.vector_layers.push(VectorLayer {
653 id: name.into(), description: layer.description.clone(),
655 minzoom: Some(layer.minzoom),
656 maxzoom: Some(layer.maxzoom),
657 fields: BTreeMap::new(),
658 });
659 }
660 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 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 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 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 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 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 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 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()); meta_builder.set_type("vector".into()); meta_builder.set_encoding("none".into()); meta_builder.set_extension("pbf".into());
755 meta_builder.add_attribution("OpenStreetMap", "https://www.openstreetmap.org/copyright/");
756
757 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 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 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 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 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 #[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 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 assert_eq!(tilestats.get(0.into()), 0);
927 tilestats.increment(0.into());
929 assert_eq!(tilestats.get(0.into()), 1);
930
931 assert_eq!(tilestats.get(1.into()), 1);
933 tilestats.increment(1.into());
935 assert_eq!(tilestats.get(1.into()), 2);
936
937 assert_eq!(tilestats.get(2.into()), 0);
939 tilestats.increment(2.into());
941 assert_eq!(tilestats.get(2.into()), 1);
942
943 assert_eq!(tilestats.get(3.into()), 0);
945 tilestats.increment(3.into());
947 assert_eq!(tilestats.get(3.into()), 1);
948
949 assert_eq!(tilestats.get(4.into()), 0);
951 tilestats.increment(4.into());
953 assert_eq!(tilestats.get(4.into()), 1);
954
955 assert_eq!(tilestats.get(5.into()), 0);
957 tilestats.increment(5.into());
959 assert_eq!(tilestats.get(5.into()), 1);
960 }
961
962 #[test]
964 fn test_facebounds() {
965 let mut facebounds = FaceBounds::default();
966 let face0 = facebounds.get_mut(0.into());
968 face0.insert(0, TileBounds { left: 0, bottom: 0, right: 0, top: 0 });
969 let face1 = facebounds.get_mut(1.into());
971 face1.insert(0, TileBounds { left: 0, bottom: 0, right: 1, top: 1 });
972 let face2 = facebounds.get_mut(2.into());
974 face2.insert(0, TileBounds { left: 0, bottom: 0, right: 2, top: 2 });
975 let face3 = facebounds.get_mut(3.into());
977 face3.insert(0, TileBounds { left: 0, bottom: 0, right: 3, top: 3 });
978 let face4 = facebounds.get_mut(4.into());
980 face4.insert(0, TileBounds { left: 0, bottom: 0, right: 4, top: 4 });
981 let face5 = facebounds.get_mut(5.into());
983 face5.insert(0, TileBounds { left: 0, bottom: 0, right: 5, top: 5 });
984
985 assert_eq!(
988 facebounds.get(0.into()).get(&0).unwrap(),
989 &TileBounds { left: 0, bottom: 0, right: 0, top: 0 }
990 );
991 assert_eq!(
993 facebounds.get(1.into()).get(&0).unwrap(),
994 &TileBounds { left: 0, bottom: 0, right: 1, top: 1 }
995 );
996 assert_eq!(
998 facebounds.get(2.into()).get(&0).unwrap(),
999 &TileBounds { left: 0, bottom: 0, right: 2, top: 2 }
1000 );
1001 assert_eq!(
1003 facebounds.get(3.into()).get(&0).unwrap(),
1004 &TileBounds { left: 0, bottom: 0, right: 3, top: 3 }
1005 );
1006 assert_eq!(
1008 facebounds.get(4.into()).get(&0).unwrap(),
1009 &TileBounds { left: 0, bottom: 0, right: 4, top: 4 }
1010 );
1011 assert_eq!(
1013 facebounds.get(5.into()).get(&0).unwrap(),
1014 &TileBounds { left: 0, bottom: 0, right: 5, top: 5 }
1015 );
1016
1017 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 #[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 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 #[test]
1081 fn test_sourcetype() {
1082 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 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 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 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 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 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 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 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 #[test]
1136 fn test_encoding() {
1137 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 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 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 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 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 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 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 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 #[test]
1188 fn test_scheme() {
1189 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 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}