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)]
400pub struct Metadata {
401 #[serde(default)]
403 pub s2tilejson: String,
404 #[serde(default)]
406 pub version: String,
407 #[serde(default)]
409 pub name: String,
410 #[serde(default)]
412 pub scheme: Scheme,
413 #[serde(default)]
415 pub description: String,
416 #[serde(rename = "type", default)]
418 pub type_: SourceType,
419 #[serde(default)]
421 pub extension: String,
422 #[serde(default)]
424 pub encoding: Encoding,
425 #[serde(default)]
427 pub faces: Vec<Face>,
428 #[serde(default)]
430 pub bounds: WMBounds,
431 #[serde(default)]
433 pub facesbounds: FaceBounds,
434 #[serde(default)]
436 pub minzoom: u8,
437 #[serde(default)]
439 pub maxzoom: u8,
440 #[serde(default)]
442 pub center: Center,
443 #[serde(default)]
445 pub attribution: Attribution,
446 #[serde(default)]
448 pub layers: LayersMetaData,
449 #[serde(default)]
451 pub tilestats: TileStatsMetadata,
452 #[serde(default)]
454 pub vector_layers: Vec<VectorLayer>,
455}
456impl Default for Metadata {
457 fn default() -> Self {
458 Self {
459 s2tilejson: "1.0.0".into(),
460 version: "1.0.0".into(),
461 name: "default".into(),
462 scheme: Scheme::default(),
463 description: "Built with s2maps-cli".into(),
464 type_: SourceType::default(),
465 extension: "pbf".into(),
466 encoding: Encoding::default(),
467 faces: Vec::new(),
468 bounds: WMBounds::default(),
469 facesbounds: FaceBounds::default(),
470 minzoom: 0,
471 maxzoom: 27,
472 center: Center::default(),
473 attribution: BTreeMap::new(),
474 layers: LayersMetaData::default(),
475 tilestats: TileStatsMetadata::default(),
476 vector_layers: Vec::new(),
477 }
478 }
479}
480
481#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
495pub struct MapboxTileJSONMetadata {
496 pub tilejson: String,
499 pub tiles: Vec<String>,
501 pub vector_layers: Vec<VectorLayer>,
503 pub attribution: Option<String>,
505 pub bounds: Option<BBox>,
507 pub center: Option<[f64; 3]>,
509 pub data: Option<Vec<String>>,
511 pub description: Option<String>,
513 pub fillzoom: Option<u8>,
515 pub grids: Option<Vec<String>>,
517 pub legend: Option<String>,
519 pub maxzoom: Option<u8>,
521 pub minzoom: Option<u8>,
523 pub name: Option<String>,
525 pub scheme: Option<Scheme>,
527 pub template: Option<String>,
529 pub version: Option<String>,
531}
532impl MapboxTileJSONMetadata {
533 pub fn to_metadata(&self) -> Metadata {
535 Metadata {
536 s2tilejson: "1.0.0".into(),
537 version: self.version.clone().unwrap_or("1.0.0".into()),
538 name: self.name.clone().unwrap_or("default".into()),
539 scheme: self.scheme.clone().unwrap_or_default(),
540 description: self.description.clone().unwrap_or("Built with s2maps-cli".into()),
541 type_: SourceType::default(),
542 extension: "pbf".into(),
543 faces: Vec::from([Face::Face0]),
544 bounds: WMBounds::default(),
545 facesbounds: FaceBounds::default(),
546 minzoom: self.minzoom.unwrap_or(0),
547 maxzoom: self.maxzoom.unwrap_or(27),
548 center: Center {
549 lon: self.center.unwrap_or([0.0, 0.0, 0.0])[0],
550 lat: self.center.unwrap_or([0.0, 0.0, 0.0])[1],
551 zoom: self.center.unwrap_or([0.0, 0.0, 0.0])[2] as u8,
552 },
553 attribution: BTreeMap::new(),
554 layers: LayersMetaData::default(),
555 tilestats: TileStatsMetadata::default(),
556 vector_layers: self.vector_layers.clone(),
557 encoding: Encoding::default(),
558 }
559 }
560}
561
562#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
564#[serde(untagged)]
565pub enum UnknownMetadata {
566 Metadata(Box<Metadata>),
568 Mapbox(Box<MapboxTileJSONMetadata>),
570}
571impl UnknownMetadata {
572 pub fn to_metadata(&self) -> Metadata {
574 match self {
575 UnknownMetadata::Metadata(m) => *m.clone(),
576 UnknownMetadata::Mapbox(m) => m.to_metadata(),
577 }
578 }
579}
580
581#[derive(Debug, Clone)]
583pub struct MetadataBuilder {
584 lon_lat_bounds: LonLatBounds,
585 faces: BTreeSet<Face>,
586 metadata: Metadata,
587}
588impl Default for MetadataBuilder {
589 fn default() -> Self {
590 MetadataBuilder {
591 lon_lat_bounds: BBox {
592 left: f64::INFINITY,
593 bottom: f64::INFINITY,
594 right: -f64::INFINITY,
595 top: -f64::INFINITY,
596 },
597 faces: BTreeSet::new(),
598 metadata: Metadata { minzoom: 30, maxzoom: 0, ..Metadata::default() },
599 }
600 }
601}
602impl MetadataBuilder {
603 pub fn commit(&mut self) -> Metadata {
605 self.update_center();
607 for face in &self.faces {
609 self.metadata.faces.push(*face);
610 }
611 self.metadata.to_owned()
613 }
614
615 pub fn set_name(&mut self, name: String) {
617 self.metadata.name = name;
618 }
619
620 pub fn set_scheme(&mut self, scheme: Scheme) {
622 self.metadata.scheme = scheme;
623 }
624
625 pub fn set_extension(&mut self, extension: String) {
627 self.metadata.extension = extension;
628 }
629
630 pub fn set_type(&mut self, type_: SourceType) {
632 self.metadata.type_ = type_;
633 }
634
635 pub fn set_version(&mut self, version: String) {
637 self.metadata.version = version;
638 }
639
640 pub fn set_description(&mut self, description: String) {
642 self.metadata.description = description;
643 }
644
645 pub fn set_encoding(&mut self, encoding: Encoding) {
647 self.metadata.encoding = encoding;
648 }
649
650 pub fn add_attribution(&mut self, display_name: &str, href: &str) {
652 self.metadata.attribution.insert(display_name.into(), href.into());
653 }
654
655 pub fn add_layer(&mut self, name: &str, layer: &LayerMetaData) {
657 if self.metadata.layers.entry(name.into()).or_insert(layer.clone()).eq(&layer) {
659 self.metadata.vector_layers.push(VectorLayer {
661 id: name.into(), description: layer.description.clone(),
663 minzoom: Some(layer.minzoom),
664 maxzoom: Some(layer.maxzoom),
665 fields: BTreeMap::new(),
666 });
667 }
668 if layer.minzoom < self.metadata.minzoom {
670 self.metadata.minzoom = layer.minzoom;
671 }
672 if layer.maxzoom > self.metadata.maxzoom {
673 self.metadata.maxzoom = layer.maxzoom;
674 }
675 }
676
677 pub fn add_tile_wm(&mut self, zoom: u8, x: u32, y: u32, ll_bounds: &LonLatBounds) {
679 self.metadata.tilestats.total += 1;
680 self.faces.insert(Face::Face0);
681 self.add_bounds_wm(zoom, x, y);
682 self.update_lon_lat_bounds(ll_bounds);
683 }
684
685 pub fn add_tile_s2(&mut self, face: Face, zoom: u8, x: u32, y: u32, ll_bounds: &LonLatBounds) {
687 self.metadata.tilestats.increment(face);
688 self.faces.insert(face);
689 self.add_bounds_s2(face, zoom, x, y);
690 self.update_lon_lat_bounds(ll_bounds);
691 }
692
693 fn update_center(&mut self) {
695 let Metadata { minzoom, maxzoom, .. } = self.metadata;
696 let BBox { left, bottom, right, top } = self.lon_lat_bounds;
697 self.metadata.center.lon = (left + right) / 2.0;
698 self.metadata.center.lat = (bottom + top) / 2.0;
699 self.metadata.center.zoom = (minzoom + maxzoom) >> 1;
700 }
701
702 fn add_bounds_wm(&mut self, zoom: u8, x: u32, y: u32) {
704 let x = x as u64;
705 let y = y as u64;
706 let bbox = self.metadata.bounds.entry(zoom).or_insert(BBox {
707 left: u64::MAX,
708 bottom: u64::MAX,
709 right: 0,
710 top: 0,
711 });
712
713 bbox.left = bbox.left.min(x);
714 bbox.bottom = bbox.bottom.min(y);
715 bbox.right = bbox.right.max(x);
716 bbox.top = bbox.top.max(y);
717 }
718
719 fn add_bounds_s2(&mut self, face: Face, zoom: u8, x: u32, y: u32) {
721 let x = x as u64;
722 let y = y as u64;
723 let bbox = self.metadata.facesbounds.get_mut(face).entry(zoom).or_insert(BBox {
724 left: u64::MAX,
725 bottom: u64::MAX,
726 right: 0,
727 top: 0,
728 });
729
730 bbox.left = bbox.left.min(x);
731 bbox.bottom = bbox.bottom.min(y);
732 bbox.right = bbox.right.max(x);
733 bbox.top = bbox.top.max(y);
734 }
735
736 fn update_lon_lat_bounds(&mut self, ll_bounds: &LonLatBounds) {
738 self.lon_lat_bounds.left = ll_bounds.left.min(self.lon_lat_bounds.left);
739 self.lon_lat_bounds.bottom = ll_bounds.bottom.min(self.lon_lat_bounds.bottom);
740 self.lon_lat_bounds.right = ll_bounds.right.max(self.lon_lat_bounds.right);
741 self.lon_lat_bounds.top = ll_bounds.top.max(self.lon_lat_bounds.top);
742 }
743}
744
745#[cfg(test)]
746mod tests {
747 use super::*;
748 use alloc::vec;
749 use s2json::{PrimitiveShape, ShapeType};
750
751 #[test]
752 fn it_works() {
753 let mut meta_builder = MetadataBuilder::default();
754
755 meta_builder.set_name("OSM".into());
757 meta_builder.set_description("A free editable map of the whole world.".into());
758 meta_builder.set_version("1.0.0".into());
759 meta_builder.set_scheme("fzxy".into()); meta_builder.set_type("vector".into()); meta_builder.set_encoding("none".into()); meta_builder.set_extension("pbf".into());
763 meta_builder.add_attribution("OpenStreetMap", "https://www.openstreetmap.org/copyright/");
764
765 let shape_str = r#"
767 {
768 "class": "string",
769 "offset": "f64",
770 "info": {
771 "name": "string",
772 "value": "i64"
773 }
774 }
775 "#;
776 let shape: Shape =
777 serde_json::from_str(shape_str).unwrap_or_else(|e| panic!("ERROR: {}", e));
778 let layer = LayerMetaData {
779 minzoom: 0,
780 maxzoom: 13,
781 description: Some("water_lines".into()),
782 draw_types: Vec::from(&[DrawType::Lines]),
783 shape: shape.clone(),
784 m_shape: None,
785 };
786 meta_builder.add_layer("water_lines", &layer);
787
788 meta_builder.add_tile_wm(
791 0,
792 0,
793 0,
794 &LonLatBounds { left: -60.0, bottom: -20.0, right: 5.0, top: 60.0 },
795 );
796 meta_builder.add_tile_s2(
798 Face::Face1,
799 5,
800 22,
801 37,
802 &LonLatBounds { left: -120.0, bottom: -7.0, right: 44.0, top: 72.0 },
803 );
804
805 let resulting_metadata: Metadata = meta_builder.commit();
807
808 assert_eq!(
809 resulting_metadata,
810 Metadata {
811 name: "OSM".into(),
812 description: "A free editable map of the whole world.".into(),
813 version: "1.0.0".into(),
814 scheme: "fzxy".into(),
815 type_: "vector".into(),
816 encoding: "none".into(),
817 extension: "pbf".into(),
818 attribution: BTreeMap::from([(
819 "OpenStreetMap".into(),
820 "https://www.openstreetmap.org/copyright/".into()
821 ),]),
822 bounds: BTreeMap::from([(0, TileBounds { left: 0, bottom: 0, right: 0, top: 0 }),]),
823 faces: Vec::from(&[Face::Face0, Face::Face1]),
824 facesbounds: FaceBounds {
825 face0: BTreeMap::new(),
826 face1: BTreeMap::from([(
827 5,
828 TileBounds { left: 22, bottom: 37, right: 22, top: 37 }
829 ),]),
830 face2: BTreeMap::new(),
831 face3: BTreeMap::new(),
832 face4: BTreeMap::new(),
833 face5: BTreeMap::new(),
834 },
835 minzoom: 0,
836 maxzoom: 13,
837 center: Center { lon: -38.0, lat: 26.0, zoom: 6 },
838 tilestats: TileStatsMetadata {
839 total: 2,
840 total_0: 0,
841 total_1: 1,
842 total_2: 0,
843 total_3: 0,
844 total_4: 0,
845 total_5: 0,
846 },
847 layers: BTreeMap::from([(
848 "water_lines".into(),
849 LayerMetaData {
850 description: Some("water_lines".into()),
851 minzoom: 0,
852 maxzoom: 13,
853 draw_types: Vec::from(&[DrawType::Lines]),
854 shape: Shape::from([
855 ("class".into(), ShapeType::Primitive(PrimitiveShape::String)),
856 ("offset".into(), ShapeType::Primitive(PrimitiveShape::F64)),
857 (
858 "info".into(),
859 ShapeType::Nested(Shape::from([
860 ("name".into(), ShapeType::Primitive(PrimitiveShape::String)),
861 ("value".into(), ShapeType::Primitive(PrimitiveShape::I64)),
862 ]))
863 ),
864 ]),
865 m_shape: None,
866 }
867 )]),
868 s2tilejson: "1.0.0".into(),
869 vector_layers: Vec::from([VectorLayer {
870 id: "water_lines".into(),
871 description: Some("water_lines".into()),
872 minzoom: Some(0),
873 maxzoom: Some(13),
874 fields: BTreeMap::new()
875 }]),
876 }
877 );
878
879 let meta_str = serde_json::to_string(&resulting_metadata).unwrap();
880
881 assert_eq!(meta_str, "{\"s2tilejson\":\"1.0.0\",\"version\":\"1.0.0\",\"name\":\"OSM\",\"scheme\":\"fzxy\",\"description\":\"A free editable map of the whole world.\",\"type\":\"vector\",\"extension\":\"pbf\",\"encoding\":\"none\",\"faces\":[0,1],\"bounds\":{\"0\":[0,0,0,0]},\"facesbounds\":{\"0\":{},\"1\":{\"5\":[22,37,22,37]},\"2\":{},\"3\":{},\"4\":{},\"5\":{}},\"minzoom\":0,\"maxzoom\":13,\"center\":{\"lon\":-38.0,\"lat\":26.0,\"zoom\":6},\"attribution\":{\"OpenStreetMap\":\"https://www.openstreetmap.org/copyright/\"},\"layers\":{\"water_lines\":{\"description\":\"water_lines\",\"minzoom\":0,\"maxzoom\":13,\"draw_types\":[2],\"shape\":{\"class\":\"string\",\"info\":{\"name\":\"string\",\"value\":\"i64\"},\"offset\":\"f64\"}}},\"tilestats\":{\"total\":2,\"0\":0,\"1\":1,\"2\":0,\"3\":0,\"4\":0,\"5\":0},\"vector_layers\":[{\"id\":\"water_lines\",\"description\":\"water_lines\",\"minzoom\":0,\"maxzoom\":13,\"fields\":{}}]}");
882
883 let meta_reparsed: Metadata =
884 serde_json::from_str(&meta_str).unwrap_or_else(|e| panic!("ERROR: {}", e));
885 assert_eq!(meta_reparsed, resulting_metadata);
886 }
887
888 #[test]
889 fn test_face() {
890 assert_eq!(Face::Face0, Face::from(0));
891 assert_eq!(Face::Face1, Face::from(1));
892 assert_eq!(Face::Face2, Face::from(2));
893 assert_eq!(Face::Face3, Face::from(3));
894 assert_eq!(Face::Face4, Face::from(4));
895 assert_eq!(Face::Face5, Face::from(5));
896
897 assert_eq!(0, u8::from(Face::Face0));
898 assert_eq!(1, u8::from(Face::Face1));
899 assert_eq!(2, u8::from(Face::Face2));
900 assert_eq!(3, u8::from(Face::Face3));
901 assert_eq!(4, u8::from(Face::Face4));
902 assert_eq!(5, u8::from(Face::Face5));
903 }
904
905 #[test]
906 fn test_bbox() {
907 let bbox: BBox = BBox { left: 0.0, bottom: 0.0, right: 0.0, top: 0.0 };
908 let json = serde_json::to_string(&bbox).unwrap();
910 assert_eq!(json, r#"[0.0,0.0,0.0,0.0]"#);
911 let bbox2: BBox = serde_json::from_str(&json).unwrap();
912 assert_eq!(bbox, bbox2);
913 }
914
915 #[test]
917 fn test_tilestats() {
918 let mut tilestats = TileStatsMetadata {
919 total: 2,
920 total_0: 0,
921 total_1: 1,
922 total_2: 0,
923 total_3: 0,
924 total_4: 0,
925 total_5: 0,
926 };
927 let json = serde_json::to_string(&tilestats).unwrap();
929 assert_eq!(json, r#"{"total":2,"0":0,"1":1,"2":0,"3":0,"4":0,"5":0}"#);
930 let tilestats2: TileStatsMetadata = serde_json::from_str(&json).unwrap();
931 assert_eq!(tilestats, tilestats2);
932
933 assert_eq!(tilestats.get(0.into()), 0);
935 tilestats.increment(0.into());
937 assert_eq!(tilestats.get(0.into()), 1);
938
939 assert_eq!(tilestats.get(1.into()), 1);
941 tilestats.increment(1.into());
943 assert_eq!(tilestats.get(1.into()), 2);
944
945 assert_eq!(tilestats.get(2.into()), 0);
947 tilestats.increment(2.into());
949 assert_eq!(tilestats.get(2.into()), 1);
950
951 assert_eq!(tilestats.get(3.into()), 0);
953 tilestats.increment(3.into());
955 assert_eq!(tilestats.get(3.into()), 1);
956
957 assert_eq!(tilestats.get(4.into()), 0);
959 tilestats.increment(4.into());
961 assert_eq!(tilestats.get(4.into()), 1);
962
963 assert_eq!(tilestats.get(5.into()), 0);
965 tilestats.increment(5.into());
967 assert_eq!(tilestats.get(5.into()), 1);
968 }
969
970 #[test]
972 fn test_facebounds() {
973 let mut facebounds = FaceBounds::default();
974 let face0 = facebounds.get_mut(0.into());
976 face0.insert(0, TileBounds { left: 0, bottom: 0, right: 0, top: 0 });
977 let face1 = facebounds.get_mut(1.into());
979 face1.insert(0, TileBounds { left: 0, bottom: 0, right: 1, top: 1 });
980 let face2 = facebounds.get_mut(2.into());
982 face2.insert(0, TileBounds { left: 0, bottom: 0, right: 2, top: 2 });
983 let face3 = facebounds.get_mut(3.into());
985 face3.insert(0, TileBounds { left: 0, bottom: 0, right: 3, top: 3 });
986 let face4 = facebounds.get_mut(4.into());
988 face4.insert(0, TileBounds { left: 0, bottom: 0, right: 4, top: 4 });
989 let face5 = facebounds.get_mut(5.into());
991 face5.insert(0, TileBounds { left: 0, bottom: 0, right: 5, top: 5 });
992
993 assert_eq!(
996 facebounds.get(0.into()).get(&0).unwrap(),
997 &TileBounds { left: 0, bottom: 0, right: 0, top: 0 }
998 );
999 assert_eq!(
1001 facebounds.get(1.into()).get(&0).unwrap(),
1002 &TileBounds { left: 0, bottom: 0, right: 1, top: 1 }
1003 );
1004 assert_eq!(
1006 facebounds.get(2.into()).get(&0).unwrap(),
1007 &TileBounds { left: 0, bottom: 0, right: 2, top: 2 }
1008 );
1009 assert_eq!(
1011 facebounds.get(3.into()).get(&0).unwrap(),
1012 &TileBounds { left: 0, bottom: 0, right: 3, top: 3 }
1013 );
1014 assert_eq!(
1016 facebounds.get(4.into()).get(&0).unwrap(),
1017 &TileBounds { left: 0, bottom: 0, right: 4, top: 4 }
1018 );
1019 assert_eq!(
1021 facebounds.get(5.into()).get(&0).unwrap(),
1022 &TileBounds { left: 0, bottom: 0, right: 5, top: 5 }
1023 );
1024
1025 let json = serde_json::to_string(&facebounds).unwrap();
1027 assert_eq!(
1028 json,
1029 "{\"0\":{\"0\":[0,0,0,0]},\"1\":{\"0\":[0,0,1,1]},\"2\":{\"0\":[0,0,2,2]},\"3\":{\"0\"\
1030 :[0,0,3,3]},\"4\":{\"0\":[0,0,4,4]},\"5\":{\"0\":[0,0,5,5]}}"
1031 );
1032 let facebounds2 = serde_json::from_str(&json).unwrap();
1033 assert_eq!(facebounds, facebounds2);
1034 }
1035
1036 #[test]
1038 fn test_drawtype() {
1039 assert_eq!(DrawType::from(1), DrawType::Points);
1040 assert_eq!(DrawType::from(2), DrawType::Lines);
1041 assert_eq!(DrawType::from(3), DrawType::Polygons);
1042 assert_eq!(DrawType::from(4), DrawType::Points3D);
1043 assert_eq!(DrawType::from(5), DrawType::Lines3D);
1044 assert_eq!(DrawType::from(6), DrawType::Polygons3D);
1045 assert_eq!(DrawType::from(7), DrawType::Raster);
1046 assert_eq!(DrawType::from(8), DrawType::Grid);
1047
1048 assert_eq!(1, u8::from(DrawType::Points));
1049 assert_eq!(2, u8::from(DrawType::Lines));
1050 assert_eq!(3, u8::from(DrawType::Polygons));
1051 assert_eq!(4, u8::from(DrawType::Points3D));
1052 assert_eq!(5, u8::from(DrawType::Lines3D));
1053 assert_eq!(6, u8::from(DrawType::Polygons3D));
1054 assert_eq!(7, u8::from(DrawType::Raster));
1055 assert_eq!(8, u8::from(DrawType::Grid));
1056
1057 let json = serde_json::to_string(&DrawType::Points).unwrap();
1059 assert_eq!(json, "1");
1060 let drawtype: DrawType = serde_json::from_str(&json).unwrap();
1061 assert_eq!(drawtype, DrawType::Points);
1062
1063 let drawtype: DrawType = serde_json::from_str("2").unwrap();
1064 assert_eq!(drawtype, DrawType::Lines);
1065
1066 let drawtype: DrawType = serde_json::from_str("3").unwrap();
1067 assert_eq!(drawtype, DrawType::Polygons);
1068
1069 let drawtype: DrawType = serde_json::from_str("4").unwrap();
1070 assert_eq!(drawtype, DrawType::Points3D);
1071
1072 let drawtype: DrawType = serde_json::from_str("5").unwrap();
1073 assert_eq!(drawtype, DrawType::Lines3D);
1074
1075 let drawtype: DrawType = serde_json::from_str("6").unwrap();
1076 assert_eq!(drawtype, DrawType::Polygons3D);
1077
1078 let drawtype: DrawType = serde_json::from_str("7").unwrap();
1079 assert_eq!(drawtype, DrawType::Raster);
1080
1081 let drawtype: DrawType = serde_json::from_str("8").unwrap();
1082 assert_eq!(drawtype, DrawType::Grid);
1083
1084 assert!(serde_json::from_str::<DrawType>("9").is_err());
1085 }
1086
1087 #[test]
1089 fn test_sourcetype() {
1090 assert_eq!(SourceType::from("vector"), SourceType::Vector);
1092 assert_eq!(SourceType::from("json"), SourceType::Json);
1093 assert_eq!(SourceType::from("raster"), SourceType::Raster);
1094 assert_eq!(SourceType::from("raster-dem"), SourceType::RasterDem);
1095 assert_eq!(SourceType::from("grid"), SourceType::Grid);
1096 assert_eq!(SourceType::from("markers"), SourceType::Markers);
1097 assert_eq!(SourceType::from("overlay"), SourceType::Unknown);
1098
1099 let json = serde_json::to_string(&SourceType::Vector).unwrap();
1101 assert_eq!(json, "\"vector\"");
1102 let sourcetype: SourceType = serde_json::from_str(&json).unwrap();
1103 assert_eq!(sourcetype, SourceType::Vector);
1104
1105 let json = serde_json::to_string(&SourceType::Json).unwrap();
1107 assert_eq!(json, "\"json\"");
1108 let sourcetype: SourceType = serde_json::from_str(&json).unwrap();
1109 assert_eq!(sourcetype, SourceType::Json);
1110
1111 let json = serde_json::to_string(&SourceType::Raster).unwrap();
1113 assert_eq!(json, "\"raster\"");
1114 let sourcetype: SourceType = serde_json::from_str(&json).unwrap();
1115 assert_eq!(sourcetype, SourceType::Raster);
1116
1117 let json = serde_json::to_string(&SourceType::RasterDem).unwrap();
1119 assert_eq!(json, "\"raster-dem\"");
1120 let sourcetype: SourceType = serde_json::from_str(&json).unwrap();
1121 assert_eq!(sourcetype, SourceType::RasterDem);
1122
1123 let json = serde_json::to_string(&SourceType::Grid).unwrap();
1125 assert_eq!(json, "\"grid\"");
1126 let sourcetype: SourceType = serde_json::from_str(&json).unwrap();
1127 assert_eq!(sourcetype, SourceType::Grid);
1128
1129 let json = serde_json::to_string(&SourceType::Markers).unwrap();
1131 assert_eq!(json, "\"markers\"");
1132 let sourcetype: SourceType = serde_json::from_str(&json).unwrap();
1133 assert_eq!(sourcetype, SourceType::Markers);
1134
1135 let json = serde_json::to_string(&SourceType::Unknown).unwrap();
1137 assert_eq!(json, "\"unknown\"");
1138 let sourcetype: SourceType = serde_json::from_str(r#""overlay""#).unwrap();
1139 assert_eq!(sourcetype, SourceType::Unknown);
1140 }
1141
1142 #[test]
1144 fn test_encoding() {
1145 assert_eq!(Encoding::from("none"), Encoding::None);
1147 assert_eq!(Encoding::from("gzip"), Encoding::Gzip);
1148 assert_eq!(Encoding::from("br"), Encoding::Brotli);
1149 assert_eq!(Encoding::from("zstd"), Encoding::Zstd);
1150
1151 assert_eq!(core::convert::Into::<&str>::into(Encoding::None), "none");
1153 assert_eq!(core::convert::Into::<&str>::into(Encoding::Gzip), "gzip");
1154 assert_eq!(core::convert::Into::<&str>::into(Encoding::Brotli), "br");
1155 assert_eq!(core::convert::Into::<&str>::into(Encoding::Zstd), "zstd");
1156
1157 assert_eq!(Encoding::from(0), Encoding::None);
1159 assert_eq!(Encoding::from(1), Encoding::Gzip);
1160 assert_eq!(Encoding::from(2), Encoding::Brotli);
1161 assert_eq!(Encoding::from(3), Encoding::Zstd);
1162
1163 assert_eq!(u8::from(Encoding::None), 0);
1165 assert_eq!(u8::from(Encoding::Gzip), 1);
1166 assert_eq!(u8::from(Encoding::Brotli), 2);
1167 assert_eq!(u8::from(Encoding::Zstd), 3);
1168
1169 let json = serde_json::to_string(&Encoding::Gzip).unwrap();
1171 assert_eq!(json, "\"gzip\"");
1172 let encoding: Encoding = serde_json::from_str(&json).unwrap();
1173 assert_eq!(encoding, Encoding::Gzip);
1174
1175 let json = serde_json::to_string(&Encoding::Brotli).unwrap();
1177 assert_eq!(json, "\"br\"");
1178 let encoding: Encoding = serde_json::from_str(&json).unwrap();
1179 assert_eq!(encoding, Encoding::Brotli);
1180
1181 let json = serde_json::to_string(&Encoding::None).unwrap();
1183 assert_eq!(json, "\"none\"");
1184 let encoding: Encoding = serde_json::from_str(&json).unwrap();
1185 assert_eq!(encoding, Encoding::None);
1186
1187 let json = serde_json::to_string(&Encoding::Zstd).unwrap();
1189 assert_eq!(json, "\"zstd\"");
1190 let encoding: Encoding = serde_json::from_str(&json).unwrap();
1191 assert_eq!(encoding, Encoding::Zstd);
1192 }
1193
1194 #[test]
1196 fn test_scheme() {
1197 assert_eq!(Scheme::from("fzxy"), Scheme::Fzxy);
1199 assert_eq!(Scheme::from("tfzxy"), Scheme::Tfzxy);
1200 assert_eq!(Scheme::from("xyz"), Scheme::Xyz);
1201 assert_eq!(Scheme::from("txyz"), Scheme::Txyz);
1202 assert_eq!(Scheme::from("tms"), Scheme::Tms);
1203
1204 assert_eq!(core::convert::Into::<&str>::into(Scheme::Fzxy), "fzxy");
1206 assert_eq!(core::convert::Into::<&str>::into(Scheme::Tfzxy), "tfzxy");
1207 assert_eq!(core::convert::Into::<&str>::into(Scheme::Xyz), "xyz");
1208 assert_eq!(core::convert::Into::<&str>::into(Scheme::Txyz), "txyz");
1209 assert_eq!(core::convert::Into::<&str>::into(Scheme::Tms), "tms");
1210 }
1211
1212 #[test]
1213 fn test_tippecanoe_metadata() {
1214 let meta_str = r#"{
1215 "name": "test_fixture_1.pmtiles",
1216 "description": "test_fixture_1.pmtiles",
1217 "version": "2",
1218 "type": "overlay",
1219 "generator": "tippecanoe v2.5.0",
1220 "generator_options": "./tippecanoe -zg -o test_fixture_1.pmtiles --force",
1221 "vector_layers": [
1222 {
1223 "id": "test_fixture_1pmtiles",
1224 "description": "",
1225 "minzoom": 0,
1226 "maxzoom": 0,
1227 "fields": {}
1228 }
1229 ],
1230 "tilestats": {
1231 "layerCount": 1,
1232 "layers": [
1233 {
1234 "layer": "test_fixture_1pmtiles",
1235 "count": 1,
1236 "geometry": "Polygon",
1237 "attributeCount": 0,
1238 "attributes": []
1239 }
1240 ]
1241 }
1242 }"#;
1243
1244 let _meta: Metadata =
1245 serde_json::from_str(meta_str).unwrap_or_else(|e| panic!("ERROR: {}", e));
1246 }
1247
1248 #[test]
1249 fn test_mapbox_metadata() {
1250 let meta_str = r#"{
1251 "tilejson": "3.0.0",
1252 "name": "OpenStreetMap",
1253 "description": "A free editable map of the whole world.",
1254 "version": "1.0.0",
1255 "attribution": "(c) OpenStreetMap contributors, CC-BY-SA",
1256 "scheme": "xyz",
1257 "tiles": [
1258 "https://a.tile.custom-osm-tiles.org/{z}/{x}/{y}.mvt",
1259 "https://b.tile.custom-osm-tiles.org/{z}/{x}/{y}.mvt",
1260 "https://c.tile.custom-osm-tiles.org/{z}/{x}/{y}.mvt"
1261 ],
1262 "minzoom": 0,
1263 "maxzoom": 18,
1264 "bounds": [-180, -85, 180, 85],
1265 "fillzoom": 6,
1266 "something_custom": "this is my unique field",
1267 "vector_layers": [
1268 {
1269 "id": "telephone",
1270 "fields": {
1271 "phone_number": "the phone number",
1272 "payment": "how to pay"
1273 }
1274 },
1275 {
1276 "id": "bicycle_parking",
1277 "fields": {
1278 "type": "the type of bike parking",
1279 "year_installed": "the year the bike parking was installed"
1280 }
1281 },
1282 {
1283 "id": "showers",
1284 "fields": {
1285 "water_temperature": "the maximum water temperature",
1286 "wear_sandles": "whether you should wear sandles or not",
1287 "wheelchair": "is the shower wheelchair friendly?"
1288 }
1289 }
1290 ]
1291 }"#;
1292
1293 let meta_mapbox: MapboxTileJSONMetadata =
1294 serde_json::from_str(meta_str).unwrap_or_else(|e| panic!("ERROR: {}", e));
1295 let meta_new = meta_mapbox.to_metadata();
1296 assert_eq!(
1297 meta_new,
1298 Metadata {
1299 name: "OpenStreetMap".into(),
1300 description: "A free editable map of the whole world.".into(),
1301 version: "1.0.0".into(),
1302 scheme: Scheme::Xyz,
1303 type_: "vector".into(),
1304 encoding: "none".into(),
1305 extension: "pbf".into(),
1306 attribution: BTreeMap::new(),
1307 vector_layers: meta_mapbox.vector_layers.clone(),
1308 maxzoom: 18,
1309 minzoom: 0,
1310 center: Center { lat: 0.0, lon: 0.0, zoom: 0 },
1311 bounds: WMBounds::default(),
1312 faces: vec![Face::Face0],
1313 facesbounds: FaceBounds::default(),
1314 tilestats: TileStatsMetadata::default(),
1315 layers: LayersMetaData::default(),
1316 s2tilejson: "1.0.0".into(),
1317 },
1318 );
1319
1320 let meta_mapbox_from_unknown: UnknownMetadata =
1321 serde_json::from_str(meta_str).unwrap_or_else(|e| panic!("ERROR: {}", e));
1322 let meta_new = meta_mapbox_from_unknown.to_metadata();
1323 assert_eq!(
1324 meta_new,
1325 Metadata {
1326 name: "OpenStreetMap".into(),
1327 description: "A free editable map of the whole world.".into(),
1328 version: "1.0.0".into(),
1329 scheme: Scheme::Xyz,
1330 type_: "vector".into(),
1331 encoding: "none".into(),
1332 extension: "pbf".into(),
1333 attribution: BTreeMap::new(),
1334 vector_layers: meta_mapbox.vector_layers.clone(),
1335 maxzoom: 18,
1336 minzoom: 0,
1337 center: Center { lat: 0.0, lon: 0.0, zoom: 0 },
1338 bounds: WMBounds::default(),
1339 faces: vec![Face::Face0],
1340 facesbounds: FaceBounds::default(),
1341 tilestats: TileStatsMetadata::default(),
1342 layers: LayersMetaData::default(),
1343 s2tilejson: "1.0.0".into(),
1344 },
1345 );
1346 }
1347}