Skip to main content

utz_common/
presets.rs

1//! The canonical preset recipe table. Every preset asset the workspace
2//! ships is described here exactly once, as a [`Recipe`] constant; the
3//! builder presets (`utz_build::Config`), the `gen-preset` command, and
4//! the data crates' recipe guards all consume this table instead of
5//! restating the numbers.
6//!
7//! A recipe stores each knob in the representation the builder takes
8//! (`f64` tolerance and grid size, enum knobs), except the density
9//! floor, which is stored in the header's fixed-point form because the
10//! builder-side fraction derives from it exactly while the reverse
11//! rounding is unavailable in `core`. The [`Provenance`] type bridges
12//! the remaining gap to [`PayloadHeader`]: it owns the `f64` → `f32`
13//! casts the encoder applies when stamping the header, so a guard can
14//! compare `Provenance::from(&header)` against `Provenance::from(recipe)`
15//! with no literals of its own.
16
17use crate::{Codec, Dataset, GeomEncoding, PayloadHeader, QuantBits, SimplifyAlgorithm};
18
19/// One preset's complete build recipe: the name and every encoder knob
20/// that determines the shipped asset's provenance stamp.
21#[derive(Debug, Clone, Copy, PartialEq)]
22pub struct Recipe {
23    /// The preset name, e.g. `"tiny-static"`, as spelled in feature
24    /// names, crate names (with `-` as `_`), and asset file names.
25    pub name: &'static str,
26    /// The dataset the asset is built from.
27    pub dataset: Dataset,
28    /// The simplification tolerance in meters, as the builder takes it
29    /// (the header stores the `f32` cast).
30    pub epsilon_m: f64,
31    /// The coordinate quantization width.
32    pub quant_bits: QuantBits,
33    /// The grid cell size in degrees, as the builder takes it (the
34    /// header stores the `f32` cast).
35    pub grid_deg: f64,
36    /// The simplification algorithm the encoder runs.
37    pub simplify_algorithm: SimplifyAlgorithm,
38    /// The geometry encoding.
39    pub geom: GeomEncoding,
40    /// The payload compression codec.
41    pub codec: Codec,
42    /// The population-density weight floor in fixed-point 1e-4, the
43    /// header's representation; 0 means unweighted. The builder-side
44    /// fraction is [`density_weight_floor()`](Recipe::density_weight_floor).
45    pub density_weight_floor_e4: u16,
46}
47
48/// The `tiny` recipe: RDP ε=10 000 m with pop-density floor 0.001, i16,
49/// a 2° grid, and gzip.
50pub const TINY: Recipe = Recipe {
51    name: "tiny",
52    dataset: Dataset::Now,
53    epsilon_m: 10_000.0,
54    quant_bits: QuantBits::Bits16,
55    grid_deg: 2.0,
56    simplify_algorithm: SimplifyAlgorithm::Rdp,
57    geom: GeomEncoding::VarintArcs,
58    codec: Codec::Gzip,
59    density_weight_floor_e4: 10,
60};
61
62/// The `tiny-static` recipe, which is [`TINY`] stored uncompressed so
63/// the asset is readable in place with zero decode RAM.
64pub const TINY_STATIC: Recipe = Recipe {
65    name: "tiny-static",
66    codec: Codec::Uncompressed,
67    ..TINY
68};
69
70/// The `compact` recipe: RDP ε=1 000 m with pop-density floor 0.001,
71/// i24, a 4/3° grid, and xz.
72pub const COMPACT: Recipe = Recipe {
73    name: "compact",
74    epsilon_m: 1_000.0,
75    quant_bits: QuantBits::Bits24,
76    grid_deg: 4.0 / 3.0,
77    codec: Codec::Xz,
78    ..TINY
79};
80
81/// The `balanced` recipe: RDP ε=50 m with pop-density floor 0.020, i24,
82/// a 2/3° grid, and brotli.
83pub const BALANCED: Recipe = Recipe {
84    name: "balanced",
85    epsilon_m: 50.0,
86    quant_bits: QuantBits::Bits24,
87    grid_deg: 2.0 / 3.0,
88    codec: Codec::Brotli,
89    density_weight_floor_e4: 200,
90    ..TINY
91};
92
93/// The `accurate` recipe: dataset `all` (the full Comprehensive zone
94/// set; the other presets use `now`), RDP ε=10 m with pop-density floor
95/// 0.10, i32, a 0.5° grid, and brotli.
96pub const ACCURATE: Recipe = Recipe {
97    name: "accurate",
98    dataset: Dataset::All,
99    epsilon_m: 10.0,
100    quant_bits: QuantBits::Bits32,
101    grid_deg: 0.5,
102    codec: Codec::Brotli,
103    density_weight_floor_e4: 1_000,
104    ..TINY
105};
106
107/// Every preset recipe, in size order. Tools that need the preset name
108/// list (CLI validation, generate-all loops) iterate this instead of
109/// keeping their own copy.
110pub static ALL: [Recipe; 5] = [TINY, TINY_STATIC, COMPACT, BALANCED, ACCURATE];
111
112/// Looks a recipe up by its preset name; the result is `None` for a
113/// name the table does not carry.
114#[must_use]
115pub fn by_name(name: &str) -> Option<&'static Recipe> {
116    ALL.iter().find(|recipe| recipe.name == name)
117}
118
119impl Recipe {
120    /// Returns the density floor as the fraction the builder takes,
121    /// `None` when the recipe is unweighted. The division is exact:
122    /// both operands are exactly representable and every 4-decimal
123    /// fraction rounds to the same nearest `f64` its literal parses to,
124    /// so the derived value is bit-identical to the fraction the asset
125    /// was generated with.
126    #[must_use]
127    pub fn density_weight_floor(&self) -> Option<f64> {
128        (self.density_weight_floor_e4 != 0)
129            .then(|| f64::from(self.density_weight_floor_e4) / 10_000.0)
130    }
131}
132
133/// The subset of header fields a recipe determines, in the header's
134/// representation (`f32` tolerance and grid size, fixed-point floor).
135/// Converting both a [`Recipe`] and a [`PayloadHeader`] into this type
136/// gives a recipe guard an exact, literal-free equality check.
137#[derive(Debug, Clone, Copy, PartialEq)]
138pub struct Provenance {
139    /// The dataset the asset was built from.
140    pub dataset: Dataset,
141    /// The simplification tolerance in meters, as stamped in the header.
142    pub epsilon_m: f32,
143    /// The coordinate quantization width.
144    pub quant_bits: QuantBits,
145    /// The grid cell size in degrees, as stamped in the header.
146    pub grid_deg: f32,
147    /// The simplification algorithm the encoder ran.
148    pub simplify_algorithm: SimplifyAlgorithm,
149    /// The geometry encoding.
150    pub geom: GeomEncoding,
151    /// The payload compression codec.
152    pub codec: Codec,
153    /// The density floor in fixed-point 1e-4; 0 means unweighted.
154    pub density_weight_floor_e4: u16,
155}
156
157impl From<&PayloadHeader> for Provenance {
158    fn from(header: &PayloadHeader) -> Provenance {
159        Provenance {
160            dataset: header.dataset,
161            epsilon_m: header.epsilon_m,
162            quant_bits: header.quant_bits,
163            grid_deg: header.grid_deg,
164            simplify_algorithm: header.simplify_algorithm,
165            geom: header.geom,
166            codec: header.codec,
167            density_weight_floor_e4: header.density_weight_floor_e4,
168        }
169    }
170}
171
172impl From<&Recipe> for Provenance {
173    fn from(recipe: &Recipe) -> Provenance {
174        #[expect(
175            clippy::cast_possible_truncation,
176            reason = "the encoder stamps epsilon_m and grid_deg through this same f64-to-f32 cast, so the provenance stamp matches it bit-exactly"
177        )]
178        Provenance {
179            dataset: recipe.dataset,
180            epsilon_m: recipe.epsilon_m as f32,
181            quant_bits: recipe.quant_bits,
182            grid_deg: recipe.grid_deg as f32,
183            simplify_algorithm: recipe.simplify_algorithm,
184            geom: recipe.geom,
185            codec: recipe.codec,
186            density_weight_floor_e4: recipe.density_weight_floor_e4,
187        }
188    }
189}
190
191#[cfg(test)]
192mod tests {
193    use super::{ACCURATE, ALL, BALANCED, COMPACT, Provenance, Recipe, TINY, TINY_STATIC, by_name};
194    use crate::Codec;
195
196    #[test]
197    fn names_are_unique_and_by_name_round_trips() {
198        for (index, recipe) in ALL.iter().enumerate() {
199            assert_eq!(
200                by_name(recipe.name).map(|found| found.name),
201                Some(recipe.name)
202            );
203            assert!(
204                ALL[..index].iter().all(|other| other.name != recipe.name),
205                "duplicate preset name {:?}",
206                recipe.name
207            );
208        }
209        assert!(by_name("no-such-preset").is_none());
210    }
211
212    #[test]
213    fn tiny_static_differs_from_tiny_only_in_codec() {
214        let restored = Recipe {
215            codec: Codec::Gzip,
216            name: "tiny",
217            ..TINY_STATIC
218        };
219        assert_eq!(restored, TINY);
220        assert_eq!(TINY_STATIC.codec, Codec::Uncompressed);
221    }
222
223    #[test]
224    fn density_floor_fractions_match_the_builder_literals_exactly() {
225        assert_eq!(TINY.density_weight_floor(), Some(0.001));
226        assert_eq!(COMPACT.density_weight_floor(), Some(0.001));
227        assert_eq!(BALANCED.density_weight_floor(), Some(0.020));
228        assert_eq!(ACCURATE.density_weight_floor(), Some(0.10));
229        let unweighted = Recipe {
230            density_weight_floor_e4: 0,
231            ..TINY
232        };
233        assert_eq!(unweighted.density_weight_floor(), None);
234    }
235
236    #[test]
237    fn provenance_casts_match_the_encoder_stamps() {
238        #[expect(
239            clippy::cast_possible_truncation,
240            reason = "the assertion reproduces the encoder's f64-to-f32 stamp on purpose"
241        )]
242        for recipe in &ALL {
243            let provenance = Provenance::from(recipe);
244            assert_eq!(
245                provenance.epsilon_m.to_bits(),
246                (recipe.epsilon_m as f32).to_bits()
247            );
248            assert_eq!(
249                provenance.grid_deg.to_bits(),
250                (recipe.grid_deg as f32).to_bits()
251            );
252            assert_eq!(provenance.dataset, recipe.dataset);
253            assert_eq!(provenance.codec, recipe.codec);
254        }
255    }
256}