mvt-reader 2.4.0

A library for decoding and reading mapbox vector tiles in Rust and WebAssembly
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
//! # mvt-reader
//!
//! `mvt-reader` is a Rust library for decoding and reading Mapbox vector tiles.
//!
//! It provides the `Reader` struct, which allows you to read vector tiles and access their layers and features.
//!
//! # Usage
//!
//! To use the `mvt-reader` library in your Rust project, add the following to your `Cargo.toml` file:
//!
//! ```toml
//! [dependencies]
//! mvt-reader = "2.4.0"
//! ```
//!
//! Then, you can import and use the library in your code:
//!
//! ```rust
//! use mvt_reader::{Reader, error::{ParserError}};
//!
//! fn main() -> Result<(), ParserError> {
//!   // Read a vector tile from file or data
//!   let data = vec![/* Vector tile data */];
//!   let reader = Reader::new(data)?;
//!
//!   // Get layer names
//!   let layer_names = reader.get_layer_names()?;
//!   for name in layer_names {
//!     println!("Layer: {}", name);
//!   }
//!
//!   // Get features for a specific layer
//!   let layer_index = 0;
//!   let features = reader.get_features(layer_index)?;
//!   for feature in features {
//!     todo!()
//!   }
//!
//!   Ok(())
//! }
//! ```
//!
//! # Features
//!
//! The `mvt-reader` library provides the following features:
//!
//! - `wasm`: Enables the compilation of the library as a WebAssembly module, allowing usage in JavaScript/TypeScript projects.
//! - `protoc`: Enables the use of `prost-build` to compile the protobuf definition sources from `vector_tile.proto`. This is useful for development and testing purposes, but it is not required for using the library in production. If the `protoc` feature is not enabled, the library will use pre-generated Rust code for the protobuf definitions.
//!
//! To enable the `wasm` feature, add the following to your `Cargo.toml` file:
//!
//! ```toml
//! [dependencies]
//! mvt-reader = { version = "2.4.0", features = ["wasm"] }
//! ```
//! 
//! To enable the `protoc` feature, add the following to your `Cargo.toml` file:
//! 
//! ```toml
//! [dependencies]
//! mvt-reader = { version = "2.4.0", features = ["protoc"] }
//! ```
//!
//! # License
//!
//! This project is licensed under the [MIT License](https://github.com/codeart1st/mvt-reader/blob/main/LICENSE).

pub mod error;
pub mod feature;
pub mod layer;

mod vector_tile;

use feature::{Feature, Value};
use geo_types::{
  Coord, CoordNum, Geometry, LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon,
};
use layer::Layer;
use num_traits::NumCast;
use prost::{Message, bytes::Bytes};
use vector_tile::{Tile, tile::GeomType};

/// The dimension used for the vector tile.
const DIMENSION: u32 = 2;

/// Reader for decoding and accessing vector tile data.
pub struct Reader {
  tile: Tile,
}

impl Reader {
  /// Creates a new `Reader` instance with the provided vector tile data.
  ///
  /// # Arguments
  ///
  /// * `data` - The vector tile data as a byte vector.
  ///
  /// # Returns
  ///
  /// A result containing the `Reader` instance if successful, or a `DecodeError` if decoding the vector tile data fails.
  ///
  /// # Examples
  ///
  /// ```
  /// use mvt_reader::Reader;
  ///
  /// let data = vec![/* Vector tile data */];
  /// let reader = Reader::new(data);
  /// ```
  pub fn new(data: Vec<u8>) -> Result<Self, error::ParserError> {
    let tile = Tile::decode(Bytes::from(data))?;
    Ok(Self { tile })
  }

  /// Retrieves the names of the layers in the vector tile.
  ///
  /// # Returns
  ///
  /// A result containing a vector of layer names if successful, or a `ParserError` if there is an error parsing the tile.
  ///
  /// # Examples
  ///
  /// ```
  /// use mvt_reader::Reader;
  ///
  /// let data = vec![/* Vector tile data */];
  /// let reader = Reader::new(data).unwrap();
  ///
  /// match reader.get_layer_names() {
  ///   Ok(layer_names) => {
  ///     for name in layer_names {
  ///       println!("Layer: {}", name);
  ///     }
  ///   }
  ///   Err(error) => {
  ///     todo!();
  ///   }
  /// }
  /// ```
  pub fn get_layer_names(&self) -> Result<Vec<String>, error::ParserError> {
    process_layers(&self.tile.layers, |layer, _| layer.name.clone())
  }

  /// Retrieves metadata about the layers in the vector tile.
  ///
  /// # Returns
  ///
  /// A result containing a vector of `Layer` structs if successful, or a `ParserError` if there is an error parsing the tile.
  ///
  /// # Examples
  ///
  /// ```
  /// use mvt_reader::Reader;
  ///
  /// let data = vec![/* Vector tile data */];
  /// let reader = Reader::new(data).unwrap();
  ///
  /// match reader.get_layer_metadata() {
  ///   Ok(layers) => {
  ///     for layer in layers {
  ///       println!("Layer: {}", layer.name);
  ///       println!("Extent: {}", layer.extent);
  ///     }
  ///   }
  ///   Err(error) => {
  ///     todo!();
  ///   }
  /// }
  /// ```
  pub fn get_layer_metadata(&self) -> Result<Vec<Layer>, error::ParserError> {
    process_layers(&self.tile.layers, |layer, index| Layer {
      layer_index: index,
      version: layer.version,
      name: layer.name.clone(),
      feature_count: layer.features.len(),
      extent: layer.extent.unwrap_or(4096),
    })
  }

  /// Retrieves the features of a specific layer in the vector tile.
  ///
  /// # Arguments
  ///
  /// * `layer_index` - The index of the layer.
  ///
  /// # Returns
  ///
  /// A result containing a vector of features if successful, or a `ParserError` if there is an error parsing the tile or accessing the layer.
  ///
  /// # Examples
  ///
  /// ```
  /// use mvt_reader::Reader;
  ///
  /// let data = vec![/* Vector tile data */];
  /// let reader = Reader::new(data).unwrap();
  ///
  /// match reader.get_features(0) {
  ///   Ok(features) => {
  ///     for feature in features {
  ///       todo!();
  ///     }
  ///   }
  ///   Err(error) => {
  ///     todo!();
  ///   }
  /// }
  /// ```
  pub fn get_features(&self, layer_index: usize) -> Result<Vec<Feature>, error::ParserError> {
    self.get_features_as::<f32>(layer_index)
  }

  /// Retrieves the features of a specific layer with geometry coordinates in the specified numeric type.
  ///
  /// This is a generic version of [`get_features`](Reader::get_features) that allows you to choose
  /// the coordinate type for the geometry. Supported types include `f32` (default), `i32`, and `i16`.
  ///
  /// # Arguments
  ///
  /// * `layer_index` - The index of the layer.
  ///
  /// # Type Parameters
  ///
  /// * `T` - The numeric type for geometry coordinates (e.g. `f32`, `i32`, `i16`).
  ///
  /// # Returns
  ///
  /// A result containing a vector of features if successful, or a `ParserError` if there is an error parsing the tile or accessing the layer.
  ///
  /// # Examples
  ///
  /// ```
  /// use mvt_reader::Reader;
  ///
  /// let data = vec![/* Vector tile data */];
  /// let reader = Reader::new(data).unwrap();
  ///
  /// // Get features with i32 coordinates
  /// let features = reader.get_features_as::<i32>(0);
  ///
  /// // Get features with i16 coordinates
  /// let features = reader.get_features_as::<i16>(0);
  /// ```
  pub fn get_features_as<T: CoordNum>(&self, layer_index: usize) -> Result<Vec<Feature<T>>, error::ParserError> {
    let layer = self.tile.layers.get(layer_index);
    match layer {
      Some(layer) => {
        let mut features = Vec::with_capacity(layer.features.len());
        for feature in layer.features.iter() {
          if let Some(geom_type) = feature.r#type {
            let geom_type = GeomType::try_from(geom_type).map_err(|_| error::ParserError::InvalidGeometry)?;
            let parsed_geometry = parse_geometry::<T>(&feature.geometry, geom_type)?;
            let parsed_tags = parse_tags(&feature.tags, &layer.keys, &layer.values)?;

            features.push(Feature {
              geometry: parsed_geometry,
              id: feature.id,
              properties: Some(parsed_tags),
            });
          }
        }
        Ok(features)
      }
      None => Ok(vec![]),
    }
  }
}

fn process_layers<T, F>(
  layers: &[vector_tile::tile::Layer],
  mut processor: F,
) -> Result<Vec<T>, error::ParserError>
where
  F: FnMut(&vector_tile::tile::Layer, usize) -> T,
{
  let mut results = Vec::with_capacity(layers.len());
  for (index, layer) in layers.iter().enumerate() {
    match layer.version {
      1 | 2 => results.push(processor(layer, index)),
      _ => {
        return Err(error::ParserError::UnsupportedVersion {
          layer_name: layer.name.clone(),
          version: layer.version,
        });
      }
    }
  }
  Ok(results)
}

fn parse_tags(
  tags: &[u32],
  keys: &[String],
  values: &[vector_tile::tile::Value],
) -> Result<std::collections::HashMap<String, Value>, error::ParserError> {
  let mut result = std::collections::HashMap::new();
  for item in tags.chunks(2) {
    if item.len() != 2
      || item[0] as usize >= keys.len()
      || item[1] as usize >= values.len()
    {
      return Err(error::ParserError::InvalidTags);
    }
    result.insert(
      keys[item[0] as usize].clone(),
      map_value(values[item[1] as usize].clone()),
    );
  }
  Ok(result)
}

fn map_value(value: vector_tile::tile::Value) -> Value {
  if let Some(s) = value.string_value {
    return Value::String(s);
  }
  if let Some(f) = value.float_value {
    return Value::Float(f);
  }
  if let Some(d) = value.double_value {
    return Value::Double(d);
  }
  if let Some(i) = value.int_value {
    return Value::Int(i);
  }
  if let Some(u) = value.uint_value {
    return Value::UInt(u);
  }
  if let Some(s) = value.sint_value {
    return Value::SInt(s);
  }
  if let Some(b) = value.bool_value {
    return Value::Bool(b);
  }
  Value::Null
}

fn shoelace_formula<T: CoordNum>(points: &[Point<T>]) -> f32 {
  let mut area: f32 = 0.0;
  let n = points.len();
  let mut v1 = points[n - 1];
  for v2 in points.iter().take(n) {
    let v2y: f32 = NumCast::from(v2.y()).unwrap_or(0.0);
    let v1y: f32 = NumCast::from(v1.y()).unwrap_or(0.0);
    let v2x: f32 = NumCast::from(v2.x()).unwrap_or(0.0);
    let v1x: f32 = NumCast::from(v1.x()).unwrap_or(0.0);
    area += (v2y - v1y) * (v2x + v1x);
    v1 = *v2;
  }
  area * 0.5
}

fn parse_geometry<T: CoordNum>(
  geometry_data: &[u32],
  geom_type: GeomType,
) -> Result<Geometry<T>, error::ParserError> {
  if geom_type == GeomType::Unknown {
    return Err(error::ParserError::InvalidGeometry);
  }

  // worst case capacity to prevent reallocation. not needed to be exact.
  let mut coordinates: Vec<Coord<T>> = Vec::with_capacity(geometry_data.len());
  let mut polygons: Vec<Polygon<T>> = Vec::new();
  let mut linestrings: Vec<LineString<T>> = Vec::new();

  let mut cursor: [i32; 2] = [0, 0];
  let mut parameter_count: u32 = 0;

  for value in geometry_data.iter() {
    if parameter_count == 0 {
      let command_integer = value;
      let id = (command_integer & 0x7) as u8;
      match id {
        1 => {
          // MoveTo
          parameter_count = (command_integer >> 3) * DIMENSION;
          if geom_type == GeomType::Linestring && !coordinates.is_empty() {
            linestrings.push(LineString::new(coordinates));
            // start with a new linestring
            coordinates = Vec::with_capacity(geometry_data.len());
          }
        }
        2 => {
          // LineTo
          parameter_count = (command_integer >> 3) * DIMENSION;
        }
        7 => {
          // ClosePath
          let first_coordinate = match coordinates.first() {
            Some(coord) => coord.to_owned(),
            None => {
              return Err(error::ParserError::InvalidGeometry);
            }
          };
          coordinates.push(first_coordinate);

          let ring = LineString::new(coordinates);

          let area = shoelace_formula(&ring.clone().into_points());

          if area > 0.0 {
            // exterior ring
            if !linestrings.is_empty() {
              // finish previous geometry
              polygons.push(Polygon::new(
                linestrings[0].clone(),
                linestrings[1..].into(),
              ));
              linestrings = Vec::new();
            }
          }

          linestrings.push(ring);
          // start a new sequence
          coordinates = Vec::with_capacity(geometry_data.len());
        }
        _ => (),
      }
    } else {
      let parameter_integer = value;
      let integer_value = ((parameter_integer >> 1) as i32) ^ -((parameter_integer & 1) as i32);
      if parameter_count.is_multiple_of(DIMENSION) {
        cursor[0] = match cursor[0].checked_add(integer_value) {
          Some(result) => result,
          None => i32::MAX, // clip value
        };
      } else {
        cursor[1] = match cursor[1].checked_add(integer_value) {
          Some(result) => result,
          None => i32::MAX, // clip value
        };
        let x = NumCast::from(cursor[0])
          .ok_or(error::ParserError::CoordinateOverflow { value: cursor[0] })?;
        let y = NumCast::from(cursor[1])
          .ok_or(error::ParserError::CoordinateOverflow { value: cursor[1] })?;
        coordinates.push(Coord { x, y });
      }
      parameter_count -= 1;
    }
  }

  match geom_type {
    GeomType::Linestring => {
      // the last linestring is in coordinates vec
      if !linestrings.is_empty() {
        linestrings.push(LineString::new(coordinates));
        return Ok(MultiLineString::new(linestrings).into());
      }
      Ok(LineString::new(coordinates).into())
    }
    GeomType::Point => Ok(
      MultiPoint(
        coordinates
          .iter()
          .map(|coord| Point::new(coord.x, coord.y))
          .collect(),
      )
      .into(),
    ),
    GeomType::Polygon => {
      if !linestrings.is_empty() {
        // finish pending polygon
        polygons.push(Polygon::new(
          linestrings[0].clone(),
          linestrings[1..].into(),
        ));
        return Ok(MultiPolygon::new(polygons).into());
      }
      match polygons.first() {
        Some(polygon) => Ok(polygon.to_owned().into()),
        None => Err(error::ParserError::InvalidGeometry),
      }
    }
    GeomType::Unknown => Err(error::ParserError::InvalidGeometry),
  }
}

#[cfg(feature = "wasm")]
pub mod wasm {

  use crate::feature::Value;
  use geojson::{Feature, GeoJson, JsonObject, JsonValue, feature::Id};
  use serde::ser::{Serialize, SerializeStruct};
  use serde_wasm_bindgen::Serializer;
  use wasm_bindgen::prelude::*;

  /// Converts a `Value` into a `serde_json::Value`.
  impl From<Value> for JsonValue {
    fn from(value: Value) -> Self {
      match value {
        Value::Null => JsonValue::Null,
        Value::Bool(b) => JsonValue::from(b),
        Value::Int(i) => JsonValue::from(i),
        Value::UInt(u) => JsonValue::from(u),
        Value::SInt(s) => JsonValue::from(s),
        Value::Float(f) => JsonValue::from(f),
        Value::Double(d) => JsonValue::from(d),
        Value::String(s) => JsonValue::from(s),
      }
    }
  }

  /// Converts a `super::feature::Feature` into a `wasm_bindgen::JsValue`.
  impl From<super::feature::Feature> for wasm_bindgen::JsValue {
    fn from(feature: super::feature::Feature) -> Self {
      let properties: Option<JsonObject> = feature.properties.as_ref().map(|props| {
        props
          .clone()
          .into_iter()
          .map(|(k, v)| (k, v.into()))
          .collect()
      });

      let geojson = GeoJson::Feature(Feature {
        bbox: None,
        geometry: Some(feature.get_geometry().into()),
        id: feature.id.map(|id| Id::Number(id.into())),
        properties,
        foreign_members: None,
      });

      geojson.serialize(&Serializer::json_compatible()).unwrap()
    }
  }

  /// Converts a `super::layer::Layer` into a `wasm_bindgen::JsValue`.
  impl From<super::layer::Layer> for wasm_bindgen::JsValue {
    fn from(layer: super::layer::Layer) -> Self {
      layer.serialize(&Serializer::json_compatible()).unwrap()
    }
  }

  impl Serialize for super::layer::Layer {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
      S: serde::ser::Serializer,
    {
      let mut state = serializer.serialize_struct("Layer", 5)?;
      state.serialize_field("layer_index", &self.layer_index)?;
      state.serialize_field("version", &self.version)?;
      state.serialize_field("name", &self.name)?;
      state.serialize_field("feature_count", &self.feature_count)?;
      state.serialize_field("extent", &self.extent)?;
      state.end()
    }
  }

  /// Reader for decoding and accessing vector tile data in WebAssembly.
  #[wasm_bindgen]
  pub struct Reader {
    reader: Option<super::Reader>,
  }

  #[wasm_bindgen]
  impl Reader {
    /// Creates a new `Reader` instance with the provided vector tile data.
    ///
    /// # Arguments
    ///
    /// * `data` - The vector tile data as a `Vec<u8>`.
    /// * `error_callback` - An optional JavaScript callback function to handle errors. It should accept a single parameter which will contain the error message as a string.
    ///
    /// # Examples
    ///
    /// ```
    /// let tileData = getVectorTileData();
    /// let reader = new Reader(tileData, handleErrors);
    /// ```
    #[wasm_bindgen(constructor)]
    pub fn new(data: Vec<u8>, error_callback: Option<js_sys::Function>) -> Reader {
      let reader = match super::Reader::new(data) {
        Ok(reader) => Some(reader),
        Err(error) => {
          if let Some(callback) = error_callback {
            callback
              .call1(&JsValue::NULL, &JsValue::from_str(&format!("{:?}", error)))
              .unwrap();
          }
          None
        }
      };
      Reader { reader }
    }

    /// Retrieves the layer names present in the vector tile.
    ///
    /// # Arguments
    ///
    /// * `error_callback` - An optional JavaScript callback function to handle errors. It should accept a single parameter which will contain the error message as a string.
    ///
    /// # Returns
    ///
    /// A JavaScript array containing the layer names as strings.
    ///
    /// # Examples
    ///
    /// ```
    /// let layerNames = reader.getLayerNames(handleErrors);
    /// for (let i = 0; i < layerNames.length; i++) {
    ///   console.log(layerNames[i]);
    /// }
    /// ```
    #[wasm_bindgen(js_name = getLayerNames)]
    pub fn get_layer_names(&self, error_callback: Option<js_sys::Function>) -> JsValue {
      self.handle_result(|reader| reader.get_layer_names(), error_callback)
    }

    /// Retrieves the layer metadata present in the vector tile.
    ///
    /// # Arguments
    ///
    /// * `error_callback` - An optional JavaScript callback function to handle errors. It should accept a single parameter which will contain the error message as a string.
    ///
    /// # Returns
    ///
    /// A JavaScript array containing the layer metadata as objects.
    ///
    /// # Examples
    ///
    /// ```
    /// let layers = reader.getLayerMetadata(handleErrors);
    /// for (let i = 0; i < layers.length; i++) {
    ///   console.log(layers[i].name);
    /// }
    /// ```
    #[wasm_bindgen(js_name = getLayerMetadata)]
    pub fn get_layer_metadata(&self, error_callback: Option<js_sys::Function>) -> JsValue {
      self.handle_result(|reader| reader.get_layer_metadata(), error_callback)
    }

    /// Retrieves the features of a specific layer in the vector tile.
    ///
    /// # Arguments
    ///
    /// * `layer_index` - The index of the layer to retrieve features from.
    /// * `error_callback` - An optional JavaScript callback function to handle errors. It should accept a single parameter which will contain the error message as a string.
    ///
    /// # Returns
    ///
    /// A JavaScript array containing the features as GeoJSON objects.
    ///
    /// # Examples
    ///
    /// ```
    /// let features = reader.getFeatures(0, handleErrors);
    /// for (let i = 0; i < features.length; i++) {
    ///   console.log(features[i]);
    /// }
    /// ```
    #[wasm_bindgen(js_name = getFeatures)]
    pub fn get_features(
      &self,
      layer_index: usize,
      error_callback: Option<js_sys::Function>,
    ) -> JsValue {
      self.handle_result(|reader| reader.get_features(layer_index), error_callback)
    }

    fn handle_result<T, F>(&self, operation: F, error_callback: Option<js_sys::Function>) -> JsValue
    where
      T: IntoIterator,
      T::Item: Into<JsValue>,
      F: FnOnce(&super::Reader) -> Result<T, super::error::ParserError>,
    {
      match &self.reader {
        Some(reader) => match operation(reader) {
          Ok(result) => result
            .into_iter()
            .map(Into::into)
            .collect::<js_sys::Array>()
            .into(),
          Err(error) => {
            if let Some(callback) = error_callback {
              callback
                .call1(&JsValue::NULL, &JsValue::from_str(&format!("{:?}", error)))
                .unwrap();
            }
            JsValue::NULL
          }
        },
        None => JsValue::NULL,
      }
    }
  }
}