Skip to main content

ifc_properties/convert/
format.rs

1//! Lengths as text: decimal in any length unit, or feet and inches with
2//! fractions.
3
4use super::{convert_value, ConversionUnit, UnitConversionError};
5
6/// How [`format_length`] writes a length.
7#[derive(Debug, Clone, PartialEq)]
8#[non_exhaustive]
9pub enum LengthFormat {
10    /// The value in `unit`, with `decimal_places` digits after the point:
11    /// `1.25` for 1250 mm in metres with two places. No unit symbol is
12    /// written.
13    Decimal {
14        /// The unit to write the value in.
15        unit: ConversionUnit,
16        /// Digits after the decimal point.
17        decimal_places: u8,
18    },
19    /// Feet and inches, the inches rounded to the nearest
20    /// `1/denominator`: `5' - 6 1/2"`. With `suppress_zero_inches`, a whole
21    /// number of feet is written `5'`.
22    FeetInches {
23        /// The fraction of an inch to round to: 2, 4, 8, 16, 32, 64 ...
24        denominator: u32,
25        /// Write `5'` rather than `5' - 0"`.
26        suppress_zero_inches: bool,
27    },
28    /// Inches only, rounded to the nearest `1/denominator`: `66 1/2"`.
29    Inches {
30        /// The fraction of an inch to round to.
31        denominator: u32,
32    },
33}
34
35impl LengthFormat {
36    /// `Decimal` with `decimal_places` digits in `unit`.
37    #[must_use]
38    pub fn decimal(unit: ConversionUnit, decimal_places: u8) -> Self {
39        Self::Decimal {
40            unit,
41            decimal_places,
42        }
43    }
44
45    /// `FeetInches` to the nearest `1/denominator` inch.
46    #[must_use]
47    pub fn feet_inches(denominator: u32, suppress_zero_inches: bool) -> Self {
48        Self::FeetInches {
49            denominator,
50            suppress_zero_inches,
51        }
52    }
53
54    /// `Inches` to the nearest `1/denominator` inch.
55    #[must_use]
56    pub fn inches(denominator: u32) -> Self {
57        Self::Inches { denominator }
58    }
59}
60
61/// Write `value`, a length in `unit`, as `format` asks.
62///
63/// Negative lengths keep their sign in front (`-1' - 6"`). A fraction is
64/// reduced (`4/8` is written `1/2`), and inches that round up to twelve
65/// carry into the feet. This is IfcOpenShell's `format_length` layout
66/// (`util/unit.py`), with the value given in any length unit rather than
67/// in feet or inches.
68///
69/// # Errors
70///
71/// [`UnitConversionError::DimensionMismatch`] when `unit`, or the decimal
72/// format's unit, is not a length; [`UnitConversionError::NonFinite`] for a
73/// value that is not finite; [`UnitConversionError::InvalidFormat`] for a
74/// zero denominator or a value too large to round to it.
75pub fn format_length(
76    value: f64,
77    unit: &ConversionUnit,
78    format: &LengthFormat,
79) -> Result<String, UnitConversionError> {
80    let length = [1, 0, 0, 0, 0, 0, 0];
81    if unit.dimensions != length {
82        return Err(UnitConversionError::DimensionMismatch {
83            from: unit.dimensions,
84            to: length,
85        });
86    }
87    match format {
88        LengthFormat::Decimal {
89            unit: target,
90            decimal_places,
91        } => {
92            let converted = convert_value(value, unit, target)?;
93            let places = usize::from(*decimal_places);
94            let text = format!("{converted:.places$}");
95            // `-0.00` reads as a negative length.
96            Ok(
97                if text.starts_with('-') && text[1..].chars().all(|c| c == '0' || c == '.') {
98                    text[1..].to_owned()
99                } else {
100                    text
101                },
102            )
103        }
104        LengthFormat::FeetInches {
105            denominator,
106            suppress_zero_inches,
107        } => {
108            let (negative, units) = rounded_fractions(value, unit, *denominator)?;
109            let per_foot = 12 * u64::from(*denominator);
110            let feet = units / per_foot;
111            let inches = units % per_foot;
112            let sign = if negative && units != 0 { "-" } else { "" };
113            if inches == 0 && *suppress_zero_inches {
114                return Ok(format!("{sign}{feet}'"));
115            }
116            Ok(format!(
117                "{sign}{feet}' - {}\"",
118                inches_text(inches, *denominator)
119            ))
120        }
121        LengthFormat::Inches { denominator } => {
122            let (negative, units) = rounded_fractions(value, unit, *denominator)?;
123            let sign = if negative && units != 0 { "-" } else { "" };
124            Ok(format!("{sign}{}\"", inches_text(units, *denominator)))
125        }
126    }
127}
128
129/// `|value|` in `1/denominator` inches, rounded half away from zero, and
130/// whether `value` is negative.
131fn rounded_fractions(
132    value: f64,
133    unit: &ConversionUnit,
134    denominator: u32,
135) -> Result<(bool, u64), UnitConversionError> {
136    if denominator == 0 {
137        return Err(UnitConversionError::InvalidFormat {
138            reason: "the fraction denominator must be at least 1",
139        });
140    }
141    let inch = ConversionUnit::named("inch")?;
142    let inches = convert_value(value, unit, &inch)?;
143    let units = (inches.abs() * f64::from(denominator)).round();
144    // 2^53: every integer below it is exact in f64.
145    if units >= 9_007_199_254_740_992.0 {
146        return Err(UnitConversionError::InvalidFormat {
147            reason: "the length is too large to round to the requested fraction",
148        });
149    }
150    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
151    let units = units as u64;
152    Ok((inches < 0.0, units))
153}
154
155/// `units / denominator` inches as `whole num/den`, reduced.
156fn inches_text(units: u64, denominator: u32) -> String {
157    let denominator = u64::from(denominator);
158    let whole = units / denominator;
159    let numerator = units % denominator;
160    if numerator == 0 {
161        return whole.to_string();
162    }
163    let divisor = gcd(numerator, denominator);
164    format!("{whole} {}/{}", numerator / divisor, denominator / divisor)
165}
166
167fn gcd(mut a: u64, mut b: u64) -> u64 {
168    while b != 0 {
169        (a, b) = (b, a % b);
170    }
171    a
172}
173
174#[cfg(test)]
175mod tests {
176    use super::*;
177
178    fn unit(spec: &str) -> ConversionUnit {
179        ConversionUnit::parse(spec).unwrap()
180    }
181
182    #[test]
183    fn feet_and_inches_round_to_the_fraction_and_carry() {
184        let foot = unit("foot");
185        let format = LengthFormat::feet_inches(8, true);
186        assert_eq!(format_length(5.5, &foot, &format).unwrap(), "5' - 6\"");
187        assert_eq!(format_length(5.0, &foot, &format).unwrap(), "5'");
188        assert_eq!(
189            format_length(5.0, &foot, &LengthFormat::feet_inches(8, false)).unwrap(),
190            "5' - 0\""
191        );
192        // 1' 5.5" in millimetres.
193        let mm = unit("MILLIMETRE");
194        assert_eq!(format_length(444.5, &mm, &format).unwrap(), "1' - 5 1/2\"");
195        // 11.99" rounds to a whole foot.
196        let inch = unit("inch");
197        assert_eq!(format_length(11.99, &inch, &format).unwrap(), "1'");
198        assert_eq!(
199            format_length(0.125, &inch, &format).unwrap(),
200            "0' - 0 1/8\""
201        );
202        assert_eq!(format_length(-18.0, &inch, &format).unwrap(), "-1' - 6\"");
203    }
204
205    #[test]
206    fn inches_and_decimals() {
207        let foot = unit("foot");
208        assert_eq!(
209            format_length(5.5417, &foot, &LengthFormat::inches(2)).unwrap(),
210            "66 1/2\""
211        );
212        let mm = unit("MILLIMETRE");
213        assert_eq!(
214            format_length(1250.0, &mm, &LengthFormat::decimal(unit("METRE"), 2)).unwrap(),
215            "1.25"
216        );
217        assert_eq!(
218            format_length(-0.001, &mm, &LengthFormat::decimal(unit("METRE"), 2)).unwrap(),
219            "0.00"
220        );
221    }
222
223    #[test]
224    fn non_lengths_and_bad_formats_are_refused() {
225        assert!(matches!(
226            format_length(1.0, &unit("SQUARE_METRE"), &LengthFormat::inches(2)),
227            Err(UnitConversionError::DimensionMismatch { .. })
228        ));
229        assert!(matches!(
230            format_length(1.0, &unit("METRE"), &LengthFormat::inches(0)),
231            Err(UnitConversionError::InvalidFormat { .. })
232        ));
233        assert!(matches!(
234            format_length(1.0, &unit("METRE"), &LengthFormat::decimal(unit("GRAM"), 2)),
235            Err(UnitConversionError::DimensionMismatch { .. })
236        ));
237    }
238}