Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
dependencies ▾

Modern-Apps.git / scripts / maps / dem_ingest / src / dataset.rs

dataset.rs64 lines · 2.7 KiBRaw
1//! Streamed `.mdem` dataset writer: header with a zero tile count, one tile
2//! record appended at a time, then the real count patched into the header.
3//! The file never needs the whole grid set in memory (a world run at the old
4//! z14/dim17 defaults held tens of GB of grids) — peak disk use is the output
5//! file itself.
6//!
7//! Writes go through a [`BufWriter`] so a tile record is a couple of `memcpy`s
8//! into the buffer rather than a syscall or two each, and one scratch buffer is
9//! reused across tiles instead of a fresh `Vec` per record.
10
11use std::fs::File;
12use std::io::BufWriter;
13use std::path::Path;
14
15const OUT_MAGIC: &[u8; 4] = b"MDEM";
16const OUT_VERSION: u8 = 1;
17
18/// Offset of the `u32` tile count in the output header
19/// (magic 4 + version 1 + zoom 1 + dim 2); patched in after the streamed body.
20const COUNT_AT: u64 = 8;
21
22/// Buffered `.mdem` writer plus a reused scratch buffer for tile records.
23pub struct DatasetWriter {
24 out: BufWriter<File>,
25 scratch: Vec<u8>,
26}
27
28/// Open the dataset and write its header with a zero tile count; the count is
29/// patched in by [`finish_dataset`].
30pub fn open_dataset(out_path: &Path, out_zoom: u8, dim: u16) -> Result<DatasetWriter, String> {
31 use std::io::Write;
32 let file =
33 File::create(out_path).map_err(|e| format!("creating {}: {e}", out_path.display()))?;
34 let mut out = BufWriter::new(file);
35 out.write_all(OUT_MAGIC).map_err(|e| format!("writing {}: {e}", out_path.display()))?;
36 out.write_all(&[OUT_VERSION, out_zoom])
37 .map_err(|e| format!("writing {}: {e}", out_path.display()))?;
38 out.write_all(&dim.to_le_bytes())
39 .map_err(|e| format!("writing {}: {e}", out_path.display()))?;
40 out.write_all(&0u32.to_le_bytes())
41 .map_err(|e| format!("writing {}: {e}", out_path.display()))?;
42 Ok(DatasetWriter { out, scratch: Vec::new() })
43}
44
45/// Append one tile's record: its pmtiles id then its `dim * dim` samples.
46pub fn write_tile(w: &mut DatasetWriter, id: u64, grid: &[u16]) -> Result<(), String> {
47 use std::io::Write;
48 w.scratch.clear();
49 w.scratch.reserve(8 + grid.len() * 2);
50 w.scratch.extend_from_slice(&id.to_le_bytes());
51 for &s in grid {
52 w.scratch.extend_from_slice(&s.to_le_bytes());
53 }
54 w.out.write_all(&w.scratch).map_err(|e| format!("writing tile {id}: {e}"))
55}
56
57/// Patch the real tile count into the header at [`COUNT_AT`], then flush.
58pub fn finish_dataset(mut w: DatasetWriter, count: u32) -> Result<(), String> {
59 use std::io::{Seek, SeekFrom, Write};
60 w.out.seek(SeekFrom::Start(COUNT_AT)).map_err(|e| format!("seeking tile count: {e}"))?;
61 w.out.write_all(&count.to_le_bytes()).map_err(|e| format!("writing tile count: {e}"))?;
62 w.out.flush().map_err(|e| format!("flushing dataset: {e}"))?;
63 Ok(())
64}