1#![doc = include_str!("../README.md")]
2#![forbid(unsafe_code)]
3
4use std::f64::consts::PI;
8use std::fmt::{Display, Formatter};
9use std::io::Read;
10
11use flate2::read::{MultiGzDecoder, ZlibDecoder};
12use strum::EnumIter;
13
14pub const EARTH_CIRCUMFERENCE: f64 = 40_075_016.685_578_5;
16pub const EARTH_CIRCUMFERENCE_DEGREES: u32 = 360;
18
19pub const EARTH_RADIUS: f64 = EARTH_CIRCUMFERENCE / 2.0 / PI;
21
22pub const MAX_ZOOM: u8 = 30;
23
24mod decoders;
25pub use decoders::*;
26mod grid;
27pub use crate::grid::{
28 BUILT_IN_GRIDS, CrsAxes, EUROPEAN_ETRS89_LAEA_QUAD, NZTM2000_QUAD, SIMPLE_CRS, TileGrid, TileGridError,
29 UPS_ANTARCTIC_WGS84_QUAD, UPS_ARCTIC_WGS84_QUAD, WEB_MERCATOR_QUAD, WEB_MERCATOR_QUAD_ID, WGS1984_QUAD_ID,
30 WORLD_CRS84_QUAD, WORLD_CRS84_QUAD_ID, WORLD_MERCATOR_WGS84_QUAD,
31};
32mod rectangle;
33pub use crate::rectangle::{TileRect, append_rect};
34mod coordinate;
35pub use crate::coordinate::TileCoord;
36
37pub type TileData = bytes::Bytes;
38pub type Tile = (TileCoord, Option<TileData>);
39
40#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, EnumIter)]
41pub enum Format {
42 Gif,
43 Jpeg,
44 Json,
45 Mvt,
46 Mlt,
47 Png,
48 Webp,
49 Avif,
50 Jxl,
51}
52
53impl Format {
54 pub const IMAGE_FORMATS: &[Self] = &[Self::Gif, Self::Jpeg, Self::Png, Self::Webp, Self::Avif, Self::Jxl];
56
57 #[must_use]
58 pub fn parse(value: &str) -> Option<Self> {
59 Some(match value.to_ascii_lowercase().as_str() {
60 "gif" => Self::Gif,
61 "jpg" | "jpeg" => Self::Jpeg,
62 "json" => Self::Json,
63 "pbf" | "mvt" => Self::Mvt,
64 "mlt" => Self::Mlt,
65 "png" => Self::Png,
66 "webp" => Self::Webp,
67 "avif" => Self::Avif,
68 "jxl" => Self::Jxl,
69 _ => None?,
70 })
71 }
72
73 #[must_use]
75 pub const fn metadata_format_value(self) -> &'static str {
76 match self {
77 Self::Gif => "gif",
78 Self::Jpeg => "jpeg",
79 Self::Json => "json",
80 Self::Mvt => "pbf",
82 Self::Mlt => "mlt",
83 Self::Png => "png",
84 Self::Webp => "webp",
85 Self::Avif => "avif",
86 Self::Jxl => "jxl",
87 }
88 }
89
90 #[must_use]
91 pub const fn content_type(self) -> &'static str {
92 match self {
93 Self::Gif => "image/gif",
94 Self::Jpeg => "image/jpeg",
95 Self::Json => "application/json",
96 Self::Mvt => "application/x-protobuf",
97 Self::Mlt => "application/vnd.maplibre-tile",
98 Self::Png => "image/png",
99 Self::Webp => "image/webp",
100 Self::Avif => "image/avif",
101 Self::Jxl => "image/jxl",
102 }
103 }
104
105 #[must_use]
107 pub const fn ogc_content_type(self) -> &'static str {
108 match self {
109 Self::Mvt => "application/vnd.mapbox-vector-tile",
110 Self::Gif | Self::Jpeg | Self::Json | Self::Mlt | Self::Png | Self::Webp | Self::Avif | Self::Jxl => {
111 self.content_type()
112 }
113 }
114 }
115
116 #[must_use]
118 pub fn from_content_type(supertype: &str, subtype: &str) -> Option<Self> {
119 Some(match (supertype, subtype) {
120 ("image", "gif") => Self::Gif,
121 ("image", "jpeg" | "jpg") => Self::Jpeg,
122 ("application", "json") => Self::Json,
123 ("application", "x-protobuf" | "vnd.mapbox-vector-tile") => Self::Mvt,
124 ("application", "vnd.maplibre-vector-tile" | "vnd.maplibre-tile") => Self::Mlt,
125 ("image", "png") => Self::Png,
126 ("image", "webp") => Self::Webp,
127 ("image", "avif") => Self::Avif,
128 ("image", "jxl") => Self::Jxl,
129 _ => None?,
130 })
131 }
132
133 #[must_use]
134 pub const fn is_detectable(self) -> bool {
135 match self {
136 Self::Png | Self::Jpeg | Self::Gif | Self::Webp | Self::Avif | Self::Jxl | Self::Json | Self::Mlt => true,
137 Self::Mvt => false,
138 }
139 }
140}
141
142impl Display for Format {
143 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
144 f.write_str(match *self {
145 Self::Gif => "gif",
146 Self::Jpeg => "jpeg",
147 Self::Json => "json",
148 Self::Mvt => "mvt",
149 Self::Mlt => "mlt",
150 Self::Png => "png",
151 Self::Webp => "webp",
152 Self::Avif => "avif",
153 Self::Jxl => "jxl",
154 })
155 }
156}
157
158#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
159pub enum Encoding {
160 Uncompressed = 0b0000_0000,
162 Internal = 0b0000_0001,
164 Gzip = 0b0000_0010,
165 Zlib = 0b0000_0100,
166 Brotli = 0b0000_1000,
167 Zstd = 0b0001_0000,
168}
169
170impl Encoding {
171 #[must_use]
173 pub fn parse(value: &str) -> Option<Self> {
174 Some(match value.to_ascii_lowercase().as_str() {
175 "none" | "identity" => Self::Uncompressed,
176 "gzip" => Self::Gzip,
177 "deflate" | "zlib" => Self::Zlib,
178 "br" | "brotli" => Self::Brotli,
179 "zstd" => Self::Zstd,
180 _ => None?,
181 })
182 }
183
184 #[must_use]
187 pub const fn compression(self) -> Option<&'static str> {
188 match self {
189 Self::Uncompressed | Self::Internal => None,
190 Self::Gzip => Some("gzip"),
191 Self::Zlib => Some("deflate"),
192 Self::Brotli => Some("br"),
193 Self::Zstd => Some("zstd"),
194 }
195 }
196
197 #[must_use]
198 pub const fn is_encoded(self) -> bool {
199 match self {
200 Self::Uncompressed | Self::Internal => false,
201 Self::Gzip | Self::Zlib | Self::Brotli | Self::Zstd => true,
202 }
203 }
204
205 #[must_use]
207 pub fn detect(value: &[u8]) -> Option<Self> {
208 match value {
209 [0x1f, 0x8b, ..] => Some(Self::Gzip),
210 [cmf, flg, ..] if is_zlib_header(*cmf, *flg) => Some(Self::Zlib),
211 _ => None,
212 }
213 }
214}
215
216fn is_zlib_header(cmf: u8, flg: u8) -> bool {
219 cmf & 0x0f == 8 && cmf >> 4 <= 7 && (u16::from(cmf) * 256 + u16::from(flg)) % 31 == 0
220}
221
222#[derive(Clone, Copy, Debug, PartialEq, Eq)]
224pub struct TileInfo {
225 pub format: Format,
227 pub encoding: Encoding,
229}
230
231impl TileInfo {
232 #[must_use]
233 pub const fn new(format: Format, encoding: Encoding) -> Self {
234 Self { format, encoding }
235 }
236
237 #[must_use]
239 pub fn detect(value: &[u8]) -> Self {
240 match Encoding::detect(value) {
241 Some(encoding @ Encoding::Gzip) => Self::detect_inner(&mut MultiGzDecoder::new(value), encoding),
242 Some(encoding @ Encoding::Zlib) => Self::detect_inner(&mut ZlibDecoder::new(value), encoding),
243 _ => match Self::detect_raster_formats(value) {
244 Some(raster_format) => Self::new(raster_format, Encoding::Internal),
245 None => Self::detect_vectorish_format(value).into(),
246 },
247 }
248 }
249
250 fn detect_inner(decoder: &mut impl Read, encoding: Encoding) -> Self {
253 let mut decompressed = Vec::new();
254 let format = if decoder
255 .by_ref()
256 .take(DETECT_PREFIX_LEN)
257 .read_to_end(&mut decompressed)
258 .is_err()
259 || rules_out_mlt_and_json(&decompressed)
260 || decoder.read_to_end(&mut decompressed).is_err()
261 {
262 Format::Mvt
263 } else {
264 Self::detect_vectorish_format(&decompressed)
265 };
266 Self::new(format, encoding)
267 }
268
269 #[must_use]
271 fn detect_raster_formats(value: &[u8]) -> Option<Format> {
272 match value {
273 v if v.starts_with(b"\x89\x50\x4E\x47\x0D\x0A\x1A\x0A") => Some(Format::Png),
274 v if v.starts_with(b"\x47\x49\x46\x38\x39\x61") => Some(Format::Gif),
275 v if v.starts_with(b"\xFF\xD8\xFF") => Some(Format::Jpeg),
276 v if v.starts_with(b"\xFF\x0A") && decode_7bit_length_and_tag(v, MLT_LAYER_TAGS).is_err() => {
277 Some(Format::Jxl)
278 }
279 v if v.starts_with(b"\x00\x00\x00\x0C\x4A\x58\x4C\x20\x0D\x0A\x87\x0A") => Some(Format::Jxl),
280 v if v.starts_with(b"RIFF") && v.len() > 8 && v[8..].starts_with(b"WEBP") => Some(Format::Webp),
281 _ => None,
282 }
283 }
284
285 #[must_use]
287 fn detect_vectorish_format(value: &[u8]) -> Format {
288 match value {
289 v if decode_7bit_length_and_tag(v, MLT_LAYER_TAGS).is_ok() => Format::Mlt,
290 v if is_valid_json(v) => Format::Json,
291 _ => Format::Mvt,
296 }
297 }
298
299 #[must_use]
300 pub const fn encoding(self, encoding: Encoding) -> Self {
301 Self { encoding, ..self }
302 }
303}
304
305impl From<Format> for TileInfo {
306 fn from(format: Format) -> Self {
307 Self::new(
308 format,
309 match format {
310 Format::Mlt | Format::Png | Format::Jpeg | Format::Webp | Format::Gif | Format::Avif | Format::Jxl => {
311 Encoding::Internal
312 }
313 Format::Mvt | Format::Json => Encoding::Uncompressed,
314 },
315 )
316 }
317}
318
319impl Display for TileInfo {
320 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
321 write!(f, "{}", self.format.content_type())?;
322 if let Some(encoding) = self.encoding.compression() {
323 write!(f, "; encoding={encoding}")?;
324 } else if self.encoding != Encoding::Uncompressed {
325 f.write_str("; uncompressed")?;
326 }
327 Ok(())
328 }
329}
330
331#[derive(thiserror::Error, Debug, PartialEq, Eq)]
332enum SevenBitDecodingError {
333 #[error("Expected a tag, but got nothing")]
335 TruncatedTag,
336 #[error("The size of the tile is too large to be decoded")]
338 SizeOverflow,
339 #[error("The size of the tile is lower than the one byte for the tag")]
341 SizeUnderflow,
342 #[error("Expected a size, but got nothing")]
344 TruncatedSize,
345 #[error("Expected {expected} bytes of data in layer according to the size, but got only {actual}")]
347 TruncatedData { expected: u64, actual: u64 },
348 #[error("Got tag {0} instead of the expected")]
350 UnexpectedTag(u8),
351}
352
353fn decode_7bit_length_and_tag(tile: &[u8], versions: &[u8]) -> Result<(), SevenBitDecodingError> {
355 if tile.is_empty() {
356 return Err(SevenBitDecodingError::TruncatedSize);
357 }
358 let mut tile_iter = tile.iter().peekable();
359 while tile_iter.peek().is_some() {
360 let mut size = 0_u64;
362 let mut header_bit_count = 0_u64;
363 loop {
364 header_bit_count += 1;
365 let Some(b) = tile_iter.next() else {
366 return Err(SevenBitDecodingError::TruncatedSize);
367 };
368 if header_bit_count * 7 + 8 > 64 {
369 return Err(SevenBitDecodingError::SizeOverflow);
370 }
371 let seven_bit_mask = !0x80;
373 size |= u64::from(*b & seven_bit_mask) << ((header_bit_count - 1) * 7);
374 if b & 0x80 == 0 {
376 let Some(tag) = tile_iter.next() else {
378 return Err(SevenBitDecodingError::TruncatedTag);
379 };
380 if !versions.contains(tag) {
381 return Err(SevenBitDecodingError::UnexpectedTag(*tag));
382 }
383 let payload_len = size.checked_sub(1).ok_or(SevenBitDecodingError::SizeUnderflow)?;
385 for i in 0..payload_len {
386 if tile_iter.next().is_none() {
387 return Err(SevenBitDecodingError::TruncatedData {
388 expected: payload_len,
389 actual: i,
390 });
391 }
392 }
393 break;
394 }
395 }
396 }
397 Ok(())
398}
399
400fn is_valid_json(tile: &[u8]) -> bool {
404 tile.starts_with(b"{") && tile.ends_with(b"}") && serde_json::from_slice::<serde::de::IgnoredAny>(tile).is_ok()
405}
406
407const MLT_LAYER_TAGS: &[u8] = &[0x1, 0x2];
409
410const DETECT_PREFIX_LEN: u64 = 16;
412
413fn rules_out_mlt_and_json(prefix: &[u8]) -> bool {
415 !prefix.starts_with(b"{")
416 && matches!(
417 decode_7bit_length_and_tag(prefix, MLT_LAYER_TAGS),
418 Err(SevenBitDecodingError::UnexpectedTag(_)
419 | SevenBitDecodingError::SizeOverflow
420 | SevenBitDecodingError::SizeUnderflow)
421 )
422}
423
424#[must_use]
426#[expect(clippy::cast_possible_truncation)]
427#[expect(clippy::cast_sign_loss)]
428pub fn tile_index(lng: f64, lat: f64, zoom: u8) -> (u32, u32) {
429 let tile_size = EARTH_CIRCUMFERENCE / f64::from(1_u32 << zoom);
430 let (x, y) = wgs84_to_webmercator(lng, lat);
431 let col = ((EARTH_CIRCUMFERENCE.mul_add(0.5, x).abs() / tile_size) as u32).min((1 << zoom) - 1);
432 let row = ((EARTH_CIRCUMFERENCE.mul_add(0.5, -y).abs() / tile_size) as u32).min((1 << zoom) - 1);
433 (col, row)
434}
435
436#[must_use]
443pub fn xyz_to_bbox(zoom: u8, min_x: u32, min_y: u32, max_x: u32, max_y: u32) -> [f64; 4] {
444 assert!(zoom <= MAX_ZOOM, "zoom {zoom} must be <= {MAX_ZOOM}");
445
446 let tile_length = EARTH_CIRCUMFERENCE / f64::from(1_u32 << zoom);
447
448 let left_down_bbox = tile_bbox(min_x, max_y, tile_length);
449 let right_top_bbox = tile_bbox(max_x, min_y, tile_length);
450
451 let (min_lng, min_lat) = webmercator_to_wgs84(left_down_bbox[0], left_down_bbox[1]);
452 let (max_lng, max_lat) = webmercator_to_wgs84(right_top_bbox[2], right_top_bbox[3]);
453 [min_lng, min_lat, max_lng, max_lat]
454}
455
456#[expect(clippy::cast_lossless)]
457#[must_use]
458pub fn tile_bbox(x: u32, y: u32, tile_length: f64) -> [f64; 4] {
459 let min_x = (x as f64).mul_add(tile_length, EARTH_CIRCUMFERENCE * -0.5);
460 let max_y = (y as f64).mul_add(-tile_length, EARTH_CIRCUMFERENCE * 0.5);
461
462 [min_x, max_y - tile_length, min_x + tile_length, max_y]
463}
464
465#[must_use]
467pub fn bbox_to_xyz(left: f64, bottom: f64, right: f64, top: f64, zoom: u8) -> (u32, u32, u32, u32) {
468 let (min_col, min_row) = tile_index(left, top, zoom);
469 let (max_col, max_row) = tile_index(right, bottom, zoom);
470 (min_col, min_row, max_col, max_row)
471}
472
473#[must_use]
475#[expect(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
476pub fn get_zoom_precision(zoom: u8) -> usize {
477 assert!(zoom <= MAX_ZOOM, "zoom {zoom} must be <= {MAX_ZOOM}");
478 let lng_delta = webmercator_to_wgs84(EARTH_CIRCUMFERENCE / f64::from(1_u32 << zoom), 0.0).0;
479 let log = lng_delta.log10() - 0.5;
480 if log > 0.0 { 0 } else { -log.ceil() as usize }
481}
482
483#[must_use]
486pub fn webmercator_to_wgs84(x: f64, y: f64) -> (f64, f64) {
487 let lng = (x / EARTH_RADIUS).to_degrees();
488 let lat = f64::atan(f64::sinh(y / EARTH_RADIUS)).to_degrees();
489 (lng, lat)
490}
491
492#[must_use]
495pub fn wgs84_to_webmercator(lon: f64, lat: f64) -> (f64, f64) {
496 let x = lon.to_radians() * EARTH_RADIUS;
497
498 let y_sin = lat.to_radians().sin();
499 let y = EARTH_RADIUS / 2.0 * ((1.0 + y_sin) / (1.0 - y_sin)).ln();
500
501 (x, y)
502}
503
504#[cfg(test)]
505mod tests {
506 use rstest::rstest;
507
508 use super::*;
509
510 #[rstest]
511 #[case::minimal_tile(&[0x01, 0x01], Ok(()))]
512 #[case::one_byte_length(&[0x02, 0x01, 0xaa], Ok(()))]
513 #[case::two_byte_length(&[[0xac_u8, 0x02, 0x01].as_slice(), &[0xaa; 299]].concat(), Ok(()))]
514 #[case::multi_byte_length(&[[0x80_u8, 0x80, 0x01, 0x01].as_slice(), &[0xdd; 16383]].concat(), Ok(()))]
515 #[case::wrong_version(&[0x03, 0x02, 0xaa], Err(SevenBitDecodingError::UnexpectedTag(0x02)))]
516 #[case::empty_input(&[], Err(SevenBitDecodingError::TruncatedSize))]
517 #[case::size_overflow(&[0xFF; 64], Err(SevenBitDecodingError::SizeOverflow))]
518 #[case::size_underflow(&[0x00, 0x01], Err(SevenBitDecodingError::SizeUnderflow))]
519 #[case::unterminated_length(&[0x80], Err(SevenBitDecodingError::TruncatedSize))]
520 #[case::missing_version_byte(&[0x05], Err(SevenBitDecodingError::TruncatedTag))]
521 #[case::wrong_length(&[0x03, 0x01], Err(SevenBitDecodingError::TruncatedData { expected: 2, actual: 0 }))]
522 fn test_decode_7bit_length_and_tag(#[case] tile: &[u8], #[case] expected: Result<(), SevenBitDecodingError>) {
523 let allowed_versions = &[0x01_u8];
524 let decoded = decode_7bit_length_and_tag(tile, allowed_versions);
525 assert_eq!(decoded, expected, "can decode one layer correctly");
526
527 if tile.is_empty() {
528 return;
529 }
530 let mut tile_with_two_layers = vec![0x01, 0x01];
531 tile_with_two_layers.extend_from_slice(tile);
532 let decoded = decode_7bit_length_and_tag(&tile_with_two_layers, allowed_versions);
533 assert_eq!(decoded, expected, "can decode two layers correctly");
534 }
535}