Skip to main content

utz_build/
config.rs

1//! The consumer-facing builder API for the `custom` tier, where the typed
2//! config IS the build config (rustdoc'd, IDE-completable, with no file
3//! discovery). It is meant for a consumer `build.rs` with `utz_build` as
4//! a build-dependency (the `prost-build` pattern):
5//!
6//! ```no_run
7//! // build.rs
8//! let out = utz_build::Config::new()
9//!     .dataset(utz_build::Dataset::Now)
10//!     .epsilon_meters(500.0)
11//!     .generate()
12//!     .unwrap();
13//! // then in the crate:
14//! //   static TZ: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/tz.utz"));
15//! //   let finder = utz::Finder::from_slice(TZ)?;
16//! ```
17//!
18//! Source data (TZBB, optionally GHS-POP for density weighting) is fetched
19//! into the cache, never committed; downloads are conditional-GET-cached
20//! so regeneration is cheap.
21//!
22//! The preset recipes double as constructors. Start from one and
23//! override a single knob instead of spelling the whole recipe:
24//! `Config::compact().codec(Codec::Uncompressed)`. The recipe values
25//! themselves live in one place, the [`utz_common::presets`] table; the
26//! constructors here are thin wrappers over the `From<&Recipe>`
27//! conversion.
28
29use std::path::PathBuf;
30
31use utz_common::presets::{self, Recipe};
32use utz_encode::encode::{self, Codec, Dataset, GeomEncoding, Params, SimplifyAlgorithm};
33
34/// The builder for a custom `.utz` asset. The defaults are dataset `now`,
35/// RDP ε=500 m, no density weighting, i24, a 2° grid, gzip, varint-arcs
36/// geometry, and output to `$OUT_DIR/tz.utz`.
37#[derive(Clone, Debug)]
38pub struct Config {
39    dataset: Dataset,
40    epsilon_m: f64,
41    quant_bits: u32,
42    grid_deg: f64,
43    codec: Codec,
44    simplify: SimplifyAlgorithm,
45    geom: GeomEncoding,
46    density_weight_floor: Option<f64>,
47    out: Option<PathBuf>,
48    cache_dir: Option<PathBuf>,
49}
50
51impl Default for Config {
52    fn default() -> Self {
53        Config {
54            dataset: Dataset::Now,
55            epsilon_m: 500.0,
56            quant_bits: 24,
57            grid_deg: 2.0,
58            codec: Codec::Gzip,
59            simplify: SimplifyAlgorithm::Rdp,
60            geom: GeomEncoding::VarintArcs,
61            density_weight_floor: None,
62            out: None,
63            cache_dir: None,
64        }
65    }
66}
67
68impl Config {
69    /// Returns a config at the documented defaults; chain knob methods to
70    /// override them, then call [`generate()`](Config::generate).
71    #[must_use]
72    pub fn new() -> Self {
73        Config::default()
74    }
75
76    /// Returns the `tiny` preset recipe ([`presets::TINY`]): RDP
77    /// ε=10 000 m with pop-density floor 0.001, i16, a 2° grid, and
78    /// gzip. A preset constructor is a starting point for one-knob
79    /// variants: `Config::tiny().geom(GeomEncoding::Coarse)`.
80    #[must_use]
81    pub fn tiny() -> Self {
82        Config::from(&presets::TINY)
83    }
84
85    /// Returns the `tiny-static` preset recipe ([`presets::TINY_STATIC`]),
86    /// which is `tiny` stored uncompressed so the asset is readable in
87    /// place with zero decode RAM.
88    #[must_use]
89    pub fn tiny_static() -> Self {
90        Config::from(&presets::TINY_STATIC)
91    }
92
93    /// Returns the `compact` preset recipe ([`presets::COMPACT`]): RDP
94    /// ε=1 000 m with pop-density floor 0.001, i24, a 4/3° grid, and xz.
95    #[must_use]
96    pub fn compact() -> Self {
97        Config::from(&presets::COMPACT)
98    }
99
100    /// Returns the `balanced` preset recipe ([`presets::BALANCED`]): RDP
101    /// ε=50 m with pop-density floor 0.020, i24, a 2/3° grid, and
102    /// brotli.
103    #[must_use]
104    pub fn balanced() -> Self {
105        Config::from(&presets::BALANCED)
106    }
107
108    /// Returns the `accurate` preset recipe ([`presets::ACCURATE`]):
109    /// dataset `all` (the full Comprehensive zone set; the other presets
110    /// use `now`), RDP ε=10 m with pop-density floor 0.10, i32, a 0.5°
111    /// grid, and brotli.
112    #[must_use]
113    pub fn accurate() -> Self {
114        Config::from(&presets::ACCURATE)
115    }
116
117    /// Sets the dataset, default [`Dataset::Now`]. A name string
118    /// (`[land-]now|1970|all`) parses via
119    /// [`dataset()`](crate::dataset()).
120    #[must_use]
121    pub fn dataset(mut self, dataset: Dataset) -> Self {
122        self.dataset = dataset;
123        self
124    }
125
126    /// Sets the simplification tolerance ceiling in meters (default 500).
127    /// The value is the ε of whichever
128    /// [`simplify_algorithm()`](Config::simplify_algorithm) runs: it is a
129    /// max-deviation bound for RDP and Imai–Iri, and Visvalingam derives
130    /// its area threshold as ε².
131    #[must_use]
132    pub fn epsilon_meters(mut self, epsilon_m: f64) -> Self {
133        self.epsilon_m = epsilon_m;
134        self
135    }
136
137    /// Sets the quantization width: 16 / 24 / 32 (default 24). Any other
138    /// value fails at [`generate()`](Config::generate), not here.
139    #[must_use]
140    pub fn quant_bits(mut self, bits: u32) -> Self {
141        self.quant_bits = bits;
142        self
143    }
144
145    /// Sets the grid cell size in degrees, 0.1–45 (default 2). Fractional
146    /// sizes are fine (the presets use 4/3, 2/3, and 0.5); out-of-range
147    /// values fail at [`generate()`](Config::generate).
148    #[must_use]
149    pub fn grid_deg(mut self, degrees: f64) -> Self {
150        self.grid_deg = degrees;
151        self
152    }
153
154    /// Sets the payload codec. `Codec::Uncompressed` gives a `core`-rung
155    /// asset: zero decode RAM at the cost of more flash.
156    #[must_use]
157    pub fn codec(mut self, codec: Codec) -> Self {
158        self.codec = codec;
159        self
160    }
161
162    /// Sets the simplification algorithm, default [`SimplifyAlgorithm::Rdp`].
163    /// The variants and their measured trade-offs are documented on
164    /// [`SimplifyAlgorithm`].
165    #[must_use]
166    pub fn simplify_algorithm(mut self, algorithm: SimplifyAlgorithm) -> Self {
167        self.simplify = algorithm;
168        self
169    }
170
171    /// Sets the geometry encoding. The default is
172    /// [`GeomEncoding::VarintArcs`] (smallest flash); the measured
173    /// size/speed ladder is the table on [`GeomEncoding`].
174    #[must_use]
175    pub fn geom(mut self, geom: GeomEncoding) -> Self {
176        self.geom = geom;
177        self
178    }
179
180    /// Enables population-density-weighted simplification. The value is
181    /// the ε multiplier floor in the densest cells, strictly between 0
182    /// and 1 (the presets use 0.001–0.10; the default is off, uniform ε;
183    /// out-of-range values fail at [`generate()`](Config::generate)).
184    /// First use downloads GHS-POP (~460 MB, cached).
185    #[must_use]
186    pub fn density_weight_floor(mut self, floor: f64) -> Self {
187        self.density_weight_floor = Some(floor);
188        self
189    }
190
191    /// Sets where to write the asset. The default is `$OUT_DIR/tz.utz`
192    /// (the build.rs context).
193    #[must_use]
194    pub fn out_path(mut self, path: impl Into<PathBuf>) -> Self {
195        self.out = Some(path.into());
196        self
197    }
198
199    /// Sets where source downloads are cached. The default is the
200    /// [`cache_dir()`](crate::cache_dir) chain (`UTZ_CACHE_DIR`, then the
201    /// per-user cache directory). Point this at a pre-fetched directory
202    /// for hermetic builds with no network. Build scripts relying on the
203    /// environment default should emit
204    /// `cargo:rerun-if-env-changed=UTZ_CACHE_DIR` (and
205    /// `UTZ_TZBB_RELEASE` if unpinned).
206    #[must_use]
207    pub fn cache_dir(mut self, path: impl Into<PathBuf>) -> Self {
208        self.cache_dir = Some(path.into());
209        self
210    }
211
212    /// Fetches the sources (cached), builds the asset, writes it, and
213    /// returns the path. It also writes `<out>.guard.rs`, a compile-time
214    /// assertion of the `utz` features this asset needs (via `utz::caps`);
215    /// `include!` it next to the `include_bytes!` so a feature mismatch
216    /// fails the build instead of the first load.
217    ///
218    /// # Errors
219    /// Returns an error for out-of-range `quant_bits`/`grid_deg`, a
220    /// source download/parse failure, an encoding failure, a missing
221    /// `OUT_DIR` when no `out_path` is set, or an I/O failure writing
222    /// the asset and its guard file.
223    pub fn generate(self) -> crate::Result<PathBuf> {
224        let cache = self.cache_dir.clone().unwrap_or_else(crate::cache_dir);
225        let (features, release) = crate::loader::load_tzbb(self.dataset, &cache)?;
226        let params = Params {
227            dataset: self.dataset,
228            tzbb_release: &release,
229            epsilon_m: self.epsilon_m,
230            quant_bits: self.quant_bits,
231            grid_deg: self.grid_deg,
232            codec: self.codec,
233            simplify: self.simplify,
234            geom: self.geom,
235            density_weight_floor: self.density_weight_floor,
236        };
237        let bytes = match self.density_weight_floor {
238            Some(floor) => {
239                let grid = crate::density::DensityGrid::load(&cache)?;
240                crate::encode_weighted(
241                    &features,
242                    &params,
243                    &grid,
244                    utz_simplify::DensityWeight::new(floor),
245                )?
246            }
247            None => encode::encode(&features, &params)?,
248        };
249        let out = if let Some(path) = self.out {
250            path
251        } else {
252            let dir = std::env::var_os("OUT_DIR").ok_or_else(|| crate::Error::NoOutDir)?;
253            PathBuf::from(dir).join("tz.utz")
254        };
255        if let Some(parent) = out.parent() {
256            std::fs::create_dir_all(parent)?;
257        }
258        std::fs::write(&out, &bytes)?;
259        write_guard(&out, self.geom, self.codec)?;
260        Ok(out)
261    }
262}
263
264/// Converts a recipe, typically one of the [`utz_common::presets`]
265/// constants, into a config carrying its knobs. The named preset
266/// constructors are thin wrappers over this; use it directly to drive
267/// the builder from the table (e.g. iterating [`presets::ALL`]).
268impl From<&Recipe> for Config {
269    fn from(recipe: &Recipe) -> Config {
270        let config = Config::new()
271            .dataset(recipe.dataset)
272            .epsilon_meters(recipe.epsilon_m)
273            .quant_bits(recipe.quant_bits.bits())
274            .grid_deg(recipe.grid_deg)
275            .codec(recipe.codec)
276            .simplify_algorithm(recipe.simplify_algorithm)
277            .geom(recipe.geom);
278        match recipe.density_weight_floor() {
279            Some(floor) => config.density_weight_floor(floor),
280            None => config,
281        }
282    }
283}
284
285/// Converts an owned recipe into a config; see [`From<&Recipe>`](#impl-From<%26Recipe>-for-Config).
286impl From<Recipe> for Config {
287    fn from(recipe: Recipe) -> Config {
288        Config::from(&recipe)
289    }
290}
291
292/// Emits `<asset>.guard.rs`, the `const _` assertions against `utz::caps`
293/// for the geometry decoder and codec the asset needs (shared by
294/// [`Config::generate()`] and the `gen` CLI).
295///
296/// # Errors
297/// Returns an error on an I/O failure writing `<out>.guard.rs`.
298pub fn write_guard(out: &std::path::Path, geom: GeomEncoding, codec: Codec) -> crate::Result<()> {
299    let name = out
300        .file_name()
301        .and_then(|file_name| file_name.to_str())
302        .unwrap_or("asset");
303    let (geom_cap_name, geom_feature_name) = match geom {
304        GeomEncoding::VarintArcs => ("GEOM_VARINT_ARCS", "geom-varint-arcs"),
305        GeomEncoding::FixedWidthArcs => ("GEOM_FIXED_WIDTH_ARCS", "geom-fixed-width-arcs"),
306        GeomEncoding::FullRings => ("GEOM_FULL_RINGS", "geom-full-rings"),
307        GeomEncoding::Coarse => ("GEOM_COARSE", "geom-coarse"),
308    };
309    let mut guard_source = format!(
310        "// generated by utz_build alongside {name}: include! this next to the\n\
311         // include_bytes! to turn a missing-feature load error into a compile error.\n\
312         const _: () = assert!(utz::caps::{geom_cap_name}, \"{name} needs the utz feature `{geom_feature_name}`\");\n"
313    );
314    let codec_guard = match codec {
315        Codec::Uncompressed => None,
316        Codec::Gzip => Some(("CODEC_GZIP", "gzip")),
317        Codec::Zstd => Some(("CODEC_ZSTD", "ruzstd` or `zstd-sys")),
318        Codec::Brotli => Some(("CODEC_BROTLI", "brotli")),
319        Codec::Xz => Some(("CODEC_XZ", "xz")),
320    };
321    if let Some((codec_cap_name, codec_feature_name)) = codec_guard {
322        use std::fmt::Write as _;
323        let _ = writeln!(
324            guard_source,
325            "const _: () = assert!(utz::caps::{codec_cap_name}, \"{name} needs the utz feature `{codec_feature_name}`\");"
326        );
327    }
328    std::fs::write(format!("{}.guard.rs", out.display()), guard_source)?;
329    Ok(())
330}