Skip to main content

flm_core/stdlib/backends/pres/
length.rs

1//! The length value of the presentation vocabulary: an exact amount and a
2//! unit, which is how a payload states a dimension.
3//!
4//! A **length** ([`Length`]) is what a payload carries wherever it states a
5//! distance or a width: the indentation of a line of a `flm.pres.lines` node
6//! ([`LinePayload`](super::LinePayload)), the size an image is shown at
7//! ([`ImagePayload`](super::ImagePayload)). It is never a bare number: a bare
8//! number would leave each backend to guess what it counts, and a count of
9//! columns or of indentation steps is too coarse to express what an author
10//! means. A length is written, parsed and projected as its decimal amount
11//! followed directly by its unit, with no space: `1tab`, `2tab`, `1.5em`,
12//! `10pt`, `0.25in`, `3mm`.
13//!
14//! # The amount is exact
15//!
16//! The amount is a fixed-point number with sixteen fractional bits
17//! ([`I48F16`], from the `fixed` crate), the model TeX uses for its own
18//! dimensions: one unit of the fraction is one *scaled point*, 1/65536 of the
19//! unit. It is exact rather than a floating-point number so that two payloads
20//! holding the same length compare equal and hash alike, and so that the
21//! output written from a length is byte-identical on every platform and every
22//! run. A decimal amount that is not a whole number of scaled points, such as
23//! `0.1`, is rounded to the nearest scaled point when it is parsed, and
24//! projected as the shortest decimal that parses back to the same amount.
25//!
26//! # The units
27//!
28//! The units form a closed set ([`LengthUnit`]):
29//!
30//! - `tab` — a **tab**, the unit each backend sets the width of through one
31//!   setting of its own (the text backend's render option `tab_width`, for
32//!   instance). A line indented by `\indent` is indented by one tab.
33//! - `em` — the width of an em in the current font.
34//! - `pt` — a **point**, 1/72 inch: the point of CSS and of PostScript. It is
35//!   the only point this vocabulary has; LaTeX writes this unit `bp` (a "big
36//!   point"), and TeX's own point of 1/72.27 inch has no unit here.
37//! - `mm`, `cm`, `in` — millimeters, centimeters and inches.
38//!
39//! The set is closed so that every backend can write every length: a unit a
40//! backend did not support would need a second way of writing the length. A
41//! unit added later changes no projection already written, since each length
42//! writes its own unit.
43//!
44//! # Conversion among the physical units
45//!
46//! Four of the units have a fixed size — `pt`, `mm`, `cm` and `in`, the
47//! **physical units** ([`LengthUnit::is_physical`]) — and a length in one of
48//! them converts to any other of them: [`Length::convert_to`] writes a length
49//! in another unit, [`Length::scaled`] multiplies a length by the ratio of two
50//! others (how an image given one dimension gets the other while keeping its
51//! proportions), [`Length::from_dots`] gives the size of a number of dots
52//! printed at a resolution, and [`Length::times`] multiplies a length by a
53//! factor (how an image is magnified for one output; any unit, kept). Each computes its result exactly, as a fraction,
54//! and rounds it **once**, at the end, to the nearest scaled point of the
55//! result's unit, a half rounded away from zero; the four units' sizes are
56//! whole multiples of 1/9144 inch (a point is 127 of them, a millimeter 360),
57//! so no size is itself rounded. A tab and an em have no fixed size and
58//! convert to nothing: a conversion involving one is refused with a
59//! [`LengthConversionError`], as is a result too large to hold.
60
61use std::fmt;
62
63pub use fixed::types::I48F16;
64
65/// The unit of a [`Length`]: one of a closed set, spelled `tab`, `em`, `pt`,
66/// `mm`, `cm` and `in` ([`LengthUnit::as_str`]).
67///
68/// See the [module documentation](self) for what each unit measures, the
69/// point in particular; in short, a tab is the unit each backend sets the
70/// width of.
71#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
72pub enum LengthUnit {
73    /// A tab, `tab`: the width each backend sets through one setting of its
74    /// own.
75    Tabs,
76    /// An em, `em`: the width of an em in the current font.
77    Ems,
78    /// A point, `pt` (see the [module documentation](self)).
79    Points,
80    /// A millimeter, `mm`.
81    Millimeters,
82    /// A centimeter, `cm`.
83    Centimeters,
84    /// An inch, `in`.
85    Inches,
86}
87
88impl LengthUnit {
89    /// Every unit, in declaration order.
90    pub const ALL: [LengthUnit; 6] = [
91        LengthUnit::Tabs,
92        LengthUnit::Ems,
93        LengthUnit::Points,
94        LengthUnit::Millimeters,
95        LengthUnit::Centimeters,
96        LengthUnit::Inches,
97    ];
98
99    /// The unit's stable name, as a length is written and projected: `tab`,
100    /// `em`, `pt`, `mm`, `cm` or `in`.
101    pub fn as_str(self) -> &'static str {
102        match self {
103            LengthUnit::Tabs => "tab",
104            LengthUnit::Ems => "em",
105            LengthUnit::Points => "pt",
106            LengthUnit::Millimeters => "mm",
107            LengthUnit::Centimeters => "cm",
108            LengthUnit::Inches => "in",
109        }
110    }
111
112    /// The unit of a stable name, if any.
113    pub fn parse(name: &str) -> Option<LengthUnit> {
114        LengthUnit::ALL.into_iter().find(|unit| unit.as_str() == name)
115    }
116
117    /// Whether the unit has a fixed size — `pt`, `mm`, `cm` or `in`, the
118    /// units a length converts among (see the
119    /// [module documentation](self#conversion-among-the-physical-units)).
120    /// A tab and an em are not physical.
121    pub fn is_physical(self) -> bool {
122        self.size().is_some()
123    }
124
125    /// The unit's size in 1/9144 inch, the largest length of which all four
126    /// physical units are whole multiples (72 × 127 = 9144 = 25.4 × 360);
127    /// `None` for a unit with no fixed size.
128    fn size(self) -> Option<i128> {
129        match self {
130            LengthUnit::Tabs | LengthUnit::Ems => None,
131            LengthUnit::Points => Some(127),
132            LengthUnit::Millimeters => Some(360),
133            LengthUnit::Centimeters => Some(3600),
134            LengthUnit::Inches => Some(9144),
135        }
136    }
137}
138
139impl fmt::Display for LengthUnit {
140    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
141        f.write_str(self.as_str())
142    }
143}
144
145/// A dimension: an exact amount of a [`LengthUnit`].
146///
147/// A length is written and projected as its decimal amount followed directly
148/// by its unit — `1tab`, `1.5em`, `10pt` — through its `Display`, and read
149/// back from that text by [`Length::parse`]. Two equal lengths compare equal
150/// and hash alike; a length is never ordered against another, since `1in` and
151/// `2pt` have no order a derived comparison would get right. The default is
152/// the zero length, `0tab`.
153///
154/// See the [module documentation](self) for why the amount is exact and what
155/// each unit measures.
156///
157/// # Examples
158///
159/// ```
160/// use flm_core::stdlib::backends::pres::{Length, LengthUnit};
161///
162/// let indent = Length::parse("1.5em")?;
163/// assert_eq!(indent.unit, LengthUnit::Ems);
164/// assert_eq!(indent.to_string(), "1.5em");
165/// assert_eq!(Length::tabs(2).to_string(), "2tab");
166/// assert!(Length::parse("1.5").is_err());
167/// # Ok::<(), flm_core::stdlib::backends::pres::LengthError>(())
168/// ```
169#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
170pub struct Length {
171    /// The amount, exact to one scaled point (1/65536 of the unit).
172    pub amount: I48F16,
173    /// The unit the amount counts.
174    pub unit: LengthUnit,
175}
176
177impl Default for Length {
178    fn default() -> Length {
179        Length::tabs(0)
180    }
181}
182
183impl Length {
184    /// The length of `amount` units of `unit`.
185    pub fn new(amount: I48F16, unit: LengthUnit) -> Length {
186        Length { amount, unit }
187    }
188
189    /// A whole number of tabs: `count` units of [`LengthUnit::Tabs`], how a
190    /// line indented by `count` `\indent` commands is indented.
191    pub fn tabs(count: i32) -> Length {
192        // A 32-bit count shifted by the sixteen fractional bits fits the
193        // amount's 64 bits, so the amount is exact.
194        Length::new(I48F16::from_bits(i64::from(count) << I48F16::FRAC_NBITS), LengthUnit::Tabs)
195    }
196
197    /// Whether the amount is zero, regardless of the unit.
198    pub fn is_zero(&self) -> bool {
199        self.amount == I48F16::ZERO
200    }
201
202    /// The length written as `text`: a decimal amount followed directly by a
203    /// unit's stable name, such as `1tab`, `1.5em`, `-2pt` or `.5in`.
204    ///
205    /// The amount is an optional sign, digits, and optionally a full stop
206    /// followed by digits, with at least one digit in all; it is rounded to
207    /// the nearest scaled point (1/65536 of the unit). No space may be written
208    /// between the amount and the unit, nor around the length.
209    ///
210    /// # Errors
211    ///
212    /// A [`LengthError`] saying what is wrong: an empty text, a text with no
213    /// unit (`1.5`), an unknown unit (`2xx`), no amount before the unit
214    /// (`pt`), an amount that is not a decimal number (`1.2.3pt`, `1e3pt`),
215    /// or an amount too large to hold.
216    pub fn parse(text: &str) -> Result<Length, LengthError> {
217        if text.is_empty() {
218            return Err(LengthError::Empty);
219        }
220        let amount_end = text.trim_end_matches(|ch: char| ch.is_ascii_alphabetic()).len();
221        let (amount, unit) = text.split_at(amount_end);
222        if unit.is_empty() {
223            return Err(LengthError::NoUnit { text: text.to_string() });
224        }
225        let unit = LengthUnit::parse(unit)
226            .ok_or_else(|| LengthError::UnknownUnit { unit: unit.to_string() })?;
227        if amount.is_empty() {
228            return Err(LengthError::NoAmount { text: text.to_string() });
229        }
230        if !is_decimal(amount) {
231            return Err(LengthError::BadAmount { text: text.to_string(), amount: amount.to_string() });
232        }
233        let value: I48F16 = amount
234            .parse()
235            .map_err(|_| LengthError::Overflow { text: text.to_string(), amount: amount.to_string() })?;
236        Ok(Length::new(value, unit))
237    }
238}
239
240/// Whether `text` is an optional sign followed by digits with at most one
241/// full stop among them, holding at least one digit: the only form of amount
242/// [`Length::parse`] accepts. The `fixed` crate's own reader admits more (an
243/// exponent, underscores), which a written length does not.
244fn is_decimal(text: &str) -> bool {
245    let digits = text.strip_prefix(['+', '-']).unwrap_or(text);
246    let (whole, fraction) = digits.split_once('.').unwrap_or((digits, ""));
247    let all_digits = |part: &str| part.bytes().all(|byte| byte.is_ascii_digit());
248    !(whole.is_empty() && fraction.is_empty()) && all_digits(whole) && all_digits(fraction)
249}
250
251impl Length {
252    /// The same length written in `unit`: `2.54cm` in inches is `1in`.
253    ///
254    /// The conversion is exact but for one rounding of the result to the
255    /// nearest scaled point of `unit`, a half rounded away from zero (see the
256    /// [module documentation](self#conversion-among-the-physical-units)).
257    ///
258    /// # Errors
259    ///
260    /// [`LengthConversionError::NotPhysical`] where the length's unit or
261    /// `unit` is a tab or an em, and [`LengthConversionError::Overflow`]
262    /// where the result is too large to hold.
263    ///
264    /// # Examples
265    ///
266    /// ```
267    /// use flm_core::stdlib::backends::pres::{Length, LengthUnit};
268    ///
269    /// let inch = Length::parse("2.54cm")?.convert_to(LengthUnit::Inches)?;
270    /// assert_eq!(inch.to_string(), "1in");
271    /// assert!(Length::parse("1em")?.convert_to(LengthUnit::Points).is_err());
272    /// # Ok::<(), Box<dyn std::error::Error>>(())
273    /// ```
274    pub fn convert_to(&self, unit: LengthUnit) -> Result<Length, LengthConversionError> {
275        let from = physical_size(self.unit)?;
276        let to = physical_size(unit)?;
277        let bits = divide_rounded(i128::from(self.amount.to_bits()) * from, to)?;
278        Ok(Length::new(I48F16::from_bits(bits), unit))
279    }
280
281    /// This length multiplied by the ratio `numerator ÷ denominator` of two
282    /// lengths, written in `unit`.
283    ///
284    /// This is how one dimension of a picture follows from the other while
285    /// keeping its proportions: a picture 340pt wide and 170pt high shown
286    /// 5cm wide is `170pt` scaled by `5cm ÷ 340pt`, written in `cm`, a height
287    /// of `2.5cm`. The three lengths may be in any physical units; the result
288    /// is computed exactly and rounded once, to the nearest scaled point of
289    /// `unit`, a half rounded away from zero.
290    ///
291    /// # Errors
292    ///
293    /// [`LengthConversionError::NotPhysical`] where any of the three lengths
294    /// or `unit` is a tab or an em; [`LengthConversionError::ZeroDenominator`]
295    /// where `denominator` is zero; [`LengthConversionError::Overflow`] where
296    /// the result is too large to hold.
297    ///
298    /// # Examples
299    ///
300    /// ```
301    /// use flm_core::stdlib::backends::pres::{Length, LengthUnit};
302    ///
303    /// let height = Length::parse("170pt")?;
304    /// let given_width = Length::parse("5cm")?;
305    /// let width = Length::parse("340pt")?;
306    /// let shown = height.scaled(&given_width, &width, given_width.unit)?;
307    /// assert_eq!(shown.to_string(), "2.5cm");
308    /// # Ok::<(), Box<dyn std::error::Error>>(())
309    /// ```
310    pub fn scaled(
311        &self,
312        numerator: &Length,
313        denominator: &Length,
314        unit: LengthUnit,
315    ) -> Result<Length, LengthConversionError> {
316        let value = i128::from(self.amount.to_bits()) * physical_size(self.unit)?;
317        let numerator =
318            i128::from(numerator.amount.to_bits()) * physical_size(numerator.unit)?;
319        let denominator =
320            i128::from(denominator.amount.to_bits()) * physical_size(denominator.unit)?;
321        let to = physical_size(unit)?;
322        if denominator == 0 {
323            return Err(LengthConversionError::ZeroDenominator);
324        }
325        // value × numerator overflows 128 bits only for amounts near 2^47
326        // units; checked, and reported as a result too large to hold.
327        let product = value.checked_mul(numerator).ok_or(LengthConversionError::Overflow)?;
328        let divisor = denominator.checked_mul(to).ok_or(LengthConversionError::Overflow)?;
329        let bits = divide_rounded(product, divisor)?;
330        Ok(Length::new(I48F16::from_bits(bits), unit))
331    }
332
333    /// This length multiplied by `factor`, in the same unit.
334    ///
335    /// This is how an image is magnified for one output. The product is
336    /// computed exactly and rounded once, to the nearest scaled point of the
337    /// unit, a half rounded away from zero. Any unit is accepted, since the
338    /// unit does not change.
339    ///
340    /// # Errors
341    ///
342    /// [`LengthConversionError::Overflow`] where the result is too large to
343    /// hold.
344    ///
345    /// # Examples
346    ///
347    /// ```
348    /// use flm_core::stdlib::backends::pres::{I48F16, Length};
349    ///
350    /// let width = Length::parse("4cm")?;
351    /// assert_eq!(width.times(I48F16::from_num(1.25))?.to_string(), "5cm");
352    /// # Ok::<(), Box<dyn std::error::Error>>(())
353    /// ```
354    pub fn times(&self, factor: I48F16) -> Result<Length, LengthConversionError> {
355        let product = i128::from(self.amount.to_bits()) * i128::from(factor.to_bits());
356        let bits = divide_rounded(product, 1_i128 << I48F16::FRAC_NBITS)?;
357        Ok(Length::new(I48F16::from_bits(bits), self.unit))
358    }
359
360    /// The size, in points, of `dots` dots printed at `dots_per_inch` dots
361    /// per inch: `dots × 72 ÷ dots_per_inch` points, a point being 1/72 inch.
362    ///
363    /// This is the physical size of a picture of `dots` pixels at a stated
364    /// resolution. It is computed exactly and rounded once, to the nearest
365    /// scaled point (1/65536 pt), a half rounded away from zero.
366    ///
367    /// # Errors
368    ///
369    /// [`LengthConversionError::ZeroDenominator`] where `dots_per_inch` is
370    /// zero, [`LengthConversionError::Overflow`] where the result is too
371    /// large to hold. A negative resolution gives a negative length.
372    ///
373    /// # Examples
374    ///
375    /// ```
376    /// use flm_core::stdlib::backends::pres::{I48F16, Length};
377    ///
378    /// assert_eq!(Length::from_dots(300, I48F16::from_num(150))?.to_string(), "144pt");
379    /// # Ok::<(), Box<dyn std::error::Error>>(())
380    /// ```
381    pub fn from_dots(dots: u64, dots_per_inch: I48F16) -> Result<Length, LengthConversionError> {
382        let resolution = i128::from(dots_per_inch.to_bits());
383        if resolution == 0 {
384            return Err(LengthConversionError::ZeroDenominator);
385        }
386        // dots × 72 points, as scaled points, over the resolution's own
387        // scaled count: the two scalings of the resolution cancel once the
388        // numerator carries one more.
389        let unit = 1_i128 << I48F16::FRAC_NBITS;
390        let numerator = i128::from(dots) * 72 * unit * unit;
391        let bits = divide_rounded(numerator, resolution)?;
392        Ok(Length::new(I48F16::from_bits(bits), LengthUnit::Points))
393    }
394
395    /// The amount alone, in the decimal a length is projected with — the
396    /// shortest that reads back to the same amount (`2`, `1.5`, `-0.25`) —
397    /// for a backend that writes the unit its own way: the page writes a tab
398    /// as a multiple of a custom property, LaTeX a point as `bp`.
399    pub(crate) fn amount_decimal(&self) -> String {
400        decimal(self.amount)
401    }
402}
403
404impl fmt::Display for Length {
405    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
406        write!(f, "{}{}", self.amount_decimal(), self.unit)
407    }
408}
409
410/// The shortest decimal that [`Length::parse`] reads back to `amount`: the
411/// whole part, then as few fractional digits as that takes, none for a whole
412/// number, a minus sign before a negative amount.
413///
414/// The `fixed` crate's own printing is not used: it prints the shortest
415/// decimal nearer to the amount than to its neighbors, which does not always
416/// read back to it (`0.1` for 6553 scaled points, which reads as 6554).
417fn decimal(amount: I48F16) -> String {
418    let bits = i128::from(amount.to_bits());
419    let magnitude = bits.unsigned_abs();
420    let unit = 1_u128 << I48F16::FRAC_NBITS;
421    let (whole, fraction) = (magnitude / unit, magnitude % unit);
422    let sign = if bits < 0 { "-" } else { "" };
423    // Sixteen fractional bits need at most sixteen decimal digits to be
424    // written exactly, so the loop always ends by returning.
425    for digits in 0..=I48F16::FRAC_NBITS {
426        let scale = 10_u128.pow(digits);
427        // The fraction rounded to `digits` digits, a half rounded up.
428        let rounded = (2 * fraction * scale + unit) / (2 * unit);
429        let (whole, rounded) = if rounded == scale { (whole + 1, 0) } else { (whole, rounded) };
430        let text = if digits == 0 {
431            format!("{sign}{whole}")
432        } else {
433            format!("{sign}{whole}.{rounded:0width$}", width = digits as usize)
434        };
435        // The first number of digits that reads back ends in no zero: the
436        // same text without it would have read back one digit earlier.
437        if text.parse::<I48F16>() == Ok(amount) {
438            return text;
439        }
440    }
441    format!("{amount}")
442}
443
444/// The size of a physical unit in 1/9144 inch, or the refusal of a unit
445/// with no fixed size.
446fn physical_size(unit: LengthUnit) -> Result<i128, LengthConversionError> {
447    unit.size().ok_or(LengthConversionError::NotPhysical { unit })
448}
449
450/// `numerator ÷ denominator` rounded to the nearest whole number, a half
451/// rounded away from zero, as the bits of an amount; the only rounding of
452/// every conversion. `denominator` is not zero.
453fn divide_rounded(numerator: i128, denominator: i128) -> Result<i64, LengthConversionError> {
454    let (numerator, denominator) =
455        if denominator < 0 { (-numerator, -denominator) } else { (numerator, denominator) };
456    let magnitude = numerator.unsigned_abs();
457    let denominator = denominator.unsigned_abs();
458    let rounded = (magnitude / denominator) + u128::from(2 * (magnitude % denominator) >= denominator);
459    let rounded = i128::try_from(rounded).map_err(|_| LengthConversionError::Overflow)?;
460    let rounded = if numerator < 0 { -rounded } else { rounded };
461    i64::try_from(rounded).map_err(|_| LengthConversionError::Overflow)
462}
463
464/// Why a length does not convert: the error [`Length::convert_to`],
465/// [`Length::scaled`], [`Length::from_dots`] and [`Length::times`] return
466/// when they refuse.
467#[derive(Debug, Clone, Copy, PartialEq, Eq)]
468pub enum LengthConversionError {
469    /// A length or the requested unit is a tab or an em, which has no fixed
470    /// size and converts to no other unit.
471    NotPhysical {
472        /// The unit with no fixed size.
473        unit: LengthUnit,
474    },
475    /// The ratio's denominator, or the resolution, is zero.
476    ZeroDenominator,
477    /// The result is too large to hold.
478    Overflow,
479}
480
481impl fmt::Display for LengthConversionError {
482    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
483        match self {
484            LengthConversionError::NotPhysical { unit } => write!(
485                f,
486                "a length in `{unit}` has no fixed size and cannot be converted to another unit"
487            ),
488            LengthConversionError::ZeroDenominator => {
489                f.write_str("a length cannot be divided by zero")
490            }
491            LengthConversionError::Overflow => f.write_str("the converted length is too large"),
492        }
493    }
494}
495
496impl std::error::Error for LengthConversionError {}
497
498/// Why a text is not a [`Length`]: the error [`Length::parse`] returns when
499/// it refuses the text.
500#[derive(Debug, Clone, PartialEq, Eq)]
501pub enum LengthError {
502    /// The text is empty.
503    Empty,
504    /// The text ends in no unit, as `1.5` does.
505    NoUnit {
506        /// The text as written.
507        text: String,
508    },
509    /// The text ends in letters that are no unit, as `2xx` does.
510    UnknownUnit {
511        /// The letters at the end of the text.
512        unit: String,
513    },
514    /// No amount is written before the unit, as in `pt`.
515    NoAmount {
516        /// The text as written.
517        text: String,
518    },
519    /// The text before the unit is not a decimal number.
520    BadAmount {
521        /// The text as written.
522        text: String,
523        /// The amount as written.
524        amount: String,
525    },
526    /// The amount is too large to hold.
527    Overflow {
528        /// The text as written.
529        text: String,
530        /// The amount as written.
531        amount: String,
532    },
533}
534
535impl fmt::Display for LengthError {
536    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
537        let units = || LengthUnit::ALL.map(LengthUnit::as_str).join(", ");
538        match self {
539            LengthError::Empty => f.write_str("a length cannot be empty"),
540            LengthError::NoUnit { text } => {
541                write!(f, "the length `{text}` has no unit; write one of {}", units())
542            }
543            LengthError::UnknownUnit { unit } => {
544                write!(f, "`{unit}` is not a unit of length; write one of {}", units())
545            }
546            LengthError::NoAmount { text } => {
547                write!(f, "the length `{text}` must begin with an amount, a decimal number")
548            }
549            LengthError::BadAmount { text, amount } => {
550                write!(
551                    f,
552                    "the length `{text}` must begin with a decimal number, such as `2`, `-0.5` \
553                     or `1.25`, but its amount `{amount}` is not one"
554                )
555            }
556            LengthError::Overflow { text, amount } => {
557                write!(f, "the amount `{amount}` of the length `{text}` is too large")
558            }
559        }
560    }
561}
562
563impl std::error::Error for LengthError {}
564
565#[cfg(test)]
566mod tests {
567    use std::collections::hash_map::DefaultHasher;
568    use std::hash::{Hash, Hasher};
569
570    use super::*;
571
572    fn hash_of(length: &Length) -> u64 {
573        let mut hasher = DefaultHasher::new();
574        length.hash(&mut hasher);
575        hasher.finish()
576    }
577
578    #[test]
579    fn a_length_parses_and_projects_back_unchanged() {
580        for (text, unit) in [
581            ("1tab", LengthUnit::Tabs),
582            ("2tab", LengthUnit::Tabs),
583            ("1.5em", LengthUnit::Ems),
584            ("10pt", LengthUnit::Points),
585            ("0.25in", LengthUnit::Inches),
586            ("3mm", LengthUnit::Millimeters),
587            ("2.54cm", LengthUnit::Centimeters),
588            ("-2pt", LengthUnit::Points),
589            ("0.1em", LengthUnit::Ems),
590        ] {
591            let length = Length::parse(text).unwrap_or_else(|error| panic!("{text}: {error}"));
592            assert_eq!(length.unit, unit, "{text}");
593            assert_eq!(length.to_string(), text);
594            assert_eq!(Length::parse(&length.to_string()), Ok(length), "{text}");
595        }
596    }
597
598    #[test]
599    fn an_amount_is_rounded_to_a_scaled_point_and_projected_shortest() {
600        let length = Length::parse("1.50em").expect("a length");
601        assert_eq!(length.amount, I48F16::from_bits(3 << 15));
602        assert_eq!(length.to_string(), "1.5em");
603        assert_eq!(Length::parse(".5in").expect("a length").to_string(), "0.5in");
604        assert_eq!(Length::parse("+2pt").expect("a length").to_string(), "2pt");
605        assert_eq!(Length::parse("3.pt").expect("a length").to_string(), "3pt");
606        // One scaled point, and every amount of the fraction, read back.
607        for bits in [1_i64, 3, 6553, 6554, 32767, 65535, 65537, -6553, i64::MAX, i64::MIN] {
608            let length = Length::new(I48F16::from_bits(bits), LengthUnit::Ems);
609            assert_eq!(Length::parse(&length.to_string()), Ok(length), "{bits}");
610        }
611    }
612
613    #[test]
614    fn the_tab_constructor_counts_whole_tabs() {
615        assert_eq!(Length::tabs(1), Length::parse("1tab").expect("a length"));
616        assert_eq!(Length::tabs(2).to_string(), "2tab");
617        assert_eq!(Length::tabs(i32::MAX).amount, I48F16::from_num(i32::MAX));
618        assert_eq!(Length::tabs(-3).to_string(), "-3tab");
619    }
620
621    #[test]
622    fn a_zero_length_is_zero_whatever_its_unit() {
623        let zero = Length::default();
624        assert!(zero.is_zero());
625        assert_eq!(zero.to_string(), "0tab");
626        assert!(Length::parse("0pt").expect("a length").is_zero());
627        assert!(Length::parse("-0em").expect("a length").is_zero());
628        assert!(!Length::tabs(1).is_zero());
629    }
630
631    #[test]
632    fn a_text_that_is_no_length_is_refused_with_its_reason() {
633        assert_eq!(Length::parse(""), Err(LengthError::Empty));
634        assert!(matches!(Length::parse("1.5"), Err(LengthError::NoUnit { .. })));
635        assert_eq!(
636            Length::parse("2xx"),
637            Err(LengthError::UnknownUnit { unit: String::from("xx") })
638        );
639        assert!(matches!(Length::parse("pt"), Err(LengthError::NoAmount { .. })));
640        assert!(matches!(Length::parse("infpt"), Err(LengthError::UnknownUnit { .. })));
641        assert!(matches!(Length::parse("nan"), Err(LengthError::UnknownUnit { .. })));
642        for text in ["1.2.3pt", "1e3pt", "1_0pt", "1 pt", " 1pt", "-pt", ".pt", "1,5em"] {
643            assert!(Length::parse(text).is_err(), "{text}");
644        }
645        assert!(matches!(
646            Length::parse("1000000000000000000000pt"),
647            Err(LengthError::Overflow { .. })
648        ));
649        assert!(Length::parse("1Pt").is_err(), "units are lowercase");
650    }
651
652    #[test]
653    fn two_equal_lengths_hash_alike() {
654        let a = Length::parse("1.5em").expect("a length");
655        let b = Length::new(I48F16::from_bits(3 << 15), LengthUnit::Ems);
656        assert_eq!(a, b);
657        assert_eq!(hash_of(&a), hash_of(&b));
658        assert_ne!(a, Length::parse("1.5pt").expect("a length"));
659    }
660
661    #[test]
662    fn every_unit_parses_from_its_spelling() {
663        for unit in LengthUnit::ALL {
664            assert_eq!(LengthUnit::parse(unit.as_str()), Some(unit));
665            assert_eq!(unit.to_string(), unit.as_str());
666        }
667        assert_eq!(LengthUnit::parse("bp"), None);
668    }
669
670    fn length(text: &str) -> Length {
671        Length::parse(text).unwrap_or_else(|error| panic!("{text}: {error}"))
672    }
673
674    #[test]
675    fn every_pair_of_physical_units_converts_both_ways() {
676        // One inch in each physical unit, exactly.
677        let inch = [("72pt", LengthUnit::Points), ("25.4mm", LengthUnit::Millimeters),
678            ("2.54cm", LengthUnit::Centimeters), ("1in", LengthUnit::Inches)];
679        for (from_text, from_unit) in inch {
680            for (to_text, to_unit) in inch {
681                let from = length(from_text);
682                let converted = from.convert_to(to_unit).expect("a physical conversion");
683                // 25.4 and 2.54 are no whole number of scaled points: each
684                // parsed amount is off by at most half a scaled point of its
685                // unit, which the conversion scales by the ratio of the units,
686                // and the conversion rounds once more.
687                let expected = length(to_text);
688                let ratio = from_unit.size().unwrap() / to_unit.size().unwrap();
689                let bound = i64::try_from(ratio).unwrap() / 2 + 2;
690                let off = (converted.amount.to_bits() - expected.amount.to_bits()).abs();
691                assert!(off <= bound, "{from_text} in {to_unit}: {converted}, not {to_text}");
692                assert_eq!(converted.unit, to_unit);
693            }
694        }
695        // Amounts that are exact in both units convert exactly.
696        for (from, unit, to) in [
697            ("72pt", LengthUnit::Inches, "1in"),
698            ("1in", LengthUnit::Points, "72pt"),
699            ("10mm", LengthUnit::Centimeters, "1cm"),
700            ("1cm", LengthUnit::Millimeters, "10mm"),
701            ("0.5in", LengthUnit::Points, "36pt"),
702            ("36pt", LengthUnit::Inches, "0.5in"),
703            ("-1in", LengthUnit::Points, "-72pt"),
704            ("0cm", LengthUnit::Points, "0pt"),
705            ("3pt", LengthUnit::Points, "3pt"),
706        ] {
707            assert_eq!(length(from).convert_to(unit), Ok(length(to)), "{from} in {unit}");
708        }
709    }
710
711    #[test]
712    fn a_length_times_a_factor_keeps_its_unit_and_rounds_once() {
713        assert_eq!(length("4cm").times(I48F16::from_num(1.25)), Ok(length("5cm")));
714        assert_eq!(length("2em").times(I48F16::from_num(0.5)), Ok(length("1em")));
715        // 3 scaled points times 0.5: 1.5, a half rounded away from zero.
716        let three = Length::new(I48F16::from_bits(3), LengthUnit::Points);
717        assert_eq!(three.times(I48F16::from_num(0.5)).expect("a product").amount.to_bits(), 2);
718        let huge = Length::new(I48F16::MAX, LengthUnit::Points);
719        assert_eq!(huge.times(I48F16::from_num(2)), Err(LengthConversionError::Overflow));
720    }
721
722    #[test]
723    fn a_conversion_rounds_once_to_the_nearest_scaled_point() {
724        // 1pt = 127/360 mm = 0.352777… mm: 23119.64… scaled points, 23120.
725        let mm = length("1pt").convert_to(LengthUnit::Millimeters).expect("a conversion");
726        assert_eq!(mm.amount.to_bits(), 23120);
727        // 1mm = 360/127 pt = 2.834645… pt: 185771.33… scaled points, 185771.
728        let pt = length("1mm").convert_to(LengthUnit::Points).expect("a conversion");
729        assert_eq!(pt.amount.to_bits(), 185771);
730        assert_eq!(length("-1mm").convert_to(LengthUnit::Points).expect("a conversion")
731            .amount.to_bits(), -185771);
732        // A half rounds away from zero: 72 scaled points of a point are one
733        // scaled point of an inch, so 36 are exactly half of one.
734        let half = Length::new(I48F16::from_bits(36), LengthUnit::Points);
735        assert_eq!(half.convert_to(LengthUnit::Inches).expect("a conversion").amount.to_bits(), 1);
736        let minus_half = Length::new(I48F16::from_bits(-36), LengthUnit::Points);
737        assert_eq!(minus_half.convert_to(LengthUnit::Inches).expect("a conversion")
738            .amount.to_bits(), -1);
739        let under_half = Length::new(I48F16::from_bits(35), LengthUnit::Points);
740        assert_eq!(under_half.convert_to(LengthUnit::Inches).expect("a conversion")
741            .amount.to_bits(), 0);
742    }
743
744    #[test]
745    fn a_round_trip_through_a_coarser_unit_comes_back_within_its_rounding() {
746        for text in ["10pt", "3.3mm", "12.7cm", "0.1in", "-7.25pt", "1000mm"] {
747            let start = length(text);
748            for unit in [LengthUnit::Points, LengthUnit::Millimeters,
749                LengthUnit::Centimeters, LengthUnit::Inches] {
750                let back = start.convert_to(unit).and_then(|there| there.convert_to(start.unit))
751                    .expect("a physical round trip");
752                // Half a scaled point of the intermediate unit is at most 36
753                // scaled points of the start's unit; the way back rounds once more.
754                let off = (back.amount.to_bits() - start.amount.to_bits()).abs();
755                assert!(off <= 73, "{text} through {unit}: {back}");
756            }
757            // Through its own unit, exactly.
758            assert_eq!(start.convert_to(start.unit), Ok(start));
759        }
760    }
761
762    #[test]
763    fn a_tab_or_an_em_converts_to_nothing() {
764        for unit in [LengthUnit::Tabs, LengthUnit::Ems] {
765            assert!(!unit.is_physical());
766            let value = Length::new(I48F16::from_num(2), unit);
767            assert_eq!(value.convert_to(LengthUnit::Points),
768                Err(LengthConversionError::NotPhysical { unit }));
769            assert_eq!(length("1pt").convert_to(unit),
770                Err(LengthConversionError::NotPhysical { unit }));
771            assert_eq!(length("1pt").scaled(&value, &length("1pt"), LengthUnit::Points),
772                Err(LengthConversionError::NotPhysical { unit }));
773            assert_eq!(length("1pt").scaled(&length("1pt"), &value, LengthUnit::Points),
774                Err(LengthConversionError::NotPhysical { unit }));
775            assert_eq!(value.scaled(&length("1pt"), &length("1pt"), LengthUnit::Points),
776                Err(LengthConversionError::NotPhysical { unit }));
777        }
778        for unit in [LengthUnit::Points, LengthUnit::Millimeters, LengthUnit::Centimeters,
779            LengthUnit::Inches] {
780            assert!(unit.is_physical());
781        }
782    }
783
784    #[test]
785    fn a_scaling_keeps_the_proportions_in_the_given_unit() {
786        // 340pt × 170pt shown 5cm wide is 2.5cm high, and 2.5cm high 5cm wide.
787        let (width, height) = (length("340pt"), length("170pt"));
788        let given = length("5cm");
789        assert_eq!(height.scaled(&given, &width, given.unit), Ok(length("2.5cm")));
790        let given = length("2.5cm");
791        assert_eq!(width.scaled(&given, &height, given.unit), Ok(length("5cm")));
792        // Across units, exactly: 1in wide, 36pt high, shown 2in wide: 1in high.
793        assert_eq!(length("36pt").scaled(&length("2in"), &length("1in"), LengthUnit::Inches),
794            Ok(length("1in")));
795        assert_eq!(length("1pt").scaled(&length("1pt"), &length("0pt"), LengthUnit::Points),
796            Err(LengthConversionError::ZeroDenominator));
797        // A result beyond the amount's range is refused, not wrapped.
798        let huge = Length::new(I48F16::MAX, LengthUnit::Inches);
799        assert_eq!(huge.scaled(&huge, &length("1pt"), LengthUnit::Points),
800            Err(LengthConversionError::Overflow));
801        assert_eq!(huge.convert_to(LengthUnit::Points), Err(LengthConversionError::Overflow));
802    }
803
804    #[test]
805    fn dots_at_a_resolution_give_points() {
806        assert_eq!(Length::from_dots(300, I48F16::from_num(150)), Ok(length("144pt")));
807        assert_eq!(Length::from_dots(96, I48F16::from_num(96)), Ok(length("72pt")));
808        assert_eq!(Length::from_dots(0, I48F16::from_num(96)), Ok(length("0pt")));
809        // 100 dots at 96 per inch: 75pt exactly; at 7 per inch, 1028.571428…pt.
810        assert_eq!(Length::from_dots(100, I48F16::from_num(96)), Ok(length("75pt")));
811        let odd = Length::from_dots(100, I48F16::from_num(7)).expect("a size");
812        assert_eq!(odd.amount.to_bits(), (7200_i64 * 65536 + 3) / 7);
813        assert_eq!(Length::from_dots(1, I48F16::ZERO), Err(LengthConversionError::ZeroDenominator));
814        assert_eq!(Length::from_dots(u64::MAX, I48F16::from_bits(1)),
815            Err(LengthConversionError::Overflow));
816    }
817}