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 exact_parts(&self) -> (&BigUint, &BigUint) {
146        (&self.0.rational.numerator, &self.0.rational.denominator)
147    }
148
149    pub(crate) fn from_exact_parts(numerator: BigUint, denominator: BigUint) -> Result<Self> {
150        if denominator.bits() == 0 {
151            return Err(invalid("ratio denominator must be positive"));
152        }
153        let rational = reduce(numerator, denominator);
154        let approximate = crate::numeric::binary::signed_ratio(
155            num_bigint::BigInt::from(rational.numerator.clone()),
156            rational.denominator.clone(),
157        )?;
158        validate(approximate)?;
159        Ok(Self(Arc::new(SpacingPayload {
160            rational,
161            approximate,
162        })))
163    }
164
165    pub(crate) fn is_zero(&self) -> bool {
166        self.0.rational.numerator.bits() == 0
167    }
168
169    pub(crate) fn product(&self, metric: LocalMetric) -> ExactLength {
170        let rational = &self.0.rational;
171        let metric = match metric {
172            LocalMetric::CssPixels(bits) => {
173                let mut value = dyadic(f64::from_bits(bits));
174                value.numerator *= 1024_u16;
175                value
176            }
177            LocalMetric::Quanta(value) => Rational {
178                numerator: BigUint::from(value),
179                denominator: BigUint::from(1_u8),
180            },
181        };
182
183        ExactLength(Rational {
184            numerator: &rational.numerator * metric.numerator,
185            denominator: &rational.denominator * metric.denominator,
186        })
187    }
188}
189
190/// A declared positive role em/radius or canonical local span, never a root size.
191#[derive(Debug, Clone, Copy)]
192pub(crate) enum LocalMetric {
193    CssPixels(u64),
194    Quanta(u64),
195}
196
197impl LocalMetric {
198    pub(crate) fn css_pixels(value: f64) -> Result<Self> {
199        if !value.is_finite() || value <= 0.0 {
200            return Err(invalid("local metric must be finite and positive"));
201        }
202        Ok(Self::CssPixels(value.to_bits()))
203    }
204
205    pub(crate) fn scalar(value: LayoutScalar) -> Result<Self> {
206        match u64::try_from(value.quanta()) {
207            Ok(value) if value > 0 => Ok(Self::Quanta(value)),
208            _ => Err(invalid("local metric must be positive")),
209        }
210    }
211}
212
213/// Unrounded nonnegative quanta. Aggregate before selecting a spatial boundary.
214#[derive(Debug, Clone)]
215pub(crate) struct ExactLength(Rational);
216
217// Test oracles may compare independently measured exact consequences. Runtime
218// matching uses the exact compare method, not this trait.
219#[cfg(test)]
220impl PartialEq for ExactLength {
221    fn eq(&self, other: &Self) -> bool {
222        &self.0.numerator * &other.0.denominator == &other.0.numerator * &self.0.denominator
223    }
224}
225
226impl ExactLength {
227    /// Retain canonical integer quanta without decoding a pixel projection.
228    pub(crate) fn quanta(value: LayoutScalar) -> Result<Self> {
229        let value =
230            u64::try_from(value.quanta()).map_err(|_| invalid("length must be nonnegative"))?;
231
232        Ok(Self(Rational {
233            numerator: BigUint::from(value),
234            denominator: BigUint::from(1_u8),
235        }))
236    }
237    /// Unrounded remainder; a negative remainder is unavailable capacity, not zero.
238    pub(crate) fn subtract(&self, other: &Self) -> Option<Self> {
239        let left = &self.0.numerator * &other.0.denominator;
240        let right = &other.0.numerator * &self.0.denominator;
241        if left < right {
242            return None;
243        }
244        Some(Self(Rational {
245            numerator: left - right,
246            denominator: &self.0.denominator * &other.0.denominator,
247        }))
248    }
249    pub(crate) fn before_pixels(&self, anchor: f64) -> Result<f64> {
250        scalar_pixels(self.before(anchor)?)
251    }
252    pub(crate) fn after_pixels(&self, anchor: f64) -> Result<f64> {
253        let value = self.before_pixels(-anchor)?;
254        Ok(if value == 0.0 { 0.0 } else { -value })
255    }
256    pub(crate) fn divided_by(&self, value: f64) -> Result<Self> {
257        if !value.is_finite() || value <= 0.0 {
258            return Err(invalid("length divisor must be finite and positive"));
259        }
260        let divisor = dyadic(value);
261
262        Ok(Self(Rational {
263            numerator: &self.0.numerator * divisor.denominator,
264            denominator: &self.0.denominator * divisor.numerator,
265        }))
266    }
267
268    pub(crate) fn pixels_rounded(&self, rounding: SpatialRounding) -> Result<f64> {
269        scalar_pixels(self.round(rounding)?)
270    }
271    /// Resolve a whole position, retaining anchor parity through half-quantum
272    /// ties instead of independently rounding the offset before subtraction.
273    pub(crate) fn before(&self, anchor: f64) -> Result<LayoutScalar> {
274        let origin = Self::pixels(anchor.abs())?;
275
276        let left = &origin.0.numerator * &self.0.denominator;
277        let right = &self.0.numerator * &origin.0.denominator;
278        let (negative, numerator) = if anchor.is_sign_negative() {
279            (true, left + right)
280        } else if left < right {
281            (true, right - left)
282        } else {
283            (false, left - right)
284        };
285        let value = Self(Rational {
286            numerator,
287            denominator: &origin.0.denominator * &self.0.denominator,
288        })
289        .round(SpatialRounding::NearestEven)?;
290        let quanta = if negative {
291            value
292                .quanta()
293                .checked_neg()
294                .ok_or_else(|| invalid("axis position overflow"))?
295        } else {
296            value.quanta()
297        };
298        Ok(LayoutScalar::from_quanta(quanta))
299    }
300    /// Exact nonnegative represented pixel ink/occupancy.
301    pub(crate) fn pixels(value: f64) -> Result<Self> {
302        validate(value)?;
303        let rational = dyadic(value);
304
305        Ok(Self(Rational {
306            numerator: rational.numerator << 10_usize,
307            denominator: rational.denominator,
308        }))
309    }
310
311    pub(crate) fn add_pixels(&self, value: f64) -> Result<Self> {
312        Ok(self.add_length(&Self::pixels(value)?))
313    }
314    pub(crate) fn add_length(&self, other: &Self) -> Self {
315        let numerator =
316            &self.0.numerator * &other.0.denominator + &other.0.numerator * &self.0.denominator;
317        let denominator = &self.0.denominator * &other.0.denominator;
318        Self(reduce(numerator, denominator))
319    }
320
321    pub(crate) fn times(&self, count: u32) -> Self {
322        Self(Rational {
323            numerator: &self.0.numerator * count,
324            denominator: self.0.denominator.clone(),
325        })
326    }
327
328    pub(crate) fn add_quanta(&self, value: LayoutScalar) -> Result<Self> {
329        let value =
330            u64::try_from(value.quanta()).map_err(|_| invalid("length must be nonnegative"))?;
331
332        Ok(Self(Rational {
333            numerator: &self.0.numerator + &self.0.denominator * value,
334            denominator: self.0.denominator.clone(),
335        }))
336    }
337
338    pub(crate) fn compare(&self, other: &Self) -> Ordering {
339        (&self.0.numerator * &other.0.denominator).cmp(&(&other.0.numerator * &self.0.denominator))
340    }
341
342    pub(crate) fn round(&self, rounding: SpatialRounding) -> Result<LayoutScalar> {
343        let quotient = &self.0.numerator / &self.0.denominator;
344        let remainder = &self.0.numerator % &self.0.denominator;
345        let mut digits = quotient.iter_u64_digits();
346        let value = digits.next().unwrap_or(0);
347        if digits.next().is_some() {
348            return Err(invalid("length exceeds layout quanta"));
349        }
350        let increment = match rounding {
351            SpatialRounding::Floor => false,
352            SpatialRounding::Ceil => remainder.bits() != 0,
353            SpatialRounding::NearestEven => {
354                match (&remainder << 1_usize).cmp(&self.0.denominator) {
355                    Ordering::Less => false,
356                    Ordering::Equal => value & 1 != 0,
357                    Ordering::Greater => true,
358                }
359            }
360        };
361        value
362            .checked_add(u64::from(increment))
363            .and_then(|value| i64::try_from(value).ok())
364            .map(LayoutScalar::from_quanta)
365            .ok_or_else(|| invalid("rounded length exceeds layout quanta"))
366    }
367}
368
369#[expect(
370    clippy::cast_precision_loss,
371    reason = "the checked quanta bound guarantees exact integer conversion"
372)]
373fn scalar_pixels(value: LayoutScalar) -> Result<f64> {
374    if value.quanta().unsigned_abs() > (1_u64 << 53) {
375        return Err(invalid("length cannot retain exact CSS quanta"));
376    }
377    Ok(value.quanta() as f64 / 1024.0)
378}
379
380fn validate(value: f64) -> Result<()> {
381    if value.is_finite() && value >= 0.0 {
382        Ok(())
383    } else {
384        Err(invalid("spacing must be finite and nonnegative"))
385    }
386}
387
388fn dyadic(value: f64) -> Rational {
389    let bits = value.to_bits();
390    let exponent = i32::try_from((bits >> 52) & 0x7ff).expect("11-bit exponent");
391    let fraction = bits & ((1_u64 << 52) - 1);
392    let (mut significand, mut shift) = if exponent == 0 {
393        (fraction, -1074)
394    } else {
395        (fraction | (1_u64 << 52), exponent - 1075)
396    };
397    if significand == 0 {
398        return Rational {
399            numerator: BigUint::from(0_u8),
400            denominator: BigUint::from(1_u8),
401        };
402    }
403    let zeros = significand.trailing_zeros();
404    significand >>= zeros;
405    shift += i32::try_from(zeros).expect("at most 53 bits");
406
407    let numerator = BigUint::from(significand);
408    let denominator = BigUint::from(1_u8);
409    if shift >= 0 {
410        Rational {
411            numerator: numerator << shift.unsigned_abs() as usize,
412            denominator,
413        }
414    } else {
415        Rational {
416            numerator,
417            denominator: denominator << shift.unsigned_abs() as usize,
418        }
419    }
420}
421
422fn reduce(numerator: BigUint, denominator: BigUint) -> Rational {
423    let (mut left, mut right) = (numerator.clone(), denominator.clone());
424    while right.bits() != 0 {
425        let remainder = &left % &right;
426        (left, right) = (right, remainder);
427    }
428
429    Rational {
430        numerator: numerator / &left,
431        denominator: denominator / &left,
432    }
433}
434
435fn invalid(message: &str) -> Error {
436    Error::Render(format!("relative spacing: {message}").into())
437}
438
439#[cfg(test)]
440mod tests {
441    use super::*;
442
443    fn resolved(value: &RelativeSpacing, pixels: u32, rounding: SpatialRounding) -> i64 {
444        value
445            .product(LocalMetric::css_pixels(f64::from(pixels)).unwrap())
446            .round(rounding)
447            .unwrap()
448            .quanta()
449    }
450
451    #[test]
452    fn finite_binary64_extremes_roundtrip_and_spatial_overflow_refuses() {
453        for bits in [
454            1,
455            0x000f_ffff_ffff_ffff,
456            0x0010_0000_0000_0000,
457            0x3fb9_9999_9999_999a,
458            0x7fef_ffff_ffff_ffff,
459        ] {
460            let value = RelativeSpacing::new(f64::from_bits(bits)).unwrap();
461            assert_eq!(value.as_f64().to_bits(), bits);
462        }
463        let tiny = RelativeSpacing::new(f64::from_bits(1)).unwrap();
464        assert_eq!(tiny.0.rational.numerator, BigUint::from(1_u8));
465        assert_eq!(tiny.0.rational.denominator.bits(), 1075);
466        assert_eq!(resolved(&tiny, u32::MAX, SpatialRounding::Floor), 0);
467        assert_eq!(resolved(&tiny, u32::MAX, SpatialRounding::NearestEven), 0);
468        assert_eq!(resolved(&tiny, u32::MAX, SpatialRounding::Ceil), 1);
469
470        let large = RelativeSpacing::new(f64::MAX)
471            .unwrap()
472            .product(LocalMetric::css_pixels(1.0).unwrap());
473        assert!(large.round(SpatialRounding::Ceil).is_err());
474        let maximum = RelativeSpacing::ratio(1, 1)
475            .unwrap()
476            .product(LocalMetric::scalar(LayoutScalar::from_quanta(i64::MAX)).unwrap());
477        assert_eq!(
478            maximum
479                .round(SpatialRounding::NearestEven)
480                .unwrap()
481                .quanta(),
482            i64::MAX
483        );
484        assert!(maximum
485            .add_quanta(LayoutScalar::from_quanta(1))
486            .unwrap()
487            .round(SpatialRounding::Floor)
488            .is_err());
489    }
490
491    #[test]
492    fn nearest_even_ties_floor_and_ceil_are_independent_boundaries() {
493        for (numerator, nearest, floor, ceil) in
494            [(1, 0, 0, 1), (3, 2, 1, 2), (5, 2, 2, 3), (7, 4, 3, 4)]
495        {
496            let value = RelativeSpacing::ratio(numerator, 2048).unwrap();
497            assert_eq!(resolved(&value, 1, SpatialRounding::NearestEven), nearest);
498            assert_eq!(resolved(&value, 1, SpatialRounding::Floor), floor);
499            assert_eq!(resolved(&value, 1, SpatialRounding::Ceil), ceil);
500        }
501    }
502
503    #[test]
504    fn exact_aggregate_retains_the_edge_inset_quantum_and_repeated_gap_sum() {
505        let em = LocalMetric::css_pixels(11.0).unwrap();
506        let padding = RelativeSpacing::from_pixels(8.8, 11).unwrap().product(em);
507        let comfort = RelativeSpacing::new(0.2).unwrap().product(em);
508        let edge = padding.add_length(&comfort);
509        assert_eq!(
510            edge.round(SpatialRounding::NearestEven).unwrap().quanta(),
511            11264
512        );
513        assert_eq!(edge.round(SpatialRounding::Ceil).unwrap().quanta(), 11265);
514        assert_eq!(
515            edge.times(2).round(SpatialRounding::Ceil).unwrap().quanta(),
516            22529
517        );
518        let gap = RelativeSpacing::ratio(1, 3072)
519            .unwrap()
520            .product(LocalMetric::css_pixels(1.0).unwrap());
521        assert_eq!(
522            gap.times(3)
523                .add_quanta(LayoutScalar::from_quanta(1024))
524                .unwrap()
525                .round(SpatialRounding::Ceil)
526                .unwrap()
527                .quanta(),
528            1025
529        );
530        assert_eq!(gap.compare(&edge), Ordering::Less);
531        assert!(gap.add_quanta(LayoutScalar::from_quanta(-1)).is_err());
532    }
533}