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