geolith 0.2.0

Shared library of the geolith builders: source readers, conflation, admin areas, tile encoding and the PMTiles and MBTiles writers
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
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
//! Streaming `PMTiles` v3 archive writer.
//!
//! Writes tiles sequentially in Hilbert order, building directory entries
//! as it goes, and finalizing the header + directories at the end.
//!
//! `PMTiles` v3 layout:
//! ```text
//! [header: 127 bytes][root_dir: up to 16_257 bytes][tile_data...][metadata_json][leaf_dirs...]
//! ```
//!
//! The root directory space is pre-reserved immediately after the header so
//! tile data can be written in a single streaming pass. `finalize()` fills
//! the reserved space with the actual serialized root directory.

use std::fs::File;
use std::io::{BufWriter, Seek as _, SeekFrom, Write as _};
use std::path::{Path, PathBuf};

use flate2::Compression as GzLevel;
use flate2::write::GzEncoder;

use crate::error::{GeolithError, Result};
use crate::output::dedup::TileDedup;
use crate::output::directory::{DirEntry, build_directories};

/// `PMTiles` v3 header size (fixed 127 bytes).
const HEADER_SIZE: u64 = 127;

/// Maximum compressed size of the root directory.
///
/// `PMTiles` consumers (go-pmtiles `pmtiles serve`, pmtiles.io viewer,
/// serverless tile workers, the JavaScript pmtiles library, and every other
/// `PMTiles` v3 implementation) issue a **single initial range request for the
/// first 16,384 bytes** of the archive. That buffer must contain the full
/// 127-byte header **plus the entire compressed root directory**. The
/// constraint is therefore:
///
/// ```text
/// HEADER_SIZE (127) + root_dir_length <= 16_384
///                   => root_dir_length <= 16_257
/// ```
///
/// If the compressed root directory exceeds 16,257 bytes, the initial fetch
/// truncates it, gzip decompression fails with `"incomplete data"`, and
/// **every tile request returns 500** from every `PMTiles` consumer. Existing
/// caches hide the symptom until cache-invalidation forces cold reads.
///
/// Tile data starts immediately after the reserved root dir space at
/// `HEADER_SIZE + MAX_ROOT_DIR_BYTES = 16_384`, exactly aligning with the
/// consumer's initial fetch boundary.
///
/// References:
/// - <https://github.com/protomaps/PMTiles/blob/main/spec/v3/spec.md>
/// - <https://github.com/protomaps/go-pmtiles/blob/main/pmtiles/directory.go>
const MAX_ROOT_DIR_BYTES: usize = 16_257;

/// `PMTiles` v3 magic number.
const MAGIC: &[u8; 7] = b"PMTiles";

/// `PMTiles` v3 compression type.
///
/// Values match the `PMTiles` v3 spec: 1=none, 2=gzip, 3=brotli, 4=zstd.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum Compression {
    /// No compression (spec value 1).
    None = 1,
    /// Gzip compression (spec value 2).
    Gzip = 2,
    /// Brotli compression (spec value 3).
    Brotli = 3,
    /// Zstd compression (spec value 4).
    Zstd = 4,
}

/// `PMTiles` tile type.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum TileType {
    /// Unknown tile type.
    Unknown = 0,
    /// MVT (Mapbox Vector Tile).
    Mvt = 1,
    /// PNG raster.
    Png = 2,
    /// JPEG raster.
    Jpeg = 3,
    /// WebP raster.
    Webp = 4,
    /// AVIF raster.
    Avif = 5,
    /// MLT (`MapLibre` Tile) — columnar vector tile format.
    Mlt = 7,
}

/// The three tile-count statistics recorded in a `PMTiles` v3 header.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
struct TileCounts {
    /// Tile IDs a consumer can address, counting run-length expansions.
    addressed: u64,
    /// Directory entries after run-length compaction.
    entries: u64,
    /// Distinct tile blobs stored, after deduplication.
    contents: u64,
}

/// Streaming `PMTiles` v3 writer.
///
/// Usage:
/// 1. Create with `PmtilesWriter::create(path, ...)`
/// 2. Call `write_tile(tile_id, data)` for each tile in Hilbert order
/// 3. Call `finalize(metadata_json)` to write header + directories
pub struct PmtilesWriter {
    /// The archive being written, named in every write error.
    path: PathBuf,
    writer: BufWriter<File>,
    dedup: TileDedup,
    entries: Vec<DirEntry>,
    tile_data_offset: u64,
    current_offset: u64,
    tile_compression: Compression,
    tile_type: TileType,
    min_zoom: u8,
    max_zoom: u8,
    tiles_written: u64,
    /// Distinct tile blobs written to the file.
    blobs_written: u64,
    /// Equal hashes of different bytes: the second tile was written in full.
    hash_collisions: u64,
    /// Scratch space for reading a stored tile back.
    verify_buf: Vec<u8>,
    bounds: (f64, f64, f64, f64),
}

impl PmtilesWriter {
    /// Create a new `PMTiles` writer.
    ///
    /// Writes a placeholder header (127 bytes) and reserves `MAX_ROOT_DIR_BYTES`
    /// bytes for the root directory. Tile data begins at offset
    /// `HEADER_SIZE + MAX_ROOT_DIR_BYTES = 16384`, which exactly aligns with
    /// the 16 KiB initial range request issued by every `PMTiles` v3 consumer.
    ///
    /// # Errors
    ///
    /// Returns an error if file creation or initial header writes fail.
    pub fn create(
        path: &Path,
        tile_compression: Compression,
        tile_type: TileType,
        min_zoom: u8,
        max_zoom: u8,
    ) -> Result<Self> {
        let at = |e: std::io::Error| {
            GeolithError::from(e).context(format!("writing the archive {}", path.display()))
        };
        // Read access too: a tile that repeats an earlier one is compared with
        // the stored bytes before it is shared.
        let file = std::fs::OpenOptions::new()
            .read(true)
            .write(true)
            .create(true)
            .truncate(true)
            .open(path)
            .map_err(at)?;
        let mut writer = BufWriter::new(file);

        // Write placeholder header (will be overwritten in finalize)
        writer.write_all(&[0u8; HEADER_SIZE as usize]).map_err(at)?;

        // Reserve space for the root directory (filled in finalize)
        writer.write_all(&[0u8; MAX_ROOT_DIR_BYTES]).map_err(at)?;

        let tile_data_start = HEADER_SIZE + MAX_ROOT_DIR_BYTES as u64;

        Ok(Self {
            path: path.to_path_buf(),
            writer,
            dedup: TileDedup::new(),
            entries: Vec::with_capacity(1 << 20),
            tile_data_offset: tile_data_start,
            current_offset: tile_data_start,
            tile_compression,
            tile_type,
            min_zoom,
            max_zoom,
            tiles_written: 0,
            blobs_written: 0,
            hash_collisions: 0,
            verify_buf: Vec::new(),
            bounds: (-180.0, -85.0, 180.0, 85.0),
        })
    }

    /// Restrict the geographic extent recorded in the archive header.
    ///
    /// Defaults to the whole world. Archives covering a small footprint should
    /// set their real bounds so consumers can frame the data without probing
    /// tiles.
    pub const fn set_bounds(&mut self, min_lon: f64, min_lat: f64, max_lon: f64, max_lat: f64) {
        self.bounds = (min_lon, min_lat, max_lon, max_lat);
    }

    /// Write a tile (already compressed). Tiles may arrive in any order;
    /// they are sorted by `tile_id` in `finalize()` before directory construction.
    ///
    /// Returns the absolute byte offset where the tile was written.
    ///
    /// # Errors
    ///
    /// Returns an error if the tile is 4 GiB or larger, or if writing tile
    /// data to the underlying file fails.
    pub fn write_tile(&mut self, tile_id: u64, data: &[u8]) -> Result<u64> {
        self.write_tile_inner(tile_id, data)
            .map_err(|e| e.context(format!("writing the archive {}", self.path.display())))
    }

    fn write_tile_inner(&mut self, tile_id: u64, data: &[u8]) -> Result<u64> {
        let stored = match self.dedup.check(data) {
            Some((offset, length)) if self.stored_equals(offset, length, data)? => {
                Some((offset, length))
            }
            Some((offset, _)) => {
                self.hash_collisions += 1;
                tracing::warn!(
                    "tile {tile_id}: the hash of its {} bytes equals that of the tile stored \
                     at offset {offset}, but the bytes differ; the tile is written in full",
                    data.len()
                );
                None
            }
            None => None,
        };
        let (abs_offset, length) = if let Some(found) = stored {
            found
        } else {
            let abs_offset = self.current_offset;
            let length = entry_length(tile_id, data.len())?;
            self.writer.write_all(data)?;
            self.dedup.record(data, abs_offset, length);
            self.current_offset += length as u64;
            self.blobs_written += 1;
            (abs_offset, length)
        };

        // Store RELATIVE offset (relative to tile_data_offset), as required by PMTiles spec.
        // The JS library computes: tile_data_offset + entry.offset to get the file position.
        let rel_offset = abs_offset - self.tile_data_offset;
        self.entries.push(DirEntry {
            tile_id,
            offset: rel_offset,
            length,
            run_length: 1,
        });
        self.tiles_written += 1;
        Ok(abs_offset)
    }

    /// Finalize the archive: write root directory, metadata, leaf directories, and header.
    ///
    /// # Errors
    ///
    /// Returns an error if directory encoding, metadata compression,
    /// or final writes fail.
    pub fn finalize(self, metadata_json: &[u8]) -> Result<()> {
        let path = self.path.clone();
        self.finalize_inner(metadata_json)
            .map_err(|e| e.context(format!("writing the archive {}", path.display())))
    }

    fn finalize_inner(mut self, metadata_json: &[u8]) -> Result<()> {
        self.writer.flush()?;

        let tile_data_end = self.current_offset;

        // Gzip-compress metadata JSON (internal_compression = Gzip per PMTiles v3 spec).
        // Readers decompress directories AND metadata using the internal_compression field.
        let compressed_metadata = gzip_compress(metadata_json);
        let metadata_offset = tile_data_end;
        self.writer.seek(SeekFrom::Start(metadata_offset))?;
        self.writer.write_all(&compressed_metadata)?;
        let metadata_length = compressed_metadata.len() as u64;

        // Sort entries by tile_id (Hilbert order) before compaction.
        // Tiles are written in zoom+row-major order during phase 3, but PMTiles
        // directories must be sorted by Hilbert tile_id so the binary search works.
        self.entries.sort_unstable_by_key(|e| e.tile_id);
        // Compact entries with run-length encoding
        let compacted = compact_entries(&self.entries);

        let counts = TileCounts {
            addressed: compacted.iter().map(|e| u64::from(e.run_length)).sum(),
            entries: compacted.len() as u64,
            contents: self.blobs_written,
        };

        // Build root + leaf directories (gzip-compressed per PMTiles v3 spec)
        let (root_dir, leaf_dirs) = build_directories(&compacted, MAX_ROOT_DIR_BYTES);

        // Verify the root directory fits in the reserved space
        if root_dir.len() > MAX_ROOT_DIR_BYTES {
            return Err(GeolithError::PmtilesWrite(format!(
                "root directory too large ({} bytes, max {})",
                root_dir.len(),
                MAX_ROOT_DIR_BYTES,
            )));
        }

        // Write leaf directories after metadata
        let leaf_offset = metadata_offset + metadata_length;
        if !leaf_dirs.is_empty() {
            self.writer.seek(SeekFrom::Start(leaf_offset))?;
            self.writer.write_all(&leaf_dirs)?;
        }
        let leaf_length = leaf_dirs.len() as u64;

        // Write the actual root directory into the pre-reserved space after the header
        let root_dir_offset = HEADER_SIZE;
        let root_dir_length = root_dir.len() as u64;
        self.writer.seek(SeekFrom::Start(root_dir_offset))?;
        self.writer.write_all(&root_dir)?;

        // Write the real header at offset 0.
        // Internal compression = Gzip (directories and metadata are gzip-compressed
        // per the PMTiles v3 spec).  Tile compression is separately tracked.
        self.writer.seek(SeekFrom::Start(0))?;
        let header = encode_header(&HeaderFields {
            root_dir_offset,
            root_dir_length,
            metadata_offset,
            metadata_length,
            tile_data_offset: self.tile_data_offset,
            tile_data_length: tile_data_end - self.tile_data_offset,
            leaf_dir_offset: leaf_offset,
            leaf_dir_length: leaf_length,
            internal_compression: Compression::Gzip,
            tile_compression: self.tile_compression,
            tile_type: self.tile_type,
            min_zoom: self.min_zoom,
            max_zoom: self.max_zoom,
            counts,
            bounds: self.bounds,
        });
        self.writer.write_all(&header)?;

        self.writer.flush()?;
        // A full disk can be reported only when the file is synced: without
        // this a finished archive could be short and the build still succeed.
        self.writer.get_ref().sync_all()?;
        super::sync_parent_dir(&self.path)?;
        Ok(())
    }

    /// Number of tiles written (including duplicates pointing to same data).
    #[must_use]
    pub const fn tiles_written(&self) -> u64 {
        self.tiles_written
    }

    /// Number of unique tile blobs written to disk.
    #[must_use]
    pub fn unique_tiles(&self) -> usize {
        usize::try_from(self.blobs_written).unwrap_or(usize::MAX)
    }

    /// Times two different tiles had the same hash. Zero in practice; each one
    /// is written in full, so the archive stays correct.
    #[must_use]
    pub const fn hash_collisions(&self) -> u64 {
        self.hash_collisions
    }

    /// Whether the `length` bytes stored at `offset` are exactly `data`.
    ///
    /// The tile may still sit in the write buffer (a repeat of the tile just
    /// written), or be in the file already. Whole tiles only: `BufWriter`
    /// flushes its buffer before it takes a write that does not fit, so a tile
    /// is never split between file and buffer.
    fn stored_equals(&mut self, offset: u64, length: u32, data: &[u8]) -> Result<bool> {
        if length as usize != data.len() {
            return Ok(false);
        }
        let buffered = self.writer.buffer().len() as u64;
        let buffer_start = self.current_offset - buffered;
        if offset >= buffer_start {
            let at = usize::try_from(offset - buffer_start).map_err(|_| {
                GeolithError::PmtilesWrite("a stored tile offset does not fit in memory".into())
            })?;
            return Ok(self.writer.buffer().get(at..at + data.len()) == Some(data));
        }
        if offset + u64::from(length) > buffer_start {
            self.writer.flush()?;
        }
        self.verify_buf.resize(data.len(), 0);
        read_back(&mut self.writer, offset, &mut self.verify_buf)?;
        Ok(self.verify_buf == data)
    }
}

/// Read `buf.len()` bytes of the archive at `offset`, which are already in the
/// file.
#[cfg(unix)]
fn read_back(writer: &mut BufWriter<File>, offset: u64, buf: &mut [u8]) -> std::io::Result<()> {
    use std::os::unix::fs::FileExt as _;
    writer.get_ref().read_exact_at(buf, offset)
}

/// Read `buf.len()` bytes of the archive at `offset`, which are already in the
/// file. Without `pread` the write position moves, so it is put back.
#[cfg(not(unix))]
fn read_back(writer: &mut BufWriter<File>, offset: u64, buf: &mut [u8]) -> std::io::Result<()> {
    use std::io::Read as _;
    let end = writer.stream_position()?;
    writer.seek(SeekFrom::Start(offset))?;
    writer.get_mut().read_exact(buf)?;
    writer.seek(SeekFrom::Start(end))?;
    Ok(())
}

/// Compact consecutive entries with the same offset/length into run-length groups.
fn compact_entries(entries: &[DirEntry]) -> Vec<DirEntry> {
    if entries.is_empty() {
        return Vec::new();
    }

    let mut compacted = Vec::with_capacity(entries.len());
    let mut current = entries[0].clone();

    for entry in entries.iter().skip(1) {
        if entry.offset == current.offset
            && entry.length == current.length
            && entry.tile_id == current.tile_id + current.run_length as u64
        {
            current.run_length += 1;
        } else {
            compacted.push(current);
            current = entry.clone();
        }
    }
    compacted.push(current);

    compacted
}

/// The `PMTiles` directory length of a tile: entries store it as a `u32`.
fn entry_length(tile_id: u64, len: usize) -> Result<u32> {
    u32::try_from(len).map_err(|_| {
        GeolithError::PmtilesWrite(format!(
            "tile {tile_id} is {len} bytes, above the 4 GiB PMTiles entry limit"
        ))
    })
}

/// Gzip-compress `data` at best compression level (matches go-pmtiles `BestCompression`).
fn gzip_compress(data: &[u8]) -> Vec<u8> {
    let mut encoder = GzEncoder::new(Vec::with_capacity(data.len() / 4 + 64), GzLevel::best());
    encoder
        .write_all(data)
        .expect("gzip write to Vec is infallible");
    encoder.finish().expect("gzip finish on Vec is infallible")
}

/// The values written into the 127-byte `PMTiles` v3 header.
struct HeaderFields {
    /// Byte offset of the root directory.
    root_dir_offset: u64,
    /// Byte length of the root directory.
    root_dir_length: u64,
    /// Byte offset of the JSON metadata.
    metadata_offset: u64,
    /// Byte length of the JSON metadata.
    metadata_length: u64,
    /// Byte offset of the tile data section.
    tile_data_offset: u64,
    /// Byte length of the tile data section.
    tile_data_length: u64,
    /// Byte offset of the leaf directories.
    leaf_dir_offset: u64,
    /// Byte length of the leaf directories.
    leaf_dir_length: u64,
    /// Compression of directories and metadata.
    internal_compression: Compression,
    /// Compression of tile data.
    tile_compression: Compression,
    /// Tile format.
    tile_type: TileType,
    /// Lowest zoom in the archive.
    min_zoom: u8,
    /// Highest zoom in the archive.
    max_zoom: u8,
    /// Tile counts.
    counts: TileCounts,
    /// Bounds as (min lon, min lat, max lon, max lat) in degrees.
    bounds: (f64, f64, f64, f64),
}

/// Encode the 127-byte `PMTiles` v3 header.
///
/// `internal_compression` controls how directories and metadata are compressed.
/// `tile_compression` controls how tile data is compressed.
/// Both use the `PMTiles` v3 spec values: 1=none, 2=gzip, 3=brotli, 4=zstd.
fn encode_header(h: &HeaderFields) -> [u8; 127] {
    let mut header = [0u8; 127];
    let mut pos = 0;

    // Magic: "PMTiles" (7 bytes)
    header[pos..pos + 7].copy_from_slice(MAGIC);
    pos += 7;

    // Version: 3 (1 byte)
    header[pos] = 3;
    pos += 1;

    // Root directory offset (8 bytes LE)
    header[pos..pos + 8].copy_from_slice(&h.root_dir_offset.to_le_bytes());
    pos += 8;

    // Root directory length (8 bytes LE)
    header[pos..pos + 8].copy_from_slice(&h.root_dir_length.to_le_bytes());
    pos += 8;

    // Metadata offset (8 bytes LE)
    header[pos..pos + 8].copy_from_slice(&h.metadata_offset.to_le_bytes());
    pos += 8;

    // Metadata length (8 bytes LE)
    header[pos..pos + 8].copy_from_slice(&h.metadata_length.to_le_bytes());
    pos += 8;

    // Leaf directory offset (8 bytes LE)
    header[pos..pos + 8].copy_from_slice(&h.leaf_dir_offset.to_le_bytes());
    pos += 8;

    // Leaf directory length (8 bytes LE)
    header[pos..pos + 8].copy_from_slice(&h.leaf_dir_length.to_le_bytes());
    pos += 8;

    // Tile data offset (8 bytes LE)
    header[pos..pos + 8].copy_from_slice(&h.tile_data_offset.to_le_bytes());
    pos += 8;

    // Tile data length (8 bytes LE)
    header[pos..pos + 8].copy_from_slice(&h.tile_data_length.to_le_bytes());
    pos += 8;

    // Addressed tiles count (8 bytes LE)
    header[pos..pos + 8].copy_from_slice(&h.counts.addressed.to_le_bytes());
    pos += 8;

    // Tile entries count (8 bytes LE)
    header[pos..pos + 8].copy_from_slice(&h.counts.entries.to_le_bytes());
    pos += 8;

    // Tile contents count (8 bytes LE)
    header[pos..pos + 8].copy_from_slice(&h.counts.contents.to_le_bytes());
    pos += 8;

    // Clustered: 1 (1 byte) -- we always write in Hilbert order
    header[pos] = 1;
    pos += 1;

    // Internal compression (1 byte) -- directories and metadata
    header[pos] = h.internal_compression as u8;
    pos += 1;

    // Tile compression (1 byte) -- tile data
    header[pos] = h.tile_compression as u8;
    pos += 1;

    // Tile type (1 byte)
    header[pos] = h.tile_type as u8;
    pos += 1;

    // Min zoom (1 byte)
    header[pos] = h.min_zoom;
    pos += 1;

    // Max zoom (1 byte)
    header[pos] = h.max_zoom;
    pos += 1;

    let (min_lon, min_lat, max_lon, max_lat) = h.bounds;
    let scaled = |degrees: f64| (degrees * 10_000_000.0) as i32;

    // Min lon (i32 as 4 bytes LE)
    header[pos..pos + 4].copy_from_slice(&scaled(min_lon).to_le_bytes());
    pos += 4;

    // Min lat (i32 as 4 bytes LE)
    header[pos..pos + 4].copy_from_slice(&scaled(min_lat).to_le_bytes());
    pos += 4;

    // Max lon (i32 as 4 bytes LE)
    header[pos..pos + 4].copy_from_slice(&scaled(max_lon).to_le_bytes());
    pos += 4;

    // Max lat (i32 as 4 bytes LE)
    header[pos..pos + 4].copy_from_slice(&scaled(max_lat).to_le_bytes());
    pos += 4;

    // Center zoom (1 byte)
    header[pos] = (h.min_zoom + h.max_zoom) / 2;
    pos += 1;

    // Center lon (i32 as 4 bytes LE)
    header[pos..pos + 4].copy_from_slice(&scaled((min_lon + max_lon) / 2.0).to_le_bytes());
    pos += 4;

    // Center lat (i32 as 4 bytes LE)
    header[pos..pos + 4].copy_from_slice(&scaled((min_lat + max_lat) / 2.0).to_le_bytes());
    // pos += 4;  // final field -- no need to advance

    header
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_tile_length_must_fit_the_u32_directory_field() {
        assert_eq!(
            entry_length(7, 4_294_967_295).expect("u32::MAX fits"),
            u32::MAX
        );
        assert!(entry_length(7, 4_294_967_296).is_err());
    }
    use tempfile::NamedTempFile;

    #[test]
    fn header_starts_with_magic() {
        let header = encode_header(&HeaderFields {
            root_dir_offset: 0,
            root_dir_length: 0,
            metadata_offset: 0,
            metadata_length: 0,
            tile_data_offset: 0,
            tile_data_length: 0,
            leaf_dir_offset: 0,
            leaf_dir_length: 0,
            internal_compression: Compression::Gzip,
            tile_compression: Compression::Gzip,
            tile_type: TileType::Mvt,
            min_zoom: 0,
            max_zoom: 15,
            counts: TileCounts::default(),
            bounds: (-180.0, -85.0, 180.0, 85.0),
        });
        assert_eq!(&header[0..7], b"PMTiles");
        assert_eq!(header[7], 3); // version
        assert_eq!(header[96], 1); // clustered = true
        // internal compression = Gzip = 2 (spec value)
        assert_eq!(header[97], Compression::Gzip as u8);
        // tile compression = Gzip = 2 (spec value)
        assert_eq!(header[98], Compression::Gzip as u8);
    }

    /// Decode the four bbox fields the `PMTiles` v3 header carries at offset 102.
    fn header_bounds(header: &[u8]) -> (f64, f64, f64, f64) {
        let at = |o: usize| {
            f64::from(i32::from_le_bytes(
                header[o..o + 4].try_into().expect("bbox field"),
            )) / 10_000_000.0
        };
        (at(102), at(106), at(110), at(114))
    }

    /// Decode the three tile-count fields the header carries at offset 72.
    fn header_counts(header: &[u8]) -> (u64, u64, u64) {
        let at = |o: usize| u64::from_le_bytes(header[o..o + 8].try_into().expect("count field"));
        (at(72), at(80), at(88))
    }

    #[test]
    fn header_defaults_to_world_bounds() {
        let tmp = NamedTempFile::new().expect("temp file");
        let writer = PmtilesWriter::create(tmp.path(), Compression::None, TileType::Png, 0, 2)
            .expect("create");
        let (min_lon, min_lat, max_lon, max_lat) = writer.bounds;

        assert!((min_lon + 180.0).abs() < 1e-9);
        assert!((min_lat + 85.0).abs() < 1e-9);
        assert!((max_lon - 180.0).abs() < 1e-9);
        assert!((max_lat - 85.0).abs() < 1e-9);
    }

    #[test]
    fn finalize_records_the_configured_bounds() {
        let tmp = NamedTempFile::new().expect("temp file");
        let path = tmp.path().to_owned();

        let mut writer =
            PmtilesWriter::create(&path, Compression::None, TileType::Png, 8, 16).expect("create");
        writer.set_bounds(7.8756, 45.9159, 8.0043, 45.9863);
        writer.write_tile(0, b"tile").expect("write");
        writer.finalize(b"{}").expect("finalize");

        let data = std::fs::read(&path).expect("read archive");
        let (min_lon, min_lat, max_lon, max_lat) = header_bounds(&data);

        assert!(
            (min_lon - 7.8756).abs() < 1e-6,
            "a glacier-scale archive must not claim world bounds, got {min_lon}"
        );
        assert!((min_lat - 45.9159).abs() < 1e-6);
        assert!((max_lon - 8.0043).abs() < 1e-6);
        assert!((max_lat - 45.9863).abs() < 1e-6);
    }

    #[test]
    fn finalize_records_the_center_inside_the_bounds() {
        let tmp = NamedTempFile::new().expect("temp file");
        let path = tmp.path().to_owned();

        let mut writer =
            PmtilesWriter::create(&path, Compression::None, TileType::Png, 8, 16).expect("create");
        writer.set_bounds(7.8756, 45.9159, 8.0043, 45.9863);
        writer.write_tile(0, b"tile").expect("write");
        writer.finalize(b"{}").expect("finalize");

        let data = std::fs::read(&path).expect("read archive");
        let center_lon =
            f64::from(i32::from_le_bytes(data[119..123].try_into().expect("lon"))) / 10_000_000.0;
        let center_lat =
            f64::from(i32::from_le_bytes(data[123..127].try_into().expect("lat"))) / 10_000_000.0;

        assert!(
            (7.8756..=8.0043).contains(&center_lon),
            "center lon {center_lon} outside bounds"
        );
        assert!(
            (45.9159..=45.9863).contains(&center_lat),
            "center lat {center_lat} outside bounds"
        );
        assert_eq!(data[118], 12, "center zoom is the midpoint of 8 and 16");
    }

    #[test]
    fn finalize_records_the_tile_counts() {
        let tmp = NamedTempFile::new().expect("temp file");
        let path = tmp.path().to_owned();

        let mut writer =
            PmtilesWriter::create(&path, Compression::None, TileType::Mvt, 0, 2).expect("create");
        writer.write_tile(0, b"unique-a").expect("write");
        writer.write_tile(1, b"unique-b").expect("write");
        writer.write_tile(2, b"unique-a").expect("write");
        writer.finalize(b"{}").expect("finalize");

        let data = std::fs::read(&path).expect("read archive");
        let (addressed, entries, contents) = header_counts(&data);

        assert_eq!(addressed, 3, "three tile IDs are addressable");
        assert_eq!(contents, 2, "only two distinct blobs are stored");
        assert!(
            entries > 0 && entries <= addressed,
            "entry count {entries} must be non-zero and no larger than {addressed}"
        );
    }

    #[test]
    fn write_and_finalize() {
        let tmp = NamedTempFile::new().unwrap();
        let path = tmp.path().to_owned();

        let mut writer =
            PmtilesWriter::create(&path, Compression::None, TileType::Mvt, 0, 2).unwrap();

        writer.write_tile(0, b"tile-0-data").unwrap();
        writer.write_tile(1, b"tile-1-data").unwrap();
        writer.write_tile(2, b"tile-0-data").unwrap(); // duplicate of tile 0

        assert_eq!(writer.tiles_written(), 3);
        assert_eq!(writer.unique_tiles(), 2);

        writer.finalize(b"{}").unwrap();

        // Verify file starts with PMTiles magic
        let data = std::fs::read(&path).unwrap();
        assert_eq!(&data[0..7], b"PMTiles");
        assert_eq!(data[7], 3); // version 3

        // Tile data must start after header + root dir reservation,
        // aligned exactly with the 16 KiB initial-fetch boundary used by
        // every PMTiles v3 consumer.
        let tile_data_offset = u64::from_le_bytes(data[56..64].try_into().unwrap());
        assert_eq!(
            tile_data_offset,
            HEADER_SIZE + MAX_ROOT_DIR_BYTES as u64,
            "tile data starts after reserved root dir space"
        );
        assert_eq!(
            tile_data_offset, 16_384,
            "tile_data_offset must equal 16_384 so the 16 KiB initial fetch \
             contains exactly header + root_dir with zero overflow"
        );
    }

    /// Regression guard for the 16_384-byte initial-fetch constraint.
    ///
    /// Every `PMTiles` v3 consumer (go-pmtiles, pmtiles.io,
    /// serverless tile workers, the JS pmtiles library) issues an initial 16 KiB range
    /// request. The 127-byte header + compressed root directory MUST fit
    /// within that buffer, so the compressed root dir cap is `16_257` bytes.
    ///
    /// If this test ever fails because `MAX_ROOT_DIR_BYTES` got raised
    /// "for more headroom", every tile request will 500 once caches expire.
    /// See the `MAX_ROOT_DIR_BYTES` docstring for the full failure story.
    #[test]
    fn max_root_dir_bytes_matches_initial_fetch_constraint() {
        // Both numbers come from the PMTiles v3 spec, not from this crate:
        // a 127-byte header and a 16 KiB first fetch.
        assert_eq!(HEADER_SIZE, 127, "the PMTiles v3 header is 127 bytes");
        assert_eq!(
            HEADER_SIZE as usize + MAX_ROOT_DIR_BYTES,
            16_384,
            "header + root_dir must exactly equal 16_384 bytes (standard \
             initial fetch size). Any other value corrupts cold reads."
        );
    }

    #[test]
    fn compact_entries_merges_runs() {
        let entries = vec![
            DirEntry {
                tile_id: 0,
                offset: 100,
                length: 50,
                run_length: 1,
            },
            DirEntry {
                tile_id: 1,
                offset: 100,
                length: 50,
                run_length: 1,
            },
            DirEntry {
                tile_id: 2,
                offset: 100,
                length: 50,
                run_length: 1,
            },
            DirEntry {
                tile_id: 3,
                offset: 200,
                length: 60,
                run_length: 1,
            },
        ];
        let compacted = compact_entries(&entries);
        assert_eq!(compacted.len(), 2);
        assert_eq!(compacted[0].run_length, 3);
        assert_eq!(compacted[1].run_length, 1);
    }

    /// A write error names the archive and what the OS said.
    #[test]
    fn a_failed_create_names_the_archive() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("no-such-dir").join("out.pmtiles");
        let err = PmtilesWriter::create(&path, Compression::None, TileType::Mvt, 0, 1)
            .err()
            .expect("the folder does not exist");
        let text = crate::error::report(&err);
        assert!(text.contains("writing the archive"), "{text}");
        assert!(text.contains("out.pmtiles"), "{text}");
        assert!(text.contains("os error 2"), "{text}");
    }

    /// `/dev/full` takes no byte: the first tile write fails and says where.
    #[cfg(target_os = "linux")]
    #[test]
    fn a_full_disk_fails_the_write_and_the_finish() {
        let writer = PmtilesWriter::create(
            Path::new("/dev/full"),
            Compression::None,
            TileType::Mvt,
            0,
            1,
        );
        // The header goes through the buffer: the failure shows at the flush.
        let err = writer
            .and_then(|mut w| {
                w.write_tile(1, &[1, 2, 3])?;
                w.finalize(b"{}")
            })
            .expect_err("a full disk must fail");
        let text = crate::error::report(&err);
        assert!(text.contains("/dev/full"), "{text}");
        assert!(text.contains("No space left on device"), "{text}");
    }

    fn writer_at(path: &Path) -> PmtilesWriter {
        PmtilesWriter::create(path, Compression::None, TileType::Mvt, 0, 4).expect("writer")
    }

    /// The `length` bytes of the finished archive at `offset`.
    fn bytes_at(path: &Path, offset: u64, length: usize) -> Vec<u8> {
        let all = std::fs::read(path).expect("archive");
        all[offset as usize..offset as usize + length].to_vec()
    }

    #[test]
    fn a_repeated_tile_is_stored_once_whether_it_is_in_the_buffer_or_the_file() {
        let file = NamedTempFile::new().expect("tmp");
        let mut writer = writer_at(file.path());
        let first = vec![7u8; 100];
        let a = writer.write_tile(1, &first).expect("write");
        // Still in the write buffer.
        assert_eq!(writer.write_tile(2, &first).expect("write"), a);
        // A tile larger than the buffer pushes the first one into the file.
        writer.write_tile(3, &vec![9u8; 100_000]).expect("write");
        assert_eq!(writer.write_tile(4, &first).expect("write"), a);
        assert_eq!(writer.unique_tiles(), 2);
        assert_eq!(writer.hash_collisions(), 0);
        writer.finalize(b"{}").expect("finalize");
        assert_eq!(bytes_at(file.path(), a, 100), first);
    }

    /// Two different tiles with one hash. Both hashes cannot be made equal
    /// from outside, so the table is told that the hash of `second` leads to
    /// where `first` is.
    #[test]
    fn two_tiles_with_one_hash_are_both_written() {
        let file = NamedTempFile::new().expect("tmp");
        let mut writer = writer_at(file.path());
        let first = vec![1u8; 64];
        let second = vec![2u8; 64];
        let a = writer.write_tile(1, &first).expect("write");
        writer.dedup.record(&second, a, 64);
        let b = writer.write_tile(2, &second).expect("write");
        assert_ne!(a, b, "the second tile has its own bytes");
        assert_eq!(writer.hash_collisions(), 1);
        assert_eq!(writer.unique_tiles(), 2);
        writer.finalize(b"{}").expect("finalize");
        assert_eq!(bytes_at(file.path(), a, 64), first);
        assert_eq!(bytes_at(file.path(), b, 64), second);
    }

    #[test]
    fn a_hash_hit_with_another_length_is_not_a_repeat() {
        let file = NamedTempFile::new().expect("tmp");
        let mut writer = writer_at(file.path());
        let a = writer.write_tile(1, &[5u8; 64]).expect("write");
        let longer = vec![5u8; 80];
        writer.dedup.record(&longer, a, 64);
        let b = writer.write_tile(2, &longer).expect("write");
        assert_ne!(a, b);
        assert_eq!(writer.hash_collisions(), 1);
    }

    /// The same collision with the first tile already in the file.
    #[test]
    fn a_collision_with_a_tile_that_is_already_in_the_file_is_caught() {
        let file = NamedTempFile::new().expect("tmp");
        let mut writer = writer_at(file.path());
        let first = vec![3u8; 64];
        let second = vec![4u8; 64];
        let a = writer.write_tile(1, &first).expect("write");
        writer.write_tile(2, &vec![8u8; 100_000]).expect("write");
        writer.dedup.record(&second, a, 64);
        let b = writer.write_tile(3, &second).expect("write");
        assert_ne!(a, b);
        assert_eq!(writer.hash_collisions(), 1);
        writer.finalize(b"{}").expect("finalize");
        assert_eq!(bytes_at(file.path(), b, 64), second);
    }
}