Skip to main content

logicaffeine_base/
quantity.rs

1//! Quantities: an exact magnitude carrying a physical [`Dimension`] and a unit.
2//!
3//! A *quantity* is a number with a unit — `2 inches`, `5 kilograms`, `9.8 m/s²`. Internally a
4//! [`Quantity`] stores its magnitude in the **SI base unit** for its dimension (metres, kilograms,
5//! seconds, …) as an exact [`Rational`], so:
6//!
7//! - addition/subtraction require the SAME dimension and just add magnitudes,
8//! - multiplication/division combine dimensions (`Length × Length = Area`),
9//! - conversion to another unit of the same dimension is exact (`÷ scale`, offset-aware), and
10//! - converting across dimensions (`Length → Mass`) is impossible — the forbidden cast.
11//!
12//! Because every unit's scale to the SI base is an exact rational (1 inch = 127/5000 m *exactly*),
13//! the whole thing is lossless: `2 inches + 5 centimetres` is `63/625 m`, which `in feet` is exactly
14//! `42/127`. A [`Unit`] may be *affine* (a nonzero `offset`, like °C/°F), so a temperature converts
15//! with scale AND offset; linear units have `offset = 0`.
16
17use crate::dimension::Dimension;
18use crate::numeric::Rational;
19
20/// A unit of measurement: its dimension and how to map a value in this unit to the SI base.
21/// `si = value · scale + offset`. Linear units have `offset = 0`; affine units (°C, °F) do not.
22#[derive(Clone, Debug, PartialEq, Eq)]
23pub struct Unit {
24    pub symbol: &'static str,
25    pub dimension: Dimension,
26    /// Multiply a value in this unit by `scale` to reach the SI base unit. Exact, nonzero.
27    pub scale: Rational,
28    /// The affine zero offset, added after scaling (0 for linear units).
29    pub offset: Rational,
30}
31
32impl Unit {
33    /// A linear unit (`si = value · scale`).
34    pub fn linear(symbol: &'static str, dimension: Dimension, scale: Rational) -> Unit {
35        Unit {
36            symbol,
37            dimension,
38            scale,
39            offset: Rational::zero(),
40        }
41    }
42
43    /// An affine unit (`si = value · scale + offset`) — temperatures.
44    pub fn affine(
45        symbol: &'static str,
46        dimension: Dimension,
47        scale: Rational,
48        offset: Rational,
49    ) -> Unit {
50        Unit {
51            symbol,
52            dimension,
53            scale,
54            offset,
55        }
56    }
57}
58
59/// An exact quantity: a magnitude in the SI base unit, tagged with its dimension.
60#[derive(Clone, Debug, PartialEq, Eq)]
61pub struct Quantity {
62    /// The magnitude expressed in the SI base unit of `dimension` (metres, kilograms, …).
63    magnitude: Rational,
64    dimension: Dimension,
65}
66
67impl Quantity {
68    /// A quantity of `value` of `unit` — normalized to the SI base (`value·scale + offset`).
69    pub fn of(value: Rational, unit: &Unit) -> Quantity {
70        Quantity {
71            magnitude: value.mul(&unit.scale).add(&unit.offset),
72            dimension: unit.dimension,
73        }
74    }
75
76    /// A dimensionless quantity (a pure number) — for scaling.
77    pub fn scalar(value: Rational) -> Quantity {
78        Quantity {
79            magnitude: value,
80            dimension: Dimension::DIMENSIONLESS,
81        }
82    }
83
84    /// A quantity given directly by its SI-base magnitude and dimension — used for physical
85    /// constants and any value whose dimension has no single named unit (e.g. the gas constant).
86    pub fn si(magnitude: Rational, dimension: Dimension) -> Quantity {
87        Quantity {
88            magnitude,
89            dimension,
90        }
91    }
92
93    /// The magnitude in the SI base unit.
94    pub fn magnitude_si(&self) -> &Rational {
95        &self.magnitude
96    }
97
98    pub fn dimension(&self) -> Dimension {
99        self.dimension
100    }
101
102    /// The magnitude expressed IN `unit` — `None` if the dimensions differ (the forbidden cast).
103    /// Linear: `(si)/scale`; affine: `(si − offset)/scale`. `1 mile in feet` is exactly `5280`.
104    pub fn in_unit(&self, unit: &Unit) -> Option<Rational> {
105        if self.dimension != unit.dimension {
106            return None;
107        }
108        self.magnitude.sub(&unit.offset).div(&unit.scale)
109    }
110
111    /// `self + other` — `None` unless the dimensions match (you cannot add Length to Mass).
112    pub fn add(&self, other: &Quantity) -> Option<Quantity> {
113        if self.dimension != other.dimension {
114            return None;
115        }
116        Some(Quantity {
117            magnitude: self.magnitude.add(&other.magnitude),
118            dimension: self.dimension,
119        })
120    }
121
122    /// `self − other` — `None` unless the dimensions match.
123    pub fn sub(&self, other: &Quantity) -> Option<Quantity> {
124        if self.dimension != other.dimension {
125            return None;
126        }
127        Some(Quantity {
128            magnitude: self.magnitude.sub(&other.magnitude),
129            dimension: self.dimension,
130        })
131    }
132
133    /// `self × other` — magnitudes multiply, dimensions combine (`Length × Length = Area`).
134    pub fn mul(&self, other: &Quantity) -> Quantity {
135        Quantity {
136            magnitude: self.magnitude.mul(&other.magnitude),
137            dimension: self.dimension.mul(other.dimension),
138        }
139    }
140
141    /// `self ÷ other` — magnitudes divide, dimensions subtract. `None` on a zero divisor magnitude.
142    pub fn div(&self, other: &Quantity) -> Option<Quantity> {
143        Some(Quantity {
144            magnitude: self.magnitude.div(&other.magnitude)?,
145            dimension: self.dimension.div(other.dimension),
146        })
147    }
148
149    /// Choose the most human-readable unit from `ladder` and return `(magnitude_in_it, unit)`.
150    /// The winner is the unit whose magnitude has the smallest absolute value that is still `≥ 1`
151    /// (so `1500 m → (1.5, km)`, `0.5 km → (500, m)`); if every candidate is below 1 the largest
152    /// magnitude (closest to 1 from below) wins. Units of a different dimension are skipped, so a
153    /// ladder with no same-dimension unit yields `None`. Exact — the conversion never rounds, and
154    /// `Quantity::of(mag, unit)` reconstructs `self`. This is Design Law #3 (auto-scale to the most
155    /// human unit), kept pure at the base layer so the interpreter `Showable` and AOT both reuse it.
156    pub fn in_best_unit<'a>(&self, ladder: &'a [Unit]) -> Option<(Rational, &'a Unit)> {
157        let one = Rational::one();
158        let mut best: Option<(Rational, &Unit)> = None;
159        for u in ladder {
160            let Some(mag) = self.in_unit(u) else { continue };
161            best = Some(match best {
162                None => (mag, u),
163                Some((best_mag, best_u)) => {
164                    let (abs, best_abs) = (mag.abs(), best_mag.abs());
165                    let take = match (abs >= one, best_abs >= one) {
166                        (true, true) => abs < best_abs, // both ≥ 1: prefer the one closest to 1 from above
167                        (true, false) => true,          // candidate qualifies, incumbent doesn't
168                        (false, true) => false,         // keep the qualifying incumbent
169                        (false, false) => abs > best_abs, // both < 1: prefer the one closest to 1 from below
170                    };
171                    if take {
172                        (mag, u)
173                    } else {
174                        (best_mag, best_u)
175                    }
176                }
177            });
178        }
179        best
180    }
181}
182
183/// The unit catalog — every scale an EXACT rational to the SI base. Organized by dimension.
184/// (Irrational-scaled units like `parsec` (648000/π·AU) and `mach` are intentionally omitted
185/// until a float-backed quantity exists; everything here is lossless.) A later wave moves this
186/// to a growable data file; the math and the names are settled here first.
187pub mod units {
188    use super::Unit;
189    use crate::dimension::Dimension;
190    use crate::numeric::Rational;
191
192    fn r(n: i64, d: i64) -> Rational {
193        Rational::from_ratio_i64(n, d).expect("nonzero denominator")
194    }
195    fn i(n: i64) -> Rational {
196        Rational::from_i64(n)
197    }
198    /// `n³` of a rational (exact).
199    fn cube(x: Rational) -> Rational {
200        x.pow(3).expect("cube exists")
201    }
202    /// `n²` of a rational (exact).
203    fn square(x: Rational) -> Rational {
204        x.pow(2).expect("square exists")
205    }
206
207    // Shared exact anchors.
208    fn inch_m() -> Rational {
209        r(127, 5000)
210    } // 1 inch = 0.0254 m, exactly
211    fn foot_m() -> Rational {
212        r(381, 1250)
213    } // 0.3048 m
214    fn lb_kg() -> Rational {
215        r(45_359_237, 100_000_000)
216    } // 0.45359237 kg
217    fn g0() -> Rational {
218        r(980_665, 100_000)
219    } // standard gravity 9.80665 m/s²
220    /// US liquid gallon = 231 in³ (exact), in m³.
221    fn us_gallon_m3() -> Rational {
222        cube(inch_m()).mul(&i(231))
223    }
224    /// Imperial gallon = 4.54609 L (exact), in m³.
225    fn imp_gallon_m3() -> Rational {
226        r(454_609, 100_000_000)
227    }
228
229    // ============================ LENGTH (base: metre) ============================
230    pub fn metre() -> Unit {
231        Unit::linear("m", Dimension::length(), Rational::one())
232    }
233    pub fn kilometre() -> Unit {
234        Unit::linear("km", Dimension::length(), i(1000))
235    }
236    pub fn hectometre() -> Unit {
237        Unit::linear("hm", Dimension::length(), i(100))
238    }
239    pub fn dekametre() -> Unit {
240        Unit::linear("dam", Dimension::length(), i(10))
241    }
242    pub fn decimetre() -> Unit {
243        Unit::linear("dm", Dimension::length(), r(1, 10))
244    }
245    pub fn centimetre() -> Unit {
246        Unit::linear("cm", Dimension::length(), r(1, 100))
247    }
248    pub fn millimetre() -> Unit {
249        Unit::linear("mm", Dimension::length(), r(1, 1000))
250    }
251    pub fn micrometre() -> Unit {
252        Unit::linear("µm", Dimension::length(), r(1, 1_000_000))
253    }
254    pub fn nanometre() -> Unit {
255        Unit::linear("nm", Dimension::length(), r(1, 1_000_000_000))
256    }
257    pub fn angstrom() -> Unit {
258        Unit::linear("Å", Dimension::length(), r(1, 10_000_000_000))
259    }
260    pub fn inch() -> Unit {
261        Unit::linear("in", Dimension::length(), inch_m())
262    }
263    pub fn foot() -> Unit {
264        Unit::linear("ft", Dimension::length(), foot_m())
265    }
266    pub fn yard() -> Unit {
267        Unit::linear("yd", Dimension::length(), r(1143, 1250))
268    } // 0.9144 m
269    pub fn mile() -> Unit {
270        Unit::linear("mi", Dimension::length(), r(201_168, 125))
271    } // 1609.344 m
272    pub fn nautical_mile() -> Unit {
273        Unit::linear("nmi", Dimension::length(), i(1852))
274    }
275    pub fn fathom() -> Unit {
276        Unit::linear("ftm", Dimension::length(), r(1143, 625))
277    } // 2 yd
278    pub fn furlong() -> Unit {
279        Unit::linear("fur", Dimension::length(), r(25_146, 125))
280    } // 201.168 m
281    pub fn chain() -> Unit {
282        Unit::linear("ch", Dimension::length(), r(12_573, 625))
283    } // 20.1168 m
284    pub fn rod() -> Unit {
285        Unit::linear("rod", Dimension::length(), r(12_573, 2500))
286    } // 5.0292 m
287    pub fn hand() -> Unit {
288        Unit::linear("hand", Dimension::length(), r(127, 1250))
289    } // 4 in
290    pub fn point() -> Unit {
291        Unit::linear("pt", Dimension::length(), r(127, 360_000))
292    } // 1/72 in
293    pub fn pica() -> Unit {
294        Unit::linear("pica", Dimension::length(), r(127, 30_000))
295    } // 1/6 in
296    pub fn thou() -> Unit {
297        Unit::linear("thou", Dimension::length(), r(127, 5_000_000))
298    } // 1/1000 in
299    pub fn astronomical_unit() -> Unit {
300        Unit::linear("AU", Dimension::length(), i(149_597_870_700))
301    }
302    pub fn light_year() -> Unit {
303        Unit::linear("ly", Dimension::length(), i(9_460_730_472_580_800))
304    } // c·Julian yr
305
306    // ============================ MASS (base: kilogram) ============================
307    pub fn kilogram() -> Unit {
308        Unit::linear("kg", Dimension::mass(), Rational::one())
309    }
310    pub fn gram() -> Unit {
311        Unit::linear("g", Dimension::mass(), r(1, 1000))
312    }
313    pub fn milligram() -> Unit {
314        Unit::linear("mg", Dimension::mass(), r(1, 1_000_000))
315    }
316    pub fn microgram() -> Unit {
317        Unit::linear("µg", Dimension::mass(), r(1, 1_000_000_000))
318    }
319    pub fn tonne() -> Unit {
320        Unit::linear("t", Dimension::mass(), i(1000))
321    }
322    pub fn pound() -> Unit {
323        Unit::linear("lb", Dimension::mass(), lb_kg())
324    }
325    pub fn ounce() -> Unit {
326        Unit::linear("oz", Dimension::mass(), lb_kg().div(&i(16)).unwrap())
327    }
328    pub fn stone() -> Unit {
329        Unit::linear("st", Dimension::mass(), lb_kg().mul(&i(14)))
330    }
331    pub fn short_ton() -> Unit {
332        Unit::linear("ton", Dimension::mass(), lb_kg().mul(&i(2000)))
333    }
334    pub fn long_ton() -> Unit {
335        Unit::linear("LT", Dimension::mass(), lb_kg().mul(&i(2240)))
336    }
337    pub fn hundredweight() -> Unit {
338        Unit::linear("cwt", Dimension::mass(), lb_kg().mul(&i(100)))
339    }
340    pub fn grain() -> Unit {
341        Unit::linear("gr", Dimension::mass(), lb_kg().div(&i(7000)).unwrap())
342    }
343    pub fn dram() -> Unit {
344        Unit::linear("dr", Dimension::mass(), lb_kg().div(&i(256)).unwrap())
345    } // oz/16
346    pub fn carat() -> Unit {
347        Unit::linear("ct", Dimension::mass(), r(1, 5000))
348    } // 0.2 g
349    pub fn troy_ounce() -> Unit {
350        Unit::linear("ozt", Dimension::mass(), r(311_034_768, 10_000_000_000))
351    } // 31.1034768 g
352    pub fn troy_pound() -> Unit {
353        Unit::linear(
354            "lbt",
355            Dimension::mass(),
356            r(311_034_768, 10_000_000_000).mul(&i(12)),
357        )
358    }
359
360    // ============================ TIME (base: second) ============================
361    pub fn second() -> Unit {
362        Unit::linear("s", Dimension::time(), Rational::one())
363    }
364    pub fn millisecond() -> Unit {
365        Unit::linear("ms", Dimension::time(), r(1, 1000))
366    }
367    pub fn microsecond() -> Unit {
368        Unit::linear("µs", Dimension::time(), r(1, 1_000_000))
369    }
370    pub fn nanosecond() -> Unit {
371        Unit::linear("ns", Dimension::time(), r(1, 1_000_000_000))
372    }
373    pub fn minute() -> Unit {
374        Unit::linear("min", Dimension::time(), i(60))
375    }
376    pub fn hour() -> Unit {
377        Unit::linear("h", Dimension::time(), i(3600))
378    }
379    pub fn day() -> Unit {
380        Unit::linear("day", Dimension::time(), i(86_400))
381    }
382    pub fn week() -> Unit {
383        Unit::linear("wk", Dimension::time(), i(604_800))
384    }
385    pub fn fortnight() -> Unit {
386        Unit::linear("fortnight", Dimension::time(), i(1_209_600))
387    }
388    pub fn julian_year() -> Unit {
389        Unit::linear("yr", Dimension::time(), i(31_557_600))
390    } // 365.25 d
391    pub fn decade() -> Unit {
392        Unit::linear("decade", Dimension::time(), i(315_576_000))
393    }
394    pub fn century() -> Unit {
395        Unit::linear("century", Dimension::time(), i(3_155_760_000))
396    }
397
398    // ====================== TEMPERATURE (base: kelvin), AFFINE ======================
399    pub fn kelvin() -> Unit {
400        Unit::affine(
401            "K",
402            Dimension::temperature(),
403            Rational::one(),
404            Rational::zero(),
405        )
406    }
407    pub fn celsius() -> Unit {
408        Unit::affine("°C", Dimension::temperature(), Rational::one(), r(5463, 20))
409    } // +273.15
410    pub fn fahrenheit() -> Unit {
411        Unit::affine("°F", Dimension::temperature(), r(5, 9), r(45967, 180))
412    }
413    pub fn rankine() -> Unit {
414        Unit::affine("°R", Dimension::temperature(), r(5, 9), Rational::zero())
415    } // K = °R·5/9
416    pub fn reaumur() -> Unit {
417        Unit::affine("°Ré", Dimension::temperature(), r(5, 4), r(5463, 20))
418    } // K = °Ré·5/4 + 273.15
419
420    // ============================ VOLUME (base: m³) ============================
421    pub fn cubic_metre() -> Unit {
422        Unit::linear("m³", Dimension::volume(), Rational::one())
423    }
424    pub fn litre() -> Unit {
425        Unit::linear("L", Dimension::volume(), r(1, 1000))
426    }
427    pub fn millilitre() -> Unit {
428        Unit::linear("mL", Dimension::volume(), r(1, 1_000_000))
429    }
430    pub fn centilitre() -> Unit {
431        Unit::linear("cL", Dimension::volume(), r(1, 100_000))
432    }
433    pub fn decilitre() -> Unit {
434        Unit::linear("dL", Dimension::volume(), r(1, 10_000))
435    }
436    pub fn cubic_centimetre() -> Unit {
437        Unit::linear("cc", Dimension::volume(), r(1, 1_000_000))
438    }
439    pub fn cubic_inch() -> Unit {
440        Unit::linear("in³", Dimension::volume(), cube(inch_m()))
441    }
442    pub fn cubic_foot() -> Unit {
443        Unit::linear("ft³", Dimension::volume(), cube(foot_m()))
444    }
445    // ---- US liquid / COOKING (anchored to the 231-in³ gallon) ----
446    pub fn us_gallon() -> Unit {
447        Unit::linear("gal", Dimension::volume(), us_gallon_m3())
448    }
449    pub fn us_quart() -> Unit {
450        Unit::linear(
451            "qt",
452            Dimension::volume(),
453            us_gallon_m3().div(&i(4)).unwrap(),
454        )
455    }
456    pub fn us_pint() -> Unit {
457        Unit::linear(
458            "pt",
459            Dimension::volume(),
460            us_gallon_m3().div(&i(8)).unwrap(),
461        )
462    }
463    pub fn us_cup() -> Unit {
464        Unit::linear(
465            "cup",
466            Dimension::volume(),
467            us_gallon_m3().div(&i(16)).unwrap(),
468        )
469    }
470    pub fn us_gill() -> Unit {
471        Unit::linear(
472            "gill",
473            Dimension::volume(),
474            us_gallon_m3().div(&i(32)).unwrap(),
475        )
476    }
477    pub fn us_fluid_ounce() -> Unit {
478        Unit::linear(
479            "fl oz",
480            Dimension::volume(),
481            us_gallon_m3().div(&i(128)).unwrap(),
482        )
483    }
484    pub fn tablespoon() -> Unit {
485        Unit::linear(
486            "tbsp",
487            Dimension::volume(),
488            us_gallon_m3().div(&i(256)).unwrap(),
489        )
490    }
491    pub fn teaspoon() -> Unit {
492        Unit::linear(
493            "tsp",
494            Dimension::volume(),
495            us_gallon_m3().div(&i(768)).unwrap(),
496        )
497    }
498    pub fn oil_barrel() -> Unit {
499        Unit::linear("bbl", Dimension::volume(), us_gallon_m3().mul(&i(42)))
500    } // 42 US gal
501      // ---- Imperial ----
502    pub fn imperial_gallon() -> Unit {
503        Unit::linear("imp gal", Dimension::volume(), imp_gallon_m3())
504    }
505    pub fn imperial_pint() -> Unit {
506        Unit::linear(
507            "imp pt",
508            Dimension::volume(),
509            imp_gallon_m3().div(&i(8)).unwrap(),
510        )
511    }
512    pub fn imperial_fluid_ounce() -> Unit {
513        Unit::linear(
514            "imp fl oz",
515            Dimension::volume(),
516            imp_gallon_m3().div(&i(160)).unwrap(),
517        )
518    }
519
520    // ============================ AREA (base: m²) ============================
521    pub fn square_metre() -> Unit {
522        Unit::linear("m²", Dimension::area(), Rational::one())
523    }
524    pub fn square_kilometre() -> Unit {
525        Unit::linear("km²", Dimension::area(), i(1_000_000))
526    }
527    pub fn square_centimetre() -> Unit {
528        Unit::linear("cm²", Dimension::area(), r(1, 10_000))
529    }
530    pub fn square_inch() -> Unit {
531        Unit::linear("in²", Dimension::area(), square(inch_m()))
532    }
533    pub fn square_foot() -> Unit {
534        Unit::linear("ft²", Dimension::area(), square(foot_m()))
535    }
536    pub fn square_yard() -> Unit {
537        Unit::linear("yd²", Dimension::area(), square(r(1143, 1250)))
538    }
539    pub fn square_mile() -> Unit {
540        Unit::linear("mi²", Dimension::area(), square(r(201_168, 125)))
541    }
542    pub fn hectare() -> Unit {
543        Unit::linear("ha", Dimension::area(), i(10_000))
544    }
545    pub fn are() -> Unit {
546        Unit::linear("a", Dimension::area(), i(100))
547    }
548    pub fn acre() -> Unit {
549        Unit::linear("ac", Dimension::area(), square(foot_m()).mul(&i(43_560)))
550    } // 43560 ft²
551
552    // ============================ SPEED (base: m/s) ============================
553    pub fn metre_per_second() -> Unit {
554        Unit::linear("m/s", Dimension::speed(), Rational::one())
555    }
556    pub fn kilometre_per_hour() -> Unit {
557        Unit::linear("km/h", Dimension::speed(), r(5, 18))
558    } // 1000/3600
559    pub fn mile_per_hour() -> Unit {
560        Unit::linear(
561            "mph",
562            Dimension::speed(),
563            r(201_168, 125).div(&i(3600)).unwrap(),
564        )
565    }
566    pub fn foot_per_second() -> Unit {
567        Unit::linear("ft/s", Dimension::speed(), foot_m())
568    }
569    pub fn knot() -> Unit {
570        Unit::linear("kn", Dimension::speed(), r(1852, 3600))
571    } // nmi/h
572
573    // ============================ FREQUENCY (base: 1/s) ============================
574    pub fn hertz() -> Unit {
575        Unit::linear("Hz", Dimension::frequency(), Rational::one())
576    }
577    pub fn kilohertz() -> Unit {
578        Unit::linear("kHz", Dimension::frequency(), i(1000))
579    }
580    pub fn megahertz() -> Unit {
581        Unit::linear("MHz", Dimension::frequency(), i(1_000_000))
582    }
583    pub fn gigahertz() -> Unit {
584        Unit::linear("GHz", Dimension::frequency(), i(1_000_000_000))
585    }
586    pub fn rpm() -> Unit {
587        Unit::linear("rpm", Dimension::frequency(), r(1, 60))
588    }
589
590    // ============================ FORCE (base: newton) ============================
591    pub fn newton() -> Unit {
592        Unit::linear("N", Dimension::force(), Rational::one())
593    }
594    pub fn kilonewton() -> Unit {
595        Unit::linear("kN", Dimension::force(), i(1000))
596    }
597    pub fn dyne() -> Unit {
598        Unit::linear("dyn", Dimension::force(), r(1, 100_000))
599    }
600    pub fn kilogram_force() -> Unit {
601        Unit::linear("kgf", Dimension::force(), g0())
602    }
603    pub fn pound_force() -> Unit {
604        Unit::linear("lbf", Dimension::force(), lb_kg().mul(&g0()))
605    }
606
607    // ============================ ENERGY (base: joule) ============================
608    pub fn joule() -> Unit {
609        Unit::linear("J", Dimension::energy(), Rational::one())
610    }
611    pub fn kilojoule() -> Unit {
612        Unit::linear("kJ", Dimension::energy(), i(1000))
613    }
614    pub fn megajoule() -> Unit {
615        Unit::linear("MJ", Dimension::energy(), i(1_000_000))
616    }
617    pub fn calorie() -> Unit {
618        Unit::linear("cal", Dimension::energy(), r(523, 125))
619    } // 4.184 J
620    pub fn kilocalorie() -> Unit {
621        Unit::linear("kcal", Dimension::energy(), r(4184, 1))
622    }
623    pub fn watt_hour() -> Unit {
624        Unit::linear("Wh", Dimension::energy(), i(3600))
625    }
626    pub fn kilowatt_hour() -> Unit {
627        Unit::linear("kWh", Dimension::energy(), i(3_600_000))
628    }
629    pub fn erg() -> Unit {
630        Unit::linear("erg", Dimension::energy(), r(1, 10_000_000))
631    }
632    pub fn electronvolt() -> Unit {
633        // 1.602176634e-19 J = 1602176634 / 10^28 (the 10^28 denominator overflows i64, so build it
634        // from BigInt — exact).
635        use crate::numeric::BigInt;
636        let scale = Rational::new(
637            BigInt::from_i64(1_602_176_634),
638            BigInt::from_i64(10).pow(28),
639        )
640        .expect("nonzero denominator");
641        Unit::linear("eV", Dimension::energy(), scale)
642    }
643
644    // ============================ POWER (base: watt) ============================
645    pub fn watt() -> Unit {
646        Unit::linear("W", Dimension::power(), Rational::one())
647    }
648    pub fn kilowatt() -> Unit {
649        Unit::linear("kW", Dimension::power(), i(1000))
650    }
651    pub fn megawatt() -> Unit {
652        Unit::linear("MW", Dimension::power(), i(1_000_000))
653    }
654    pub fn horsepower() -> Unit {
655        Unit::linear(
656            "hp",
657            Dimension::power(),
658            lb_kg().mul(&g0()).mul(&foot_m()).mul(&i(550)),
659        )
660    } // 550 ft·lbf/s
661
662    // ============================ PRESSURE (base: pascal) ============================
663    pub fn pascal() -> Unit {
664        Unit::linear("Pa", Dimension::pressure(), Rational::one())
665    }
666    pub fn kilopascal() -> Unit {
667        Unit::linear("kPa", Dimension::pressure(), i(1000))
668    }
669    pub fn bar() -> Unit {
670        Unit::linear("bar", Dimension::pressure(), i(100_000))
671    }
672    pub fn millibar() -> Unit {
673        Unit::linear("mbar", Dimension::pressure(), i(100))
674    }
675    pub fn atmosphere() -> Unit {
676        Unit::linear("atm", Dimension::pressure(), i(101_325))
677    }
678    pub fn psi() -> Unit {
679        Unit::linear(
680            "psi",
681            Dimension::pressure(),
682            lb_kg().mul(&g0()).div(&square(inch_m())).unwrap(),
683        )
684    } // lbf/in²
685
686    // ============================ INFORMATION (base: bit) ============================
687    pub fn bit() -> Unit {
688        Unit::linear("bit", Dimension::information(), Rational::one())
689    }
690    pub fn byte() -> Unit {
691        Unit::linear("B", Dimension::information(), i(8))
692    }
693    pub fn kilobit() -> Unit {
694        Unit::linear("kbit", Dimension::information(), i(1000))
695    }
696    pub fn kilobyte() -> Unit {
697        Unit::linear("kB", Dimension::information(), i(8000))
698    }
699    pub fn megabyte() -> Unit {
700        Unit::linear("MB", Dimension::information(), i(8_000_000))
701    }
702    pub fn gigabyte() -> Unit {
703        Unit::linear("GB", Dimension::information(), i(8_000_000_000))
704    }
705    pub fn kibibyte() -> Unit {
706        Unit::linear("KiB", Dimension::information(), i(8 * 1024))
707    }
708    pub fn mebibyte() -> Unit {
709        Unit::linear("MiB", Dimension::information(), i(8 * 1024 * 1024))
710    }
711    pub fn gibibyte() -> Unit {
712        Unit::linear("GiB", Dimension::information(), i(8 * 1024 * 1024 * 1024))
713    }
714
715    // ============================ ANGLE (base: radian) ============================
716    // (Degrees etc. are exact multiples of a turn; radian-to-degree is irrational, so these are
717    // defined against the TURN as the natural rational anchor — full circle = 1 turn.)
718    pub fn turn() -> Unit {
719        Unit::linear("turn", Dimension::angle(), Rational::one())
720    }
721    pub fn degree() -> Unit {
722        Unit::linear("°", Dimension::angle(), r(1, 360))
723    }
724    pub fn gradian() -> Unit {
725        Unit::linear("grad", Dimension::angle(), r(1, 400))
726    }
727    pub fn arcminute() -> Unit {
728        Unit::linear("′", Dimension::angle(), r(1, 21_600))
729    } // degree/60
730    pub fn arcsecond() -> Unit {
731        Unit::linear("″", Dimension::angle(), r(1, 1_296_000))
732    } // degree/3600
733
734    // ============================ ELECTRICAL ============================
735    pub fn ampere() -> Unit {
736        Unit::linear("A", Dimension::current(), Rational::one())
737    }
738    pub fn milliampere() -> Unit {
739        Unit::linear("mA", Dimension::current(), r(1, 1000))
740    }
741    pub fn coulomb() -> Unit {
742        Unit::linear("C", Dimension::charge(), Rational::one())
743    }
744    pub fn ampere_hour() -> Unit {
745        Unit::linear("Ah", Dimension::charge(), i(3600))
746    }
747    pub fn milliampere_hour() -> Unit {
748        Unit::linear("mAh", Dimension::charge(), r(18, 5))
749    } // 3.6 C
750    pub fn volt() -> Unit {
751        Unit::linear("V", Dimension::voltage(), Rational::one())
752    }
753    pub fn millivolt() -> Unit {
754        Unit::linear("mV", Dimension::voltage(), r(1, 1000))
755    }
756    pub fn kilovolt() -> Unit {
757        Unit::linear("kV", Dimension::voltage(), i(1000))
758    }
759    pub fn ohm() -> Unit {
760        Unit::linear("Ω", Dimension::resistance(), Rational::one())
761    }
762
763    // ============================ AMOUNT / LUMINOUS ============================
764    pub fn mole() -> Unit {
765        Unit::linear("mol", Dimension::amount(), Rational::one())
766    }
767    pub fn candela() -> Unit {
768        Unit::linear("cd", Dimension::luminous(), Rational::one())
769    }
770
771    /// `mantissa · 10^pow10` as an exact rational (for values past i64, e.g. stellar masses).
772    fn e(mantissa: i64, pow10: u32) -> Rational {
773        use crate::numeric::BigInt;
774        Rational::from_bigint(BigInt::from_i64(mantissa).mul(&BigInt::from_i64(10).pow(pow10)))
775    }
776
777    // ============================ COOKING EXTRAS (volume) ============================
778    pub fn stick_of_butter() -> Unit {
779        Unit::linear(
780            "stick",
781            Dimension::volume(),
782            us_gallon_m3().div(&i(32)).unwrap(),
783        )
784    } // ½ cup = 8 tbsp
785    pub fn dash() -> Unit {
786        Unit::linear(
787            "dash",
788            Dimension::volume(),
789            us_gallon_m3().div(&i(6144)).unwrap(),
790        )
791    } // ⅛ tsp
792    pub fn pinch() -> Unit {
793        Unit::linear(
794            "pinch",
795            Dimension::volume(),
796            us_gallon_m3().div(&i(12288)).unwrap(),
797        )
798    } // ¹⁄₁₆ tsp
799    pub fn smidgen() -> Unit {
800        Unit::linear(
801            "smidgen",
802            Dimension::volume(),
803            us_gallon_m3().div(&i(24576)).unwrap(),
804        )
805    } // ¹⁄₃₂ tsp
806      // US DRY volume (anchored to the 2150.42-in³ bushel).
807    fn us_bushel_m3() -> Rational {
808        cube(inch_m()).mul(&r(215_042, 100))
809    } // 2150.42 in³
810    pub fn bushel() -> Unit {
811        Unit::linear("bu", Dimension::volume(), us_bushel_m3())
812    }
813    pub fn peck() -> Unit {
814        Unit::linear(
815            "pk",
816            Dimension::volume(),
817            us_bushel_m3().div(&i(4)).unwrap(),
818        )
819    }
820    pub fn dry_gallon() -> Unit {
821        Unit::linear(
822            "dry gal",
823            Dimension::volume(),
824            us_bushel_m3().div(&i(8)).unwrap(),
825        )
826    }
827    pub fn dry_quart() -> Unit {
828        Unit::linear(
829            "dry qt",
830            Dimension::volume(),
831            us_bushel_m3().div(&i(32)).unwrap(),
832        )
833    }
834    pub fn dry_pint() -> Unit {
835        Unit::linear(
836            "dry pt",
837            Dimension::volume(),
838            us_bushel_m3().div(&i(64)).unwrap(),
839        )
840    }
841
842    // ============================ NAUTICAL (length) ============================
843    pub fn cable() -> Unit {
844        Unit::linear("cable", Dimension::length(), r(926, 5))
845    } // ¹⁄₁₀ nmi = 185.2 m
846    pub fn league() -> Unit {
847        Unit::linear("lea", Dimension::length(), r(603_504, 125))
848    } // 3 statute miles
849    pub fn nautical_league() -> Unit {
850        Unit::linear("nl", Dimension::length(), i(5556))
851    } // 3 nmi
852
853    // ============================ ASTRONOMICAL ============================
854    pub fn light_second() -> Unit {
855        Unit::linear("ls", Dimension::length(), i(299_792_458))
856    } // c·1 s
857    pub fn light_minute() -> Unit {
858        Unit::linear("lmin", Dimension::length(), i(299_792_458 * 60))
859    }
860    pub fn light_hour() -> Unit {
861        Unit::linear("lh", Dimension::length(), i(299_792_458 * 3600))
862    }
863    pub fn light_day() -> Unit {
864        Unit::linear("ld", Dimension::length(), i(299_792_458 * 86_400))
865    }
866    pub fn lunar_distance() -> Unit {
867        Unit::linear("LD", Dimension::length(), i(384_399_000))
868    } // mean Earth–Moon
869    pub fn solar_radius() -> Unit {
870        Unit::linear("R☉", Dimension::length(), i(696_340_000))
871    }
872    pub fn earth_radius() -> Unit {
873        Unit::linear("R⊕", Dimension::length(), i(6_371_000))
874    } // mean
875      // Astronomical MASSES (measured values, exact as the conventional decimals given).
876    pub fn solar_mass() -> Unit {
877        Unit::linear("M☉", Dimension::mass(), e(198_892, 25))
878    } // 1.98892e30 kg
879    pub fn earth_mass() -> Unit {
880        Unit::linear("M⊕", Dimension::mass(), e(59_722, 20))
881    } // 5.9722e24 kg
882    pub fn jupiter_mass() -> Unit {
883        Unit::linear("M♃", Dimension::mass(), e(18_982, 23))
884    } // 1.8982e27 kg
885
886    // ============================ RADIATION ============================
887    pub fn gray() -> Unit {
888        Unit::linear("Gy", Dimension::absorbed_dose(), Rational::one())
889    } // J/kg
890    pub fn sievert() -> Unit {
891        Unit::linear("Sv", Dimension::absorbed_dose(), Rational::one())
892    } // J/kg (equiv dose)
893    pub fn rad_unit() -> Unit {
894        Unit::linear("rad", Dimension::absorbed_dose(), r(1, 100))
895    } // 0.01 Gy
896    pub fn rem() -> Unit {
897        Unit::linear("rem", Dimension::absorbed_dose(), r(1, 100))
898    } // 0.01 Sv
899    pub fn becquerel() -> Unit {
900        Unit::linear("Bq", Dimension::radioactivity(), Rational::one())
901    } // 1/s
902    pub fn curie() -> Unit {
903        Unit::linear("Ci", Dimension::radioactivity(), i(37_000_000_000))
904    } // 3.7e10 Bq
905    pub fn roentgen() -> Unit {
906        Unit::linear("R", Dimension::exposure(), r(129, 500_000))
907    } // 2.58e-4 C/kg
908    pub fn katal() -> Unit {
909        Unit::linear("kat", Dimension::catalytic_activity(), Rational::one())
910    } // mol/s
911
912    // ============================ ILLUMINATION (photometry) ============================
913    pub fn lumen() -> Unit {
914        Unit::linear("lm", Dimension::luminous_flux(), Rational::one())
915    } // cd·sr
916    pub fn lux() -> Unit {
917        Unit::linear("lx", Dimension::illuminance(), Rational::one())
918    } // lm/m²
919    pub fn phot() -> Unit {
920        Unit::linear("ph", Dimension::illuminance(), i(10_000))
921    } // lm/cm²
922    pub fn foot_candle() -> Unit {
923        Unit::linear("fc", Dimension::illuminance(), square(r(1250, 381)))
924    } // lm/ft² = 1/0.3048² lx
925    pub fn nit() -> Unit {
926        Unit::linear("nit", Dimension::luminance(), Rational::one())
927    } // cd/m²
928
929    // ============================ DATA RATE (base: bit/s) ============================
930    pub fn bit_per_second() -> Unit {
931        Unit::linear("bit/s", Dimension::data_rate(), Rational::one())
932    }
933    pub fn kilobit_per_second() -> Unit {
934        Unit::linear("kbps", Dimension::data_rate(), i(1000))
935    }
936    pub fn megabit_per_second() -> Unit {
937        Unit::linear("Mbps", Dimension::data_rate(), i(1_000_000))
938    }
939    pub fn gigabit_per_second() -> Unit {
940        Unit::linear("Gbps", Dimension::data_rate(), i(1_000_000_000))
941    }
942    pub fn byte_per_second() -> Unit {
943        Unit::linear("B/s", Dimension::data_rate(), i(8))
944    }
945    pub fn megabyte_per_second() -> Unit {
946        Unit::linear("MB/s", Dimension::data_rate(), i(8_000_000))
947    }
948
949    // ============================ VOLUMETRIC FLOW (base: m³/s) ============================
950    pub fn cubic_metre_per_second() -> Unit {
951        Unit::linear("m³/s", Dimension::volumetric_flow(), Rational::one())
952    }
953    pub fn litre_per_second() -> Unit {
954        Unit::linear("L/s", Dimension::volumetric_flow(), r(1, 1000))
955    }
956    pub fn litre_per_minute() -> Unit {
957        Unit::linear("L/min", Dimension::volumetric_flow(), r(1, 60_000))
958    }
959    pub fn gallon_per_minute() -> Unit {
960        Unit::linear(
961            "gpm",
962            Dimension::volumetric_flow(),
963            us_gallon_m3().div(&i(60)).unwrap(),
964        )
965    }
966    pub fn cubic_foot_per_minute() -> Unit {
967        Unit::linear(
968            "cfm",
969            Dimension::volumetric_flow(),
970            cube(foot_m()).div(&i(60)).unwrap(),
971        )
972    }
973
974    // ============================ CONCENTRATION (base: mol/m³) ============================
975    pub fn molar() -> Unit {
976        Unit::linear("M", Dimension::molar_concentration(), i(1000))
977    } // mol/L
978    pub fn millimolar() -> Unit {
979        Unit::linear("mM", Dimension::molar_concentration(), Rational::one())
980    }
981    pub fn micromolar() -> Unit {
982        Unit::linear("µM", Dimension::molar_concentration(), r(1, 1000))
983    }
984    pub fn molal() -> Unit {
985        Unit::linear("m", Dimension::molality(), Rational::one())
986    } // mol/kg
987
988    // ============================ VISCOSITY ============================
989    pub fn pascal_second() -> Unit {
990        Unit::linear("Pa·s", Dimension::dynamic_viscosity(), Rational::one())
991    }
992    pub fn poise() -> Unit {
993        Unit::linear("P", Dimension::dynamic_viscosity(), r(1, 10))
994    }
995    pub fn centipoise() -> Unit {
996        Unit::linear("cP", Dimension::dynamic_viscosity(), r(1, 1000))
997    }
998    pub fn square_metre_per_second() -> Unit {
999        Unit::linear("m²/s", Dimension::kinematic_viscosity(), Rational::one())
1000    }
1001    pub fn stokes() -> Unit {
1002        Unit::linear("St", Dimension::kinematic_viscosity(), r(1, 10_000))
1003    }
1004    pub fn centistokes() -> Unit {
1005        Unit::linear("cSt", Dimension::kinematic_viscosity(), r(1, 1_000_000))
1006    }
1007
1008    // ============================ FUEL ECONOMY (base: m/m³ = m⁻²) ============================
1009    pub fn mile_per_gallon() -> Unit {
1010        Unit::linear(
1011            "mpg",
1012            Dimension::fuel_economy(),
1013            r(201_168, 125).div(&us_gallon_m3()).unwrap(),
1014        )
1015    }
1016    pub fn km_per_litre() -> Unit {
1017        Unit::linear(
1018            "km/L",
1019            Dimension::fuel_economy(),
1020            i(1000).div(&r(1, 1000)).unwrap(),
1021        )
1022    } // 10^6 m⁻²
1023
1024    // ============================ TORQUE (shares the energy dimension M·L²·T⁻²) ============================
1025    pub fn newton_metre() -> Unit {
1026        Unit::linear("N·m", Dimension::energy(), Rational::one())
1027    }
1028    pub fn pound_foot() -> Unit {
1029        Unit::linear(
1030            "lb·ft",
1031            Dimension::energy(),
1032            lb_kg().mul(&g0()).mul(&foot_m()),
1033        )
1034    }
1035
1036    // ============================ EXTRA SI PREFIXES (extend existing dimensions) ============================
1037    pub fn megametre() -> Unit {
1038        Unit::linear("Mm", Dimension::length(), i(1_000_000))
1039    }
1040    pub fn gigametre() -> Unit {
1041        Unit::linear("Gm", Dimension::length(), i(1_000_000_000))
1042    }
1043    pub fn picometre() -> Unit {
1044        Unit::linear("pm", Dimension::length(), r(1, 1_000_000_000_000))
1045    }
1046    pub fn femtometre() -> Unit {
1047        Unit::linear("fm", Dimension::length(), r(1, 1_000_000_000_000_000))
1048    }
1049    pub fn nanogram() -> Unit {
1050        Unit::linear("ng", Dimension::mass(), r(1, 1_000_000_000_000))
1051    }
1052    pub fn picosecond() -> Unit {
1053        Unit::linear("ps", Dimension::time(), r(1, 1_000_000_000_000))
1054    }
1055    pub fn gigawatt() -> Unit {
1056        Unit::linear("GW", Dimension::power(), i(1_000_000_000))
1057    }
1058    pub fn terawatt() -> Unit {
1059        Unit::linear("TW", Dimension::power(), i(1_000_000_000_000))
1060    }
1061    pub fn gigajoule() -> Unit {
1062        Unit::linear("GJ", Dimension::energy(), i(1_000_000_000))
1063    }
1064    pub fn terajoule() -> Unit {
1065        Unit::linear("TJ", Dimension::energy(), i(1_000_000_000_000))
1066    }
1067    pub fn terabit() -> Unit {
1068        Unit::linear("Tbit", Dimension::information(), i(1_000_000_000_000))
1069    }
1070    pub fn terabyte() -> Unit {
1071        Unit::linear("TB", Dimension::information(), i(8_000_000_000_000))
1072    }
1073    pub fn petabyte() -> Unit {
1074        Unit::linear("PB", Dimension::information(), i(8_000_000_000_000_000))
1075    }
1076
1077    // ============================ ELECTROMAGNETISM ============================
1078    pub fn siemens() -> Unit {
1079        Unit::linear("S", Dimension::conductance(), Rational::one())
1080    }
1081    pub fn millisiemens() -> Unit {
1082        Unit::linear("mS", Dimension::conductance(), r(1, 1000))
1083    }
1084    pub fn farad() -> Unit {
1085        Unit::linear("F", Dimension::capacitance(), Rational::one())
1086    }
1087    pub fn microfarad() -> Unit {
1088        Unit::linear("µF", Dimension::capacitance(), r(1, 1_000_000))
1089    }
1090    pub fn nanofarad() -> Unit {
1091        Unit::linear("nF", Dimension::capacitance(), r(1, 1_000_000_000))
1092    }
1093    pub fn picofarad() -> Unit {
1094        Unit::linear("pF", Dimension::capacitance(), r(1, 1_000_000_000_000))
1095    }
1096    pub fn weber() -> Unit {
1097        Unit::linear("Wb", Dimension::magnetic_flux(), Rational::one())
1098    }
1099    pub fn maxwell() -> Unit {
1100        Unit::linear("Mx", Dimension::magnetic_flux(), r(1, 100_000_000))
1101    } // 1e-8 Wb
1102    pub fn henry() -> Unit {
1103        Unit::linear("H", Dimension::inductance(), Rational::one())
1104    }
1105    pub fn millihenry() -> Unit {
1106        Unit::linear("mH", Dimension::inductance(), r(1, 1000))
1107    }
1108    pub fn microhenry() -> Unit {
1109        Unit::linear("µH", Dimension::inductance(), r(1, 1_000_000))
1110    }
1111    pub fn tesla() -> Unit {
1112        Unit::linear("T", Dimension::magnetic_flux_density(), Rational::one())
1113    }
1114    pub fn millitesla() -> Unit {
1115        Unit::linear("mT", Dimension::magnetic_flux_density(), r(1, 1000))
1116    }
1117    pub fn gauss() -> Unit {
1118        Unit::linear("G", Dimension::magnetic_flux_density(), r(1, 10_000))
1119    } // 1e-4 T
1120
1121    // ============================ SURFACE TENSION (base: N/m) ============================
1122    pub fn newton_per_metre() -> Unit {
1123        Unit::linear("N/m", Dimension::surface_tension(), Rational::one())
1124    }
1125    pub fn dyne_per_centimetre() -> Unit {
1126        Unit::linear("dyn/cm", Dimension::surface_tension(), r(1, 1000))
1127    } // 1e-3 N/m
1128
1129    // ============================ COUNTING & RATIO (dimensionless) ============================
1130    // The base "unit" is a bare count of one; everything here is a pure dimensionless scale factor.
1131    pub fn each() -> Unit {
1132        Unit::linear("ea", Dimension::DIMENSIONLESS, Rational::one())
1133    }
1134    pub fn pair() -> Unit {
1135        Unit::linear("pair", Dimension::DIMENSIONLESS, i(2))
1136    }
1137    pub fn dozen() -> Unit {
1138        Unit::linear("dz", Dimension::DIMENSIONLESS, i(12))
1139    }
1140    pub fn baker_dozen() -> Unit {
1141        Unit::linear("baker's dz", Dimension::DIMENSIONLESS, i(13))
1142    }
1143    pub fn score() -> Unit {
1144        Unit::linear("score", Dimension::DIMENSIONLESS, i(20))
1145    }
1146    pub fn gross() -> Unit {
1147        Unit::linear("gross", Dimension::DIMENSIONLESS, i(144))
1148    }
1149    pub fn great_gross() -> Unit {
1150        Unit::linear("great gross", Dimension::DIMENSIONLESS, i(1728))
1151    }
1152    pub fn ream() -> Unit {
1153        Unit::linear("ream", Dimension::DIMENSIONLESS, i(500))
1154    }
1155    pub fn percent() -> Unit {
1156        Unit::linear("%", Dimension::DIMENSIONLESS, r(1, 100))
1157    }
1158    pub fn permille() -> Unit {
1159        Unit::linear("‰", Dimension::DIMENSIONLESS, r(1, 1000))
1160    }
1161    pub fn ppm() -> Unit {
1162        Unit::linear("ppm", Dimension::DIMENSIONLESS, r(1, 1_000_000))
1163    }
1164    pub fn ppb() -> Unit {
1165        Unit::linear("ppb", Dimension::DIMENSIONLESS, r(1, 1_000_000_000))
1166    }
1167    pub fn basis_point() -> Unit {
1168        Unit::linear("bp", Dimension::DIMENSIONLESS, r(1, 10_000))
1169    }
1170
1171    /// Look up a unit by an English name, plural, or symbol (case-insensitive) — the surface-syntax
1172    /// bridge so `quantity(2, "inch")` / `... in "feet"` resolve to a [`Unit`]. This is the growable
1173    /// catalog's name index; unknown names return `None` (the front-end turns that into a clean
1174    /// error). Spelling variants and both singular/plural map to the same unit.
1175    pub fn by_name(name: &str) -> Option<Unit> {
1176        let n = name.trim().to_ascii_lowercase();
1177        let u = match n.as_str() {
1178            // Length.
1179            "meter" | "metre" | "meters" | "metres" | "m" => metre(),
1180            "kilometer" | "kilometre" | "kilometers" | "kilometres" | "km" => kilometre(),
1181            "centimeter" | "centimetre" | "centimeters" | "centimetres" | "cm" => centimetre(),
1182            "millimeter" | "millimetre" | "millimeters" | "millimetres" | "mm" => millimetre(),
1183            "micrometer" | "micrometre" | "micron" | "microns" | "µm" | "um" => micrometre(),
1184            "nanometer" | "nanometre" | "nanometers" | "nanometres" | "nm" => nanometre(),
1185            "inch" | "inches" | "in" => inch(),
1186            "foot" | "feet" | "ft" => foot(),
1187            "yard" | "yards" | "yd" => yard(),
1188            "mile" | "miles" | "mi" => mile(),
1189            "nautical mile" | "nautical miles" | "nmi" => nautical_mile(),
1190            "angstrom" | "angstroms" | "ångström" | "å" => angstrom(),
1191            "light year" | "light years" | "lightyear" | "ly" => light_year(),
1192            "astronomical unit" | "astronomical units" | "au" => astronomical_unit(),
1193            // Mass.
1194            "kilogram" | "kilograms" | "kg" => kilogram(),
1195            "gram" | "grams" | "g" => gram(),
1196            "milligram" | "milligrams" | "mg" => milligram(),
1197            "microgram" | "micrograms" | "µg" | "ug" => microgram(),
1198            "tonne" | "tonnes" | "metric ton" | "metric tons" | "t" => tonne(),
1199            "pound" | "pounds" | "lb" | "lbs" => pound(),
1200            "ounce" | "ounces" | "oz" => ounce(),
1201            "stone" | "stones" | "st" => stone(),
1202            "carat" | "carats" | "ct" => carat(),
1203            // Time.
1204            "second" | "seconds" | "sec" | "secs" | "s" => second(),
1205            "millisecond" | "milliseconds" | "ms" => millisecond(),
1206            "microsecond" | "microseconds" | "µs" | "us" => microsecond(),
1207            "nanosecond" | "nanoseconds" | "ns" => nanosecond(),
1208            "minute" | "minutes" | "min" | "mins" => minute(),
1209            "hour" | "hours" | "hr" | "hrs" | "h" => hour(),
1210            "day" | "days" => day(),
1211            "week" | "weeks" | "wk" => week(),
1212            "year" | "years" | "yr" | "yrs" => julian_year(),
1213            // Temperature (affine).
1214            "kelvin" | "k" => kelvin(),
1215            "celsius" | "centigrade" | "°c" | "c" => celsius(),
1216            "fahrenheit" | "°f" | "f" => fahrenheit(),
1217            "rankine" | "°r" => rankine(),
1218            "reaumur" | "réaumur" | "°ré" => reaumur(),
1219            // Volume (incl. cooking).
1220            "liter" | "litre" | "liters" | "litres" | "l" => litre(),
1221            "milliliter" | "millilitre" | "milliliters" | "millilitres" | "ml" => millilitre(),
1222            "cubic meter" | "cubic metre" | "m3" | "m³" => cubic_metre(),
1223            "gallon" | "gallons" | "gal" => us_gallon(),
1224            "quart" | "quarts" | "qt" => us_quart(),
1225            "pint" | "pints" | "pt" => us_pint(),
1226            "cup" | "cups" => us_cup(),
1227            "tablespoon" | "tablespoons" | "tbsp" => tablespoon(),
1228            "teaspoon" | "teaspoons" | "tsp" => teaspoon(),
1229            "fluid ounce" | "fluid ounces" | "fl oz" => us_fluid_ounce(),
1230            // Area.
1231            "square meter" | "square metre" | "square meters" | "square metres" | "m2" => {
1232                square_metre()
1233            }
1234            "square foot" | "square feet" | "sq ft" => square_foot(),
1235            "square inch" | "square inches" | "sq in" => square_inch(),
1236            "hectare" | "hectares" | "ha" => hectare(),
1237            "acre" | "acres" => acre(),
1238            // Speed.
1239            "meter per second" | "metre per second" | "meters per second" | "m/s" => {
1240                metre_per_second()
1241            }
1242            "kilometer per hour" | "kilometre per hour" | "km/h" | "kph" => kilometre_per_hour(),
1243            "mile per hour" | "miles per hour" | "mph" => mile_per_hour(),
1244            "knot" | "knots" | "kn" => knot(),
1245            // Frequency.
1246            "hertz" | "hz" => hertz(),
1247            "kilohertz" | "khz" => kilohertz(),
1248            "megahertz" | "mhz" => megahertz(),
1249            "gigahertz" | "ghz" => gigahertz(),
1250            // Energy.
1251            "joule" | "joules" | "j" => joule(),
1252            "kilojoule" | "kilojoules" | "kj" => kilojoule(),
1253            "calorie" | "calories" | "cal" => calorie(),
1254            "kilocalorie" | "kilocalories" | "kcal" => kilocalorie(),
1255            "watt hour" | "watt hours" | "wh" => watt_hour(),
1256            "kilowatt hour" | "kilowatt hours" | "kwh" => kilowatt_hour(),
1257            "electronvolt" | "electronvolts" | "ev" => electronvolt(),
1258            // Power.
1259            "watt" | "watts" | "w" => watt(),
1260            "kilowatt" | "kilowatts" | "kw" => kilowatt(),
1261            "megawatt" | "megawatts" | "mw" => megawatt(),
1262            "horsepower" | "hp" => horsepower(),
1263            // Pressure.
1264            "pascal" | "pascals" | "pa" => pascal(),
1265            "kilopascal" | "kilopascals" | "kpa" => kilopascal(),
1266            "bar" | "bars" => bar(),
1267            "atmosphere" | "atmospheres" | "atm" => atmosphere(),
1268            "psi" => psi(),
1269            // Information.
1270            "bit" | "bits" => bit(),
1271            "byte" | "bytes" => byte(),
1272            "kilobyte" | "kilobytes" | "kb" => kilobyte(),
1273            "megabyte" | "megabytes" | "mb" => megabyte(),
1274            "gigabyte" | "gigabytes" | "gb" => gigabyte(),
1275            // Angle (radian is irrational vs. these and is intentionally absent, like parsec/mach).
1276            "turn" | "turns" => turn(),
1277            "degree" | "degrees" | "deg" | "°" => degree(),
1278            "gradian" | "gradians" | "grad" => gradian(),
1279            "arcminute" | "arcminutes" => arcminute(),
1280            "arcsecond" | "arcseconds" => arcsecond(),
1281            // Radiation & catalysis.
1282            "gray" | "grays" | "gy" => gray(),
1283            "sievert" | "sieverts" | "sv" => sievert(),
1284            "rad" | "rads" => rad_unit(),
1285            "rem" | "rems" => rem(),
1286            "becquerel" | "becquerels" | "bq" => becquerel(),
1287            "curie" | "curies" | "ci" => curie(),
1288            "roentgen" | "roentgens" => roentgen(),
1289            "katal" | "katals" | "kat" => katal(),
1290            // Photometry.
1291            "lumen" | "lumens" | "lm" => lumen(),
1292            "lux" | "lx" => lux(),
1293            "phot" | "phots" => phot(),
1294            "foot candle" | "foot-candle" | "footcandle" | "fc" => foot_candle(),
1295            "nit" | "nits" => nit(),
1296            // Electromagnetism. (The bare "v"/"a" symbols are intentionally absent — they
1297            // collide with everyday identifiers and the article, like radian/parsec above.)
1298            "volt" | "volts" => volt(),
1299            "millivolt" | "millivolts" | "mv" => millivolt(),
1300            "kilovolt" | "kilovolts" | "kv" => kilovolt(),
1301            "ampere" | "amperes" | "amp" | "amps" => ampere(),
1302            "milliampere" | "milliamperes" | "milliamp" | "milliamps" => milliampere(),
1303            "coulomb" | "coulombs" => coulomb(),
1304            "ampere hour" | "ampere hours" | "ah" => ampere_hour(),
1305            "milliampere hour" | "milliampere hours" | "mah" => milliampere_hour(),
1306            "ohm" | "ohms" | "ω" => ohm(),
1307            "siemens" => siemens(),
1308            "millisiemens" => millisiemens(),
1309            "farad" | "farads" => farad(),
1310            "microfarad" | "microfarads" | "µf" | "uf" => microfarad(),
1311            "nanofarad" | "nanofarads" | "nf" => nanofarad(),
1312            "picofarad" | "picofarads" | "pf" => picofarad(),
1313            "weber" | "webers" | "wb" => weber(),
1314            "maxwell" | "maxwells" | "mx" => maxwell(),
1315            "henry" | "henries" => henry(),
1316            "tesla" | "teslas" => tesla(),
1317            "gauss" => gauss(),
1318            // Viscosity.
1319            "pascal second" | "pascal-second" | "pa·s" | "pas" => pascal_second(),
1320            "poise" => poise(),
1321            "centipoise" | "cp" => centipoise(),
1322            "stokes" | "stoke" => stokes(),
1323            "centistokes" | "cst" => centistokes(),
1324            // Flow & concentration.
1325            "gallon per minute" | "gpm" => gallon_per_minute(),
1326            "cubic foot per minute" | "cfm" => cubic_foot_per_minute(),
1327            "litre per second" | "liter per second" | "l/s" => litre_per_second(),
1328            "molar" => molar(),
1329            "millimolar" | "mm/l" => millimolar(),
1330            // Data rate.
1331            "bit per second" | "bits per second" | "bps" => bit_per_second(),
1332            "kilobit per second" | "kbps" => kilobit_per_second(),
1333            "megabit per second" | "mbps" => megabit_per_second(),
1334            "gigabit per second" | "gbps" => gigabit_per_second(),
1335            "byte per second" | "bytes per second" => byte_per_second(),
1336            // Surface tension.
1337            "newton per meter" | "newton per metre" | "n/m" => newton_per_metre(),
1338            // Cooking extras.
1339            "stick" | "sticks" | "stick of butter" => stick_of_butter(),
1340            "dash" | "dashes" => dash(),
1341            "pinch" | "pinches" => pinch(),
1342            "smidgen" | "smidgens" => smidgen(),
1343            // Nautical.
1344            "fathom" | "fathoms" => fathom(),
1345            "cable" | "cables" => cable(),
1346            "league" | "leagues" => league(),
1347            // Astronomical.
1348            "light second" | "light-second" | "light seconds" => light_second(),
1349            "light minute" | "light-minute" | "light minutes" => light_minute(),
1350            // (parsec is irrational vs. metre — intentionally absent, like mach.)
1351            // Counting & ratio (dimensionless).
1352            "each" | "ea" | "count" => each(),
1353            "pair" | "pairs" => pair(),
1354            "dozen" | "dozens" | "dz" => dozen(),
1355            "score" | "scores" => score(),
1356            "gross" => gross(),
1357            "ream" | "reams" => ream(),
1358            "percent" | "percents" | "%" => percent(),
1359            "permille" | "per mille" | "‰" => permille(),
1360            "ppm" => ppm(),
1361            "ppb" => ppb(),
1362            "basis point" | "basis points" => basis_point(),
1363            // Extra SI prefixes (the ones beyond the common ladder above).
1364            "megameter" | "megametre" => megametre(),
1365            "gigameter" | "gigametre" => gigametre(),
1366            "picometer" | "picometre" | "pm" => picometre(),
1367            "nanogram" | "nanograms" => nanogram(),
1368            "gigawatt" | "gigawatts" | "gw" => gigawatt(),
1369            "terawatt" | "terawatts" | "tw" => terawatt(),
1370            "terabyte" | "terabytes" | "tb" => terabyte(),
1371            "petabyte" | "petabytes" | "pb" => petabyte(),
1372            _ => return None,
1373        };
1374        Some(u)
1375    }
1376}
1377
1378/// Physical constants as first-class [`Quantity`] values — each carries its dimension, so they
1379/// compose with units under the same dimensional algebra (`E = m·c²` type-checks, and `c` can be
1380/// asked for `in kilometres_per_hour`). The post-2019-SI defining constants are EXACT rationals
1381/// (the SI fixes their numeric values); measured constants (G) use their CODATA value.
1382pub mod constants {
1383    use super::Quantity;
1384    use crate::dimension::Dimension;
1385    use crate::numeric::{BigInt, Rational};
1386
1387    /// `mantissa · 10^pow10` exactly (for large positive magnitudes like Avogadro's number).
1388    fn ep(mantissa: i64, pow10: u32) -> Rational {
1389        Rational::from_bigint(BigInt::from_i64(mantissa).mul(&BigInt::from_i64(10).pow(pow10)))
1390    }
1391    /// `mantissa · 10^(−pow10)` exactly (for tiny magnitudes like Planck's constant).
1392    fn en(mantissa: i64, pow10: u32) -> Rational {
1393        Rational::new(BigInt::from_i64(mantissa), BigInt::from_i64(10).pow(pow10)).unwrap()
1394    }
1395    fn r(n: i64, d: i64) -> Rational {
1396        Rational::new(BigInt::from_i64(n), BigInt::from_i64(d)).unwrap()
1397    }
1398
1399    /// The action dimension (energy × time = M·L²·T⁻¹), used by the Planck constant.
1400    fn action() -> Dimension {
1401        Dimension::energy().mul(Dimension::time())
1402    }
1403
1404    /// Speed of light in vacuum, `c` = 299 792 458 m/s (exact).
1405    pub fn speed_of_light() -> Quantity {
1406        Quantity::si(ep(299_792_458, 0), Dimension::speed())
1407    }
1408    /// Planck constant, `h` = 6.626 070 15 × 10⁻³⁴ J·s (exact).
1409    pub fn planck_constant() -> Quantity {
1410        Quantity::si(en(662_607_015, 42), action())
1411    }
1412    /// Elementary charge, `e` = 1.602 176 634 × 10⁻¹⁹ C (exact).
1413    pub fn elementary_charge() -> Quantity {
1414        Quantity::si(en(1_602_176_634, 28), Dimension::charge())
1415    }
1416    /// Boltzmann constant, `k_B` = 1.380 649 × 10⁻²³ J/K (exact).
1417    pub fn boltzmann_constant() -> Quantity {
1418        Quantity::si(
1419            en(1_380_649, 29),
1420            Dimension::energy().div(Dimension::temperature()),
1421        )
1422    }
1423    /// Avogadro constant, `N_A` = 6.022 140 76 × 10²³ mol⁻¹ (exact).
1424    pub fn avogadro_constant() -> Quantity {
1425        Quantity::si(ep(602_214_076, 15), Dimension::amount().recip())
1426    }
1427    /// Molar gas constant, `R = N_A · k_B` = 8.314 462 618… J/(mol·K) (exact, a product of exacts).
1428    pub fn molar_gas_constant() -> Quantity {
1429        avogadro_constant().mul(&boltzmann_constant())
1430    }
1431    /// Newtonian gravitational constant, `G` = 6.674 30 × 10⁻¹¹ m³·kg⁻¹·s⁻² (CODATA measured value).
1432    pub fn gravitational_constant() -> Quantity {
1433        let dim = Dimension::volume()
1434            .div(Dimension::mass())
1435            .div(Dimension::time().powi(2));
1436        Quantity::si(en(667_430, 16), dim)
1437    }
1438    /// Standard gravity, `g₀` = 9.806 65 m/s² (exact by definition).
1439    pub fn standard_gravity() -> Quantity {
1440        Quantity::si(r(980_665, 100_000), Dimension::acceleration())
1441    }
1442    /// Standard atmosphere, `atm` = 101 325 Pa (exact by definition).
1443    pub fn standard_atmosphere() -> Quantity {
1444        Quantity::si(ep(101_325, 0), Dimension::pressure())
1445    }
1446}
1447
1448/// The **light-travel time** across a distance — `distance / c`, exact. Returns a Time quantity, or
1449/// `None` if `distance` is not a length (the dimensional guard). This is the core of "universal /
1450/// space-travel time": the delay before an event at distance `d` is observed elsewhere (Earth↔Sun
1451/// ≈ 499 s, Earth↔Mars ≈ 3–22 min). The result rides the exact rational tower, so it never drifts.
1452pub fn light_travel_time(distance: &Quantity) -> Option<Quantity> {
1453    if distance.dimension() != Dimension::length() {
1454        return None;
1455    }
1456    distance.div(&constants::speed_of_light())
1457}
1458
1459/// Convert a **Time**-dimensioned quantity to a whole number of nanoseconds (rounded to the nearest),
1460/// the bridge from the exact `Quantity` world to the instant model. `None` if `q` is not a time, or
1461/// the result does not fit `i64`.
1462pub fn time_quantity_to_nanos(q: &Quantity) -> Option<i64> {
1463    if q.dimension() != Dimension::time() {
1464        return None;
1465    }
1466    // magnitude_si is in seconds; ×10⁹ → nanoseconds (still exact), rounded to the nearest whole.
1467    q.magnitude_si()
1468        .mul(&Rational::from_i64(1_000_000_000))
1469        .round()
1470        .to_i64()
1471}
1472
1473/// The instant (nanoseconds since the epoch) at which an event happening at `event_nanos` is
1474/// **observed** by someone a distance away — `event + distance/c`. The relativistic light-delay the
1475/// space-travel time model is built on. `None` if `distance` is not a length or the result overflows.
1476pub fn observed_arrival_nanos(event_nanos: i64, distance: &Quantity) -> Option<i64> {
1477    let delay = time_quantity_to_nanos(&light_travel_time(distance)?)?;
1478    event_nanos.checked_add(delay)
1479}
1480
1481/// A point in 3-D space, coordinates in **metres** (an inertial frame's axes). Euclidean distance
1482/// is transcendental (a square root), so positions are `f64` — the one place the time tower leaves
1483/// the exact-rational world, because the geometry of spacetime demands it.
1484#[derive(Clone, Copy, Debug, PartialEq)]
1485pub struct Position {
1486    pub x: f64,
1487    pub y: f64,
1488    pub z: f64,
1489}
1490
1491impl Position {
1492    /// The straight-line distance to another point, in metres.
1493    pub fn distance_to(self, other: Position) -> f64 {
1494        let (dx, dy, dz) = (self.x - other.x, self.y - other.y, self.z - other.z);
1495        (dx * dx + dy * dy + dz * dz).sqrt()
1496    }
1497}
1498
1499/// A **space-aware timestamp** — *when* (a SmoothUTC instant, nanoseconds) AND *where* (a position
1500/// in space). This is the heart of the light-cone model: two events can only be causally ordered if
1501/// their time separation is at least the light-travel time between their *positions*. Closer in time
1502/// than that and they are **spacelike-separated** — genuinely concurrent, no signal could connect
1503/// them, which is exactly where CRDTs (conflict-free, order-free merge) are the right tool.
1504#[derive(Clone, Copy, Debug, PartialEq)]
1505pub struct SpacetimeStamp {
1506    pub instant_nanos: i64,
1507    pub position: Position,
1508}
1509
1510/// How two [`SpacetimeStamp`]s relate causally. `Before`: `self` is in the past light cone of the
1511/// other (a signal from `self` could reach it). `After`: the reverse. `Concurrent`: spacelike —
1512/// neither can have affected the other.
1513#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1514pub enum CausalRelation {
1515    Before,
1516    After,
1517    Concurrent,
1518}
1519
1520impl SpacetimeStamp {
1521    /// The light-travel time (nanoseconds) between the two events' positions — the minimum time
1522    /// separation for a causal link. Symmetric.
1523    pub fn light_separation_nanos(self, other: SpacetimeStamp) -> i64 {
1524        let metres = self.position.distance_to(other.position);
1525        (metres / 299_792_458.0 * 1e9).round() as i64
1526    }
1527
1528    /// The causal relation to `other`, decided by the light cone: causally ordered only when the
1529    /// time gap covers the spatial (light) gap; otherwise spacelike-concurrent.
1530    pub fn causal_relation(self, other: SpacetimeStamp) -> CausalRelation {
1531        // i128 so a far-apart pair of i64 instants can't overflow the difference.
1532        let dt = other.instant_nanos as i128 - self.instant_nanos as i128;
1533        let light = self.light_separation_nanos(other) as i128;
1534        if dt >= light {
1535            CausalRelation::Before // `other` is in self's forward light cone
1536        } else if -dt >= light {
1537            CausalRelation::After // self is in other's forward light cone
1538        } else {
1539            CausalRelation::Concurrent // spacelike — |dt| < light, no signal connects them
1540        }
1541    }
1542
1543    /// The instant this event is **observed** from `observer` (its own time + the light delay across
1544    /// the distance) — the space-aware generalisation of [`observed_arrival_nanos`].
1545    pub fn observed_at_nanos(self, observer: Position) -> i64 {
1546        let other = SpacetimeStamp {
1547            instant_nanos: self.instant_nanos,
1548            position: observer,
1549        };
1550        self.instant_nanos + self.light_separation_nanos(other)
1551    }
1552}
1553
1554/// The special-relativistic **Lorentz factor** `γ = 1/√(1 − β²)` for a speed `β` as a fraction of
1555/// `c`. `None` for `|β| ≥ 1` (or NaN) — nothing reaches or exceeds light speed. Inherently a float
1556/// (relativity is transcendental), unlike the exact-rational quantity arithmetic.
1557pub fn lorentz_factor(beta: f64) -> Option<f64> {
1558    // `!(< 1.0)` also rejects NaN.
1559    if !(beta.abs() < 1.0) {
1560        return None;
1561    }
1562    Some(1.0 / (1.0 - beta * beta).sqrt())
1563}
1564
1565/// The **proper time** (in seconds) a clock experiences over `coordinate_seconds` of coordinate
1566/// time while moving at speed `β` (fraction of `c`): `coordinate / γ`. A moving clock ticks slow —
1567/// this is the space-traveller's "time attenuation". `None` for `|β| ≥ 1`.
1568pub fn proper_time_seconds(coordinate_seconds: f64, beta: f64) -> Option<f64> {
1569    Some(coordinate_seconds / lorentz_factor(beta)?)
1570}
1571
1572/// The time-dilation factor `γ` for a velocity given as a **speed [`Quantity`]** (β derived as
1573/// `v/c`). `None` if `velocity` is not a speed or is ≥ `c`.
1574pub fn time_dilation_factor(velocity: &Quantity) -> Option<f64> {
1575    if velocity.dimension() != Dimension::speed() {
1576        return None;
1577    }
1578    let c = constants::speed_of_light();
1579    let beta = velocity.magnitude_si().to_f64() / c.magnitude_si().to_f64();
1580    lorentz_factor(beta)
1581}
1582
1583#[cfg(test)]
1584#[path = "../../logicaffeine_tests/unit/logicaffeine_base/quantity/tests.rs"]
1585mod tests;