Skip to main content

rustorb_core/
fixed.rs

1//! `fixed`: decimal fixed-point values.
2
3use std::fmt;
4use std::str::FromStr;
5
6/// The value of an IDL `fixed<digits, scale>`: a decimal number with a
7/// sign, its digits and the number of them after the decimal point.
8///
9/// The value is kept as it was made, and fitted to the digits and scale of
10/// a `fixed` type when it is sent: digits after the scale are cut off,
11/// and an integer part that does not fit is `DATA_CONVERSION`. Values
12/// compare by their number, so `1.50` equals `1.5`. Arithmetic is not
13/// provided.
14#[derive(Debug, Clone, Default)]
15pub struct Fixed {
16    /// The digits, each 0 to 9, most significant first, without leading
17    /// zeros in the integer part.
18    digits: Vec<u8>,
19    /// How many of the digits are after the decimal point.
20    scale: u16,
21    negative: bool,
22}
23
24/// The text given to [`Fixed::from_str`] is not a decimal number.
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct ParseFixedError;
27
28impl fmt::Display for ParseFixedError {
29    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
30        f.write_str("invalid fixed-point literal")
31    }
32}
33
34impl std::error::Error for ParseFixedError {}
35
36impl Fixed {
37    /// The value with the digits `digits` (each 0 to 9, most significant
38    /// first), `scale` of them after the decimal point. `None` if a digit
39    /// is over 9 or there are fewer digits than `scale`.
40    pub fn from_digits(digits: &[u8], scale: u16, negative: bool) -> Option<Fixed> {
41        if digits.iter().any(|&d| d > 9) || digits.len() < scale as usize {
42            return None;
43        }
44        let int_len = digits.len() - scale as usize;
45        let skip = digits[..int_len].iter().take_while(|&&d| d == 0).count();
46        let digits = digits[skip..].to_vec();
47        let negative = negative && digits.iter().any(|&d| d != 0);
48        Some(Fixed {
49            digits,
50            scale,
51            negative,
52        })
53    }
54
55    /// The digits, most significant first, without leading zeros in the
56    /// integer part.
57    pub fn digits(&self) -> &[u8] {
58        &self.digits
59    }
60
61    /// How many of the digits are after the decimal point.
62    pub fn scale(&self) -> u16 {
63        self.scale
64    }
65
66    /// Whether the value is below zero.
67    pub fn is_negative(&self) -> bool {
68        self.negative
69    }
70
71    fn int_digits(&self) -> &[u8] {
72        &self.digits[..self.digits.len() - self.scale as usize]
73    }
74
75    fn frac_digits(&self) -> &[u8] {
76        &self.digits[self.digits.len() - self.scale as usize..]
77    }
78
79    /// The value with at most `scale` digits after the decimal point, the
80    /// others cut off.
81    pub fn truncate(&self, scale: u16) -> Fixed {
82        if scale >= self.scale {
83            return self.clone();
84        }
85        let cut = (self.scale - scale) as usize;
86        let digits = &self.digits[..self.digits.len() - cut];
87        Fixed::from_digits(digits, scale, self.negative).expect("valid digits")
88    }
89
90    /// The value with at most `scale` digits after the decimal point,
91    /// rounded half away from zero.
92    pub fn round(&self, scale: u16) -> Fixed {
93        if scale >= self.scale {
94            return self.clone();
95        }
96        let cut = (self.scale - scale) as usize;
97        let keep = self.digits.len() - cut;
98        let mut digits = self.digits[..keep].to_vec();
99        if self.digits[keep] >= 5 {
100            let mut i = digits.len();
101            loop {
102                if i == 0 {
103                    digits.insert(0, 1);
104                    break;
105                }
106                i -= 1;
107                if digits[i] == 9 {
108                    digits[i] = 0;
109                } else {
110                    digits[i] += 1;
111                    break;
112                }
113            }
114        }
115        Fixed::from_digits(&digits, scale, self.negative).expect("valid digits")
116    }
117
118    /// The exactly `digits` digits of the value as a `fixed<digits,
119    /// scale>`, digits after `scale` cut off; `None` if the integer part
120    /// does not fit.
121    pub fn to_digits(&self, digits: u16, scale: u16) -> Option<Vec<u8>> {
122        let int = self.int_digits();
123        let int_room = digits.checked_sub(scale)? as usize;
124        if int.len() > int_room {
125            return None;
126        }
127        let mut out = vec![0; int_room - int.len()];
128        out.extend_from_slice(int);
129        let frac = self.frac_digits();
130        for i in 0..scale as usize {
131            out.push(frac.get(i).copied().unwrap_or(0));
132        }
133        Some(out)
134    }
135
136    /// The integer part without leading zeros and the fraction without
137    /// trailing zeros, for comparisons.
138    fn normalized(&self) -> (&[u8], &[u8]) {
139        let frac = self.frac_digits();
140        let end = frac.len() - frac.iter().rev().take_while(|&&d| d == 0).count();
141        (self.int_digits(), &frac[..end])
142    }
143
144    fn is_zero(&self) -> bool {
145        self.digits.iter().all(|&d| d == 0)
146    }
147}
148
149impl PartialEq for Fixed {
150    fn eq(&self, other: &Fixed) -> bool {
151        if self.is_zero() && other.is_zero() {
152            return true;
153        }
154        self.negative == other.negative && self.normalized() == other.normalized()
155    }
156}
157
158impl Eq for Fixed {}
159
160impl FromStr for Fixed {
161    type Err = ParseFixedError;
162
163    /// Parses `[-+]digits[.digits]`, with an optional `d` or `D` suffix as
164    /// in IDL literals.
165    fn from_str(s: &str) -> Result<Fixed, ParseFixedError> {
166        let s = s.strip_suffix(['d', 'D']).unwrap_or(s);
167        let (negative, s) = match s.as_bytes().first() {
168            Some(b'-') => (true, &s[1..]),
169            Some(b'+') => (false, &s[1..]),
170            _ => (false, s),
171        };
172        let (int, frac) = s.split_once('.').unwrap_or((s, ""));
173        if int.is_empty() && frac.is_empty() {
174            return Err(ParseFixedError);
175        }
176        let mut digits = Vec::with_capacity(int.len() + frac.len());
177        for c in int.bytes().chain(frac.bytes()) {
178            if !c.is_ascii_digit() {
179                return Err(ParseFixedError);
180            }
181            digits.push(c - b'0');
182        }
183        let scale = u16::try_from(frac.len()).map_err(|_| ParseFixedError)?;
184        Fixed::from_digits(&digits, scale, negative).ok_or(ParseFixedError)
185    }
186}
187
188impl fmt::Display for Fixed {
189    /// Writes the value with all its digits: `-12.50`, `0.5`, `7`.
190    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
191        if self.negative {
192            f.write_str("-")?;
193        }
194        let int = self.int_digits();
195        if int.is_empty() {
196            f.write_str("0")?;
197        }
198        for d in int {
199            write!(f, "{d}")?;
200        }
201        let frac = self.frac_digits();
202        if !frac.is_empty() {
203            f.write_str(".")?;
204            for d in frac {
205                write!(f, "{d}")?;
206            }
207        }
208        Ok(())
209    }
210}
211
212#[cfg(test)]
213mod tests {
214    use super::*;
215
216    fn f(s: &str) -> Fixed {
217        s.parse().unwrap()
218    }
219
220    #[test]
221    fn parses_and_prints() {
222        assert_eq!(f("123.45").to_string(), "123.45");
223        assert_eq!(f("-0.50").to_string(), "-0.50");
224        assert_eq!(f("-1.50").to_string(), "-1.50");
225        assert_eq!(f("007").to_string(), "7");
226        assert_eq!(f(".5").to_string(), "0.5");
227        assert_eq!(f("1.5d").to_string(), "1.5");
228        assert_eq!(f("-0").to_string(), "0");
229        assert!("".parse::<Fixed>().is_err());
230        assert!("1.2.3".parse::<Fixed>().is_err());
231        assert!("-".parse::<Fixed>().is_err());
232    }
233
234    #[test]
235    fn compares_by_number() {
236        assert_eq!(f("1.50"), f("1.5"));
237        assert_eq!(f("-0.0"), f("0"));
238        assert_ne!(f("1.5"), f("-1.5"));
239        assert_ne!(f("1.5"), f("15"));
240    }
241
242    #[test]
243    fn fits_to_a_type() {
244        assert_eq!(f("12.345").to_digits(5, 2), Some(vec![0, 1, 2, 3, 4]));
245        assert_eq!(f("-1").to_digits(3, 1), Some(vec![0, 1, 0]));
246        assert_eq!(f("1234").to_digits(5, 2), None);
247        assert_eq!(f("0.5").to_digits(1, 1), Some(vec![5]));
248    }
249
250    #[test]
251    fn rounds_and_truncates() {
252        assert_eq!(f("1.25").round(1).to_string(), "1.3");
253        assert_eq!(f("-1.25").round(1).to_string(), "-1.3");
254        assert_eq!(f("9.96").round(1).to_string(), "10.0");
255        assert_eq!(f("1.29").truncate(1).to_string(), "1.2");
256        assert_eq!(f("1.2").round(3).to_string(), "1.2");
257    }
258}