Skip to main content

lichtung_plot/theme/
spacing.rs

1//! Immutable reduced rational identities and exact local lengths.
2
3use std::cmp::Ordering;
4use std::sync::Arc;
5
6use num_bigint::BigUint;
7
8use crate::layout::kernel::{LayoutScalar, SpatialRounding};
9use crate::{Error, Result};
10
11#[derive(Debug, Clone, PartialEq, Eq)]
12struct Rational {
13    numerator: BigUint,
14    denominator: BigUint,
15}
16
17#[derive(Debug)]
18struct SpacingPayload {
19    rational: Rational,
20    // Immutable nearest-even inspection only. Never an identity/spatial operand.
21    approximate: f64,
22}
23
24impl PartialEq for SpacingPayload {
25    fn eq(&self, other: &Self) -> bool {
26        self.rational == other.rational
27    }
28}
29
30impl Eq for SpacingPayload {}
31
32/// Exact nonnegative dimensionless spacing, resolved against its consuming role's metric.
33///
34/// `new` retains the represented binary64 rational; `ratio` retains the reduced
35/// mathematical integer ratio. Approximate inspection is never a layout operand.
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct RelativeSpacing(Arc<SpacingPayload>);
38
39impl RelativeSpacing {
40    pub(crate) fn compare(&self, other: &Self) -> Ordering {
41        if Arc::ptr_eq(&self.0, &other.0) {
42            return Ordering::Equal;
43        }
44        let left = &self.0.rational;
45        let right = &other.0.rational;
46
47        (&left.numerator * &right.denominator).cmp(&(&right.numerator * &left.denominator))
48    }
49    pub(crate) fn same(&self, other: &Self) -> bool {
50        if Arc::ptr_eq(&self.0, &other.0) {
51            return true;
52        }
53        for (left, right) in [
54            (&self.0.rational.numerator, &other.0.rational.numerator),
55            (&self.0.rational.denominator, &other.0.rational.denominator),
56        ] {
57            if left.iter_u64_digits().len() != right.iter_u64_digits().len() {
58                return false;
59            }
60            let (mut left, mut right) = (left.iter_u64_digits(), right.iter_u64_digits());
61            while left.len() != 0 {
62                if left.next() != right.next() {
63                    return false;
64                }
65            }
66        }
67        true
68    }
69
70    pub(crate) fn observe_feedback(
71        &self,
72        round: &mut crate::layout::kernel::FeedbackRound,
73    ) -> Result<()> {
74        for value in [&self.0.rational.numerator, &self.0.rational.denominator] {
75            let mut digits = value.iter_u64_digits();
76            round.observe_count(digits.len())?;
77            while digits.len() != 0 {
78                let digit = digits.next().expect("remaining normalized rational digit");
79                round.observe_count((digit >> 32) as usize)?;
80                round.observe_count((digit & 0xffff_ffff) as usize)?;
81            }
82        }
83        Ok(())
84    }
85
86    /// Retain a finite nonnegative binary64 ratio, normalizing signed zero.
87    pub fn new(value: f64) -> Result<Self> {
88        validate(value)?;
89
90        let rational = dyadic(value);
91        Ok(Self(Arc::new(SpacingPayload {
92            rational,
93            approximate: if value == 0.0 { 0.0 } else { value },
94        })))
95    }
96
97    /// Retain a mathematical integer ratio; denominator must be positive.
98    pub fn ratio(numerator: u32, denominator: u32) -> Result<Self> {
99        if denominator == 0 {
100            return Err(invalid("ratio denominator must be positive"));
101        }
102
103        // Bounded Euclidean gcd on mathematical integers, before BigUint storage.
104        let (mut left, mut right) = (numerator, denominator);
105        while right != 0 {
106            (left, right) = (right, left % right);
107        }
108
109        Ok(Self(Arc::new(SpacingPayload {
110            rational: Rational {
111                numerator: BigUint::from(numerator / left),
112                denominator: BigUint::from(denominator / left),
113            },
114            // Both integer operands are exactly representable; IEEE division is
115            // nearest-even inspection of this rational, including canonical zero.
116            approximate: f64::from(numerator) / f64::from(denominator),
117        })))
118    }
119
120    pub(crate) fn from_pixels(pixels: f64, em: u32) -> Result<Self> {
121        validate(pixels)?;
122        if em == 0 {
123            return Err(invalid("source em must be positive"));
124        }
125
126        let source = dyadic(pixels);
127
128        let denominator = &source.denominator * em;
129        let rational = reduce(source.numerator, denominator);
130        Ok(Self(Arc::new(SpacingPayload {
131            rational,
132            approximate: if pixels == 0.0 {
133                0.0
134            } else {
135                pixels / f64::from(em)
136            },
137        })))
138    }
139
140    /// Inspect the nearest binary64 approximation without changing exact identity.
141    pub fn as_f64(&self) -> f64 {
142        self.0.approximate
143    }
144
145    pub(crate) fn is_zero(&self) -> bool {
146        self.0.rational.numerator.bits() == 0
147    }
148
149    pub(crate) fn product(&self, metric: LocalMetric) -> ExactLength {
150        let rational = &self.0.rational;
151        let metric = match metric {
152            LocalMetric::CssPixels(bits) => {
153                let mut value = dyadic(f64::from_bits(bits));
154                value.numerator *= 1024_u16;
155                value
156            }
157            LocalMetric::Quanta(value) => Rational {
158                numerator: BigUint::from(value),
159                denominator: BigUint::from(1_u8),
160            },
161        };
162
163        ExactLength(Rational {
164            numerator: &rational.numerator * metric.numerator,
165            denominator: &rational.denominator * metric.denominator,
166        })
167    }
168}
169
170/// A declared positive role em/radius or canonical local span, never a root size.
171#[derive(Debug, Clone, Copy)]
172pub(crate) enum LocalMetric {
173    CssPixels(u64),
174    Quanta(u64),
175}
176
177impl LocalMetric {
178    pub(crate) fn css_pixels(value: f64) -> Result<Self> {
179        if !value.is_finite() || value <= 0.0 {
180            return Err(invalid("local metric must be finite and positive"));
181        }
182        Ok(Self::CssPixels(value.to_bits()))
183    }
184
185    pub(crate) fn scalar(value: LayoutScalar) -> Result<Self> {
186        match u64::try_from(value.quanta()) {
187            Ok(value) if value > 0 => Ok(Self::Quanta(value)),
188            _ => Err(invalid("local metric must be positive")),
189        }
190    }
191}
192
193/// Unrounded nonnegative quanta. Aggregate before selecting a spatial boundary.
194#[derive(Debug, Clone)]
195pub(crate) struct ExactLength(Rational);
196
197// Test oracles may compare independently measured exact consequences. Runtime
198// matching uses the exact compare method, not this trait.
199#[cfg(test)]
200impl PartialEq for ExactLength {
201    fn eq(&self, other: &Self) -> bool {
202        &self.0.numerator * &other.0.denominator == &other.0.numerator * &self.0.denominator
203    }
204}
205
206impl ExactLength {
207    /// Retain canonical integer quanta without decoding a pixel projection.
208    pub(crate) fn quanta(value: LayoutScalar) -> Result<Self> {
209        let value =
210            u64::try_from(value.quanta()).map_err(|_| invalid("length must be nonnegative"))?;
211
212        Ok(Self(Rational {
213            numerator: BigUint::from(value),
214            denominator: BigUint::from(1_u8),
215        }))
216    }
217    /// Unrounded remainder; a negative remainder is unavailable capacity, not zero.
218    pub(crate) fn subtract(&self, other: &Self) -> Option<Self> {
219        let left = &self.0.numerator * &other.0.denominator;
220        let right = &other.0.numerator * &self.0.denominator;
221        if left < right {
222            return None;
223        }
224        Some(Self(Rational {
225            numerator: left - right,
226            denominator: &self.0.denominator * &other.0.denominator,
227        }))
228    }
229    pub(crate) fn before_pixels(&self, anchor: f64) -> Result<f64> {
230        scalar_pixels(self.before(anchor)?)
231    }
232    pub(crate) fn after_pixels(&self, anchor: f64) -> Result<f64> {
233        let value = self.before_pixels(-anchor)?;
234        Ok(if value == 0.0 { 0.0 } else { -value })
235    }
236    pub(crate) fn divided_by(&self, value: f64) -> Result<Self> {
237        if !value.is_finite() || value <= 0.0 {
238            return Err(invalid("length divisor must be finite and positive"));
239        }
240        let divisor = dyadic(value);
241
242        Ok(Self(Rational {
243            numerator: &self.0.numerator * divisor.denominator,
244            denominator: &self.0.denominator * divisor.numerator,
245        }))
246    }
247
248    pub(crate) fn pixels_rounded(&self, rounding: SpatialRounding) -> Result<f64> {
249        scalar_pixels(self.round(rounding)?)
250    }
251    /// Resolve a whole position, retaining anchor parity through half-quantum
252    /// ties instead of independently rounding the offset before subtraction.
253    pub(crate) fn before(&self, anchor: f64) -> Result<LayoutScalar> {
254        let origin = Self::pixels(anchor.abs())?;
255
256        let left = &origin.0.numerator * &self.0.denominator;
257        let right = &self.0.numerator * &origin.0.denominator;
258        let (negative, numerator) = if anchor.is_sign_negative() {
259            (true, left + right)
260        } else if left < right {
261            (true, right - left)
262        } else {
263            (false, left - right)
264        };
265        let value = Self(Rational {
266            numerator,
267            denominator: &origin.0.denominator * &self.0.denominator,
268        })
269        .round(SpatialRounding::NearestEven)?;
270        let quanta = if negative {
271            value
272                .quanta()
273                .checked_neg()
274                .ok_or_else(|| invalid("axis position overflow"))?
275        } else {
276            value.quanta()
277        };
278        Ok(LayoutScalar::from_quanta(quanta))
279    }
280    /// Exact nonnegative represented pixel ink/occupancy.
281    pub(crate) fn pixels(value: f64) -> Result<Self> {
282        validate(value)?;
283        let rational = dyadic(value);
284
285        Ok(Self(Rational {
286            numerator: rational.numerator << 10_usize,
287            denominator: rational.denominator,
288        }))
289    }
290
291    pub(crate) fn add_pixels(&self, value: f64) -> Result<Self> {
292        Ok(self.add_length(&Self::pixels(value)?))
293    }
294    pub(crate) fn add_length(&self, other: &Self) -> Self {
295        let numerator =
296            &self.0.numerator * &other.0.denominator + &other.0.numerator * &self.0.denominator;
297        let denominator = &self.0.denominator * &other.0.denominator;
298        Self(reduce(numerator, denominator))
299    }
300
301    pub(crate) fn times(&self, count: u32) -> Self {
302        Self(Rational {
303            numerator: &self.0.numerator * count,
304            denominator: self.0.denominator.clone(),
305        })
306    }
307
308    pub(crate) fn add_quanta(&self, value: LayoutScalar) -> Result<Self> {
309        let value =
310            u64::try_from(value.quanta()).map_err(|_| invalid("length must be nonnegative"))?;
311
312        Ok(Self(Rational {
313            numerator: &self.0.numerator + &self.0.denominator * value,
314            denominator: self.0.denominator.clone(),
315        }))
316    }
317
318    pub(crate) fn compare(&self, other: &Self) -> Ordering {
319        (&self.0.numerator * &other.0.denominator).cmp(&(&other.0.numerator * &self.0.denominator))
320    }
321
322    pub(crate) fn round(&self, rounding: SpatialRounding) -> Result<LayoutScalar> {
323        let quotient = &self.0.numerator / &self.0.denominator;
324        let remainder = &self.0.numerator % &self.0.denominator;
325        let mut digits = quotient.iter_u64_digits();
326        let value = digits.next().unwrap_or(0);
327        if digits.next().is_some() {
328            return Err(invalid("length exceeds layout quanta"));
329        }
330        let increment = match rounding {
331            SpatialRounding::Floor => false,
332            SpatialRounding::Ceil => remainder.bits() != 0,
333            SpatialRounding::NearestEven => {
334                match (&remainder << 1_usize).cmp(&self.0.denominator) {
335                    Ordering::Less => false,
336                    Ordering::Equal => value & 1 != 0,
337                    Ordering::Greater => true,
338                }
339            }
340        };
341        value
342            .checked_add(u64::from(increment))
343            .and_then(|value| i64::try_from(value).ok())
344            .map(LayoutScalar::from_quanta)
345            .ok_or_else(|| invalid("rounded length exceeds layout quanta"))
346    }
347}
348
349#[expect(
350    clippy::cast_precision_loss,
351    reason = "the checked quanta bound guarantees exact integer conversion"
352)]
353fn scalar_pixels(value: LayoutScalar) -> Result<f64> {
354    if value.quanta().unsigned_abs() > (1_u64 << 53) {
355        return Err(invalid("length cannot retain exact CSS quanta"));
356    }
357    Ok(value.quanta() as f64 / 1024.0)
358}
359
360fn validate(value: f64) -> Result<()> {
361    if value.is_finite() && value >= 0.0 {
362        Ok(())
363    } else {
364        Err(invalid("spacing must be finite and nonnegative"))
365    }
366}
367
368fn dyadic(value: f64) -> Rational {
369    let bits = value.to_bits();
370    let exponent = i32::try_from((bits >> 52) & 0x7ff).expect("11-bit exponent");
371    let fraction = bits & ((1_u64 << 52) - 1);
372    let (mut significand, mut shift) = if exponent == 0 {
373        (fraction, -1074)
374    } else {
375        (fraction | (1_u64 << 52), exponent - 1075)
376    };
377    if significand == 0 {
378        return Rational {
379            numerator: BigUint::from(0_u8),
380            denominator: BigUint::from(1_u8),
381        };
382    }
383    let zeros = significand.trailing_zeros();
384    significand >>= zeros;
385    shift += i32::try_from(zeros).expect("at most 53 bits");
386
387    let numerator = BigUint::from(significand);
388    let denominator = BigUint::from(1_u8);
389    if shift >= 0 {
390        Rational {
391            numerator: numerator << shift.unsigned_abs() as usize,
392            denominator,
393        }
394    } else {
395        Rational {
396            numerator,
397            denominator: denominator << shift.unsigned_abs() as usize,
398        }
399    }
400}
401
402fn reduce(numerator: BigUint, denominator: BigUint) -> Rational {
403    let (mut left, mut right) = (numerator.clone(), denominator.clone());
404    while right.bits() != 0 {
405        let remainder = &left % &right;
406        (left, right) = (right, remainder);
407    }
408
409    Rational {
410        numerator: numerator / &left,
411        denominator: denominator / &left,
412    }
413}
414
415fn invalid(message: &str) -> Error {
416    Error::Render(format!("relative spacing: {message}").into())
417}
418
419#[cfg(test)]
420mod tests {
421    use super::*;
422
423    fn resolved(value: &RelativeSpacing, pixels: u32, rounding: SpatialRounding) -> i64 {
424        value
425            .product(LocalMetric::css_pixels(f64::from(pixels)).unwrap())
426            .round(rounding)
427            .unwrap()
428            .quanta()
429    }
430
431    #[test]
432    fn finite_binary64_extremes_roundtrip_and_spatial_overflow_refuses() {
433        for bits in [
434            1,
435            0x000f_ffff_ffff_ffff,
436            0x0010_0000_0000_0000,
437            0x3fb9_9999_9999_999a,
438            0x7fef_ffff_ffff_ffff,
439        ] {
440            let value = RelativeSpacing::new(f64::from_bits(bits)).unwrap();
441            assert_eq!(value.as_f64().to_bits(), bits);
442        }
443        let tiny = RelativeSpacing::new(f64::from_bits(1)).unwrap();
444        assert_eq!(tiny.0.rational.numerator, BigUint::from(1_u8));
445        assert_eq!(tiny.0.rational.denominator.bits(), 1075);
446        assert_eq!(resolved(&tiny, u32::MAX, SpatialRounding::Floor), 0);
447        assert_eq!(resolved(&tiny, u32::MAX, SpatialRounding::NearestEven), 0);
448        assert_eq!(resolved(&tiny, u32::MAX, SpatialRounding::Ceil), 1);
449
450        let large = RelativeSpacing::new(f64::MAX)
451            .unwrap()
452            .product(LocalMetric::css_pixels(1.0).unwrap());
453        assert!(large.round(SpatialRounding::Ceil).is_err());
454        let maximum = RelativeSpacing::ratio(1, 1)
455            .unwrap()
456            .product(LocalMetric::scalar(LayoutScalar::from_quanta(i64::MAX)).unwrap());
457        assert_eq!(
458            maximum
459                .round(SpatialRounding::NearestEven)
460                .unwrap()
461                .quanta(),
462            i64::MAX
463        );
464        assert!(maximum
465            .add_quanta(LayoutScalar::from_quanta(1))
466            .unwrap()
467            .round(SpatialRounding::Floor)
468            .is_err());
469    }
470
471    #[test]
472    fn nearest_even_ties_floor_and_ceil_are_independent_boundaries() {
473        for (numerator, nearest, floor, ceil) in
474            [(1, 0, 0, 1), (3, 2, 1, 2), (5, 2, 2, 3), (7, 4, 3, 4)]
475        {
476            let value = RelativeSpacing::ratio(numerator, 2048).unwrap();
477            assert_eq!(resolved(&value, 1, SpatialRounding::NearestEven), nearest);
478            assert_eq!(resolved(&value, 1, SpatialRounding::Floor), floor);
479            assert_eq!(resolved(&value, 1, SpatialRounding::Ceil), ceil);
480        }
481    }
482
483    #[test]
484    fn exact_aggregate_retains_the_edge_inset_quantum_and_repeated_gap_sum() {
485        let em = LocalMetric::css_pixels(11.0).unwrap();
486        let padding = RelativeSpacing::from_pixels(8.8, 11).unwrap().product(em);
487        let comfort = RelativeSpacing::new(0.2).unwrap().product(em);
488        let edge = padding.add_length(&comfort);
489        assert_eq!(
490            edge.round(SpatialRounding::NearestEven).unwrap().quanta(),
491            11264
492        );
493        assert_eq!(edge.round(SpatialRounding::Ceil).unwrap().quanta(), 11265);
494        assert_eq!(
495            edge.times(2).round(SpatialRounding::Ceil).unwrap().quanta(),
496            22529
497        );
498        let gap = RelativeSpacing::ratio(1, 3072)
499            .unwrap()
500            .product(LocalMetric::css_pixels(1.0).unwrap());
501        assert_eq!(
502            gap.times(3)
503                .add_quanta(LayoutScalar::from_quanta(1024))
504                .unwrap()
505                .round(SpatialRounding::Ceil)
506                .unwrap()
507                .quanta(),
508            1025
509        );
510        assert_eq!(gap.compare(&edge), Ordering::Less);
511        assert!(gap.add_quanta(LayoutScalar::from_quanta(-1)).is_err());
512    }
513}