1use super::{convert_value, ConversionUnit, UnitConversionError};
5
6#[derive(Debug, Clone, PartialEq)]
8#[non_exhaustive]
9pub enum LengthFormat {
10 Decimal {
14 unit: ConversionUnit,
16 decimal_places: u8,
18 },
19 FeetInches {
23 denominator: u32,
25 suppress_zero_inches: bool,
27 },
28 Inches {
30 denominator: u32,
32 },
33}
34
35impl LengthFormat {
36 #[must_use]
38 pub fn decimal(unit: ConversionUnit, decimal_places: u8) -> Self {
39 Self::Decimal {
40 unit,
41 decimal_places,
42 }
43 }
44
45 #[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 #[must_use]
56 pub fn inches(denominator: u32) -> Self {
57 Self::Inches { denominator }
58 }
59}
60
61pub 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 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
129fn 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 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
155fn 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 let mm = unit("MILLIMETRE");
194 assert_eq!(format_length(444.5, &mm, &format).unwrap(), "1' - 5 1/2\"");
195 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}