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, &[0x1]).is_err() => Some(Format::Jxl),
277 v if v.starts_with(b"\x00\x00\x00\x0C\x4A\x58\x4C\x20\x0D\x0A\x87\x0A") => Some(Format::Jxl),
278 v if v.starts_with(b"RIFF") && v.len() > 8 && v[8..].starts_with(b"WEBP") => Some(Format::Webp),
279 _ => None,
280 }
281 }
282
283 #[must_use]
285 fn detect_vectorish_format(value: &[u8]) -> Format {
286 match value {
287 v if decode_7bit_length_and_tag(v, &[0x1]).is_ok() => Format::Mlt,
288 v if is_valid_json(v) => Format::Json,
289 _ => Format::Mvt,
294 }
295 }
296
297 #[must_use]
298 pub const fn encoding(self, encoding: Encoding) -> Self {
299 Self { encoding, ..self }
300 }
301}
302
303impl From<Format> for TileInfo {
304 fn from(format: Format) -> Self {
305 Self::new(
306 format,
307 match format {
308 Format::Mlt | Format::Png | Format::Jpeg | Format::Webp | Format::Gif | Format::Avif | Format::Jxl => {
309 Encoding::Internal
310 }
311 Format::Mvt | Format::Json => Encoding::Uncompressed,
312 },
313 )
314 }
315}
316
317impl Display for TileInfo {
318 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
319 write!(f, "{}", self.format.content_type())?;
320 if let Some(encoding) = self.encoding.compression() {
321 write!(f, "; encoding={encoding}")?;
322 } else if self.encoding != Encoding::Uncompressed {
323 f.write_str("; uncompressed")?;
324 }
325 Ok(())
326 }
327}
328
329#[derive(thiserror::Error, Debug, PartialEq, Eq)]
330enum SevenBitDecodingError {
331 #[error("Expected a tag, but got nothing")]
333 TruncatedTag,
334 #[error("The size of the tile is too large to be decoded")]
336 SizeOverflow,
337 #[error("The size of the tile is lower than the one byte for the tag")]
339 SizeUnderflow,
340 #[error("Expected a size, but got nothing")]
342 TruncatedSize,
343 #[error("Expected {expected} bytes of data in layer according to the size, but got only {actual}")]
345 TruncatedData { expected: u64, actual: u64 },
346 #[error("Got tag {0} instead of the expected")]
348 UnexpectedTag(u8),
349}
350
351fn decode_7bit_length_and_tag(tile: &[u8], versions: &[u8]) -> Result<(), SevenBitDecodingError> {
353 if tile.is_empty() {
354 return Err(SevenBitDecodingError::TruncatedSize);
355 }
356 let mut tile_iter = tile.iter().peekable();
357 while tile_iter.peek().is_some() {
358 let mut size = 0_u64;
360 let mut header_bit_count = 0_u64;
361 loop {
362 header_bit_count += 1;
363 let Some(b) = tile_iter.next() else {
364 return Err(SevenBitDecodingError::TruncatedSize);
365 };
366 if header_bit_count * 7 + 8 > 64 {
367 return Err(SevenBitDecodingError::SizeOverflow);
368 }
369 let seven_bit_mask = !0x80;
371 size |= u64::from(*b & seven_bit_mask) << ((header_bit_count - 1) * 7);
372 if b & 0x80 == 0 {
374 let Some(tag) = tile_iter.next() else {
376 return Err(SevenBitDecodingError::TruncatedTag);
377 };
378 if !versions.contains(tag) {
379 return Err(SevenBitDecodingError::UnexpectedTag(*tag));
380 }
381 let payload_len = size.checked_sub(1).ok_or(SevenBitDecodingError::SizeUnderflow)?;
383 for i in 0..payload_len {
384 if tile_iter.next().is_none() {
385 return Err(SevenBitDecodingError::TruncatedData {
386 expected: payload_len,
387 actual: i,
388 });
389 }
390 }
391 break;
392 }
393 }
394 }
395 Ok(())
396}
397
398fn is_valid_json(tile: &[u8]) -> bool {
402 tile.starts_with(b"{") && tile.ends_with(b"}") && serde_json::from_slice::<serde::de::IgnoredAny>(tile).is_ok()
403}
404
405const DETECT_PREFIX_LEN: u64 = 16;
407
408fn rules_out_mlt_and_json(prefix: &[u8]) -> bool {
410 !prefix.starts_with(b"{")
411 && matches!(
412 decode_7bit_length_and_tag(prefix, &[0x1]),
413 Err(SevenBitDecodingError::UnexpectedTag(_)
414 | SevenBitDecodingError::SizeOverflow
415 | SevenBitDecodingError::SizeUnderflow)
416 )
417}
418
419#[must_use]
421#[expect(clippy::cast_possible_truncation)]
422#[expect(clippy::cast_sign_loss)]
423pub fn tile_index(lng: f64, lat: f64, zoom: u8) -> (u32, u32) {
424 let tile_size = EARTH_CIRCUMFERENCE / f64::from(1_u32 << zoom);
425 let (x, y) = wgs84_to_webmercator(lng, lat);
426 let col = ((EARTH_CIRCUMFERENCE.mul_add(0.5, x).abs() / tile_size) as u32).min((1 << zoom) - 1);
427 let row = ((EARTH_CIRCUMFERENCE.mul_add(0.5, -y).abs() / tile_size) as u32).min((1 << zoom) - 1);
428 (col, row)
429}
430
431#[must_use]
438pub fn xyz_to_bbox(zoom: u8, min_x: u32, min_y: u32, max_x: u32, max_y: u32) -> [f64; 4] {
439 assert!(zoom <= MAX_ZOOM, "zoom {zoom} must be <= {MAX_ZOOM}");
440
441 let tile_length = EARTH_CIRCUMFERENCE / f64::from(1_u32 << zoom);
442
443 let left_down_bbox = tile_bbox(min_x, max_y, tile_length);
444 let right_top_bbox = tile_bbox(max_x, min_y, tile_length);
445
446 let (min_lng, min_lat) = webmercator_to_wgs84(left_down_bbox[0], left_down_bbox[1]);
447 let (max_lng, max_lat) = webmercator_to_wgs84(right_top_bbox[2], right_top_bbox[3]);
448 [min_lng, min_lat, max_lng, max_lat]
449}
450
451#[expect(clippy::cast_lossless)]
452#[must_use]
453pub fn tile_bbox(x: u32, y: u32, tile_length: f64) -> [f64; 4] {
454 let min_x = (x as f64).mul_add(tile_length, EARTH_CIRCUMFERENCE * -0.5);
455 let max_y = (y as f64).mul_add(-tile_length, EARTH_CIRCUMFERENCE * 0.5);
456
457 [min_x, max_y - tile_length, min_x + tile_length, max_y]
458}
459
460#[must_use]
462pub fn bbox_to_xyz(left: f64, bottom: f64, right: f64, top: f64, zoom: u8) -> (u32, u32, u32, u32) {
463 let (min_col, min_row) = tile_index(left, top, zoom);
464 let (max_col, max_row) = tile_index(right, bottom, zoom);
465 (min_col, min_row, max_col, max_row)
466}
467
468#[must_use]
470#[expect(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
471pub fn get_zoom_precision(zoom: u8) -> usize {
472 assert!(zoom <= MAX_ZOOM, "zoom {zoom} must be <= {MAX_ZOOM}");
473 let lng_delta = webmercator_to_wgs84(EARTH_CIRCUMFERENCE / f64::from(1_u32 << zoom), 0.0).0;
474 let log = lng_delta.log10() - 0.5;
475 if log > 0.0 { 0 } else { -log.ceil() as usize }
476}
477
478#[must_use]
481pub fn webmercator_to_wgs84(x: f64, y: f64) -> (f64, f64) {
482 let lng = (x / EARTH_RADIUS).to_degrees();
483 let lat = f64::atan(f64::sinh(y / EARTH_RADIUS)).to_degrees();
484 (lng, lat)
485}
486
487#[must_use]
490pub fn wgs84_to_webmercator(lon: f64, lat: f64) -> (f64, f64) {
491 let x = lon.to_radians() * EARTH_RADIUS;
492
493 let y_sin = lat.to_radians().sin();
494 let y = EARTH_RADIUS / 2.0 * ((1.0 + y_sin) / (1.0 - y_sin)).ln();
495
496 (x, y)
497}
498
499#[cfg(test)]
500mod tests {
501 use rstest::rstest;
502
503 use super::*;
504
505 #[rstest]
506 #[case::minimal_tile(&[0x01, 0x01], Ok(()))]
507 #[case::one_byte_length(&[0x02, 0x01, 0xaa], Ok(()))]
508 #[case::two_byte_length(&[[0xac_u8, 0x02, 0x01].as_slice(), &[0xaa; 299]].concat(), Ok(()))]
509 #[case::multi_byte_length(&[[0x80_u8, 0x80, 0x01, 0x01].as_slice(), &[0xdd; 16383]].concat(), Ok(()))]
510 #[case::wrong_version(&[0x03, 0x02, 0xaa], Err(SevenBitDecodingError::UnexpectedTag(0x02)))]
511 #[case::empty_input(&[], Err(SevenBitDecodingError::TruncatedSize))]
512 #[case::size_overflow(&[0xFF; 64], Err(SevenBitDecodingError::SizeOverflow))]
513 #[case::size_underflow(&[0x00, 0x01], Err(SevenBitDecodingError::SizeUnderflow))]
514 #[case::unterminated_length(&[0x80], Err(SevenBitDecodingError::TruncatedSize))]
515 #[case::missing_version_byte(&[0x05], Err(SevenBitDecodingError::TruncatedTag))]
516 #[case::wrong_length(&[0x03, 0x01], Err(SevenBitDecodingError::TruncatedData { expected: 2, actual: 0 }))]
517 fn test_decode_7bit_length_and_tag(#[case] tile: &[u8], #[case] expected: Result<(), SevenBitDecodingError>) {
518 let allowed_versions = &[0x01_u8];
519 let decoded = decode_7bit_length_and_tag(tile, allowed_versions);
520 assert_eq!(decoded, expected, "can decode one layer correctly");
521
522 if tile.is_empty() {
523 return;
524 }
525 let mut tile_with_two_layers = vec![0x01, 0x01];
526 tile_with_two_layers.extend_from_slice(tile);
527 let decoded = decode_7bit_length_and_tag(&tile_with_two_layers, allowed_versions);
528 assert_eq!(decoded, expected, "can decode two layers correctly");
529 }
530}