Skip to main content

ancdec/ancdec32/
convert.rs

1use super::AncDec32;
2use crate::error::ParseError;
3use crate::util::{pow10_32, StackBuf};
4use core::convert::TryFrom;
5use core::fmt::Write;
6use core::str::FromStr;
7
8impl AncDec32 {
9    /// Converts to `f64` (may lose precision).
10    pub fn to_f64(&self) -> f64 {
11        let v = self.int as f64
12            + if self.scale == 0 {
13                0.0
14            } else {
15                self.frac as f64 / pow10_32(self.scale) as f64
16            };
17        if self.neg {
18            -v
19        } else {
20            v
21        }
22    }
23
24    /// Converts to `i64`, truncating the fractional part.
25    pub fn to_i64(&self) -> i64 {
26        if self.neg {
27            -(self.int as i64)
28        } else {
29            self.int as i64
30        }
31    }
32
33    /// Converts to `i128`, truncating the fractional part.
34    pub fn to_i128(&self) -> i128 {
35        if self.neg {
36            -(self.int as i128)
37        } else {
38            self.int as i128
39        }
40    }
41}
42
43/// FromStr trait: enables `"123.45".parse::<AncDec32>()`
44impl FromStr for AncDec32 {
45    type Err = ParseError;
46    fn from_str(s: &str) -> Result<Self, Self::Err> {
47        Self::parse_str(s)
48    }
49}
50
51impl TryFrom<&str> for AncDec32 {
52    type Error = ParseError;
53    #[inline(always)]
54    fn try_from(s: &str) -> Result<Self, Self::Error> {
55        Self::parse_str(s)
56    }
57}
58
59impl TryFrom<f32> for AncDec32 {
60    type Error = ParseError;
61    #[inline(always)]
62    fn try_from(n: f32) -> Result<Self, Self::Error> {
63        AncDec32::try_from(n as f64)
64    }
65}
66
67impl TryFrom<f64> for AncDec32 {
68    type Error = ParseError;
69    #[inline(always)]
70    fn try_from(n: f64) -> Result<Self, Self::Error> {
71        if n.is_nan() || n.is_infinite() {
72            return Err(ParseError::InvalidFloat);
73        }
74        let mut buf = StackBuf::<32>::new();
75        write!(buf, "{}", n).ok();
76        Self::parse_str(buf.as_str())
77    }
78}
79
80/// Lossless widening from AncDec8 (u8) to AncDec32 (u32)
81#[cfg(feature = "dec8")]
82impl From<crate::ancdec8::AncDec8> for AncDec32 {
83    #[inline(always)]
84    fn from(a: crate::ancdec8::AncDec8) -> Self {
85        Self {
86            int: a.int as u32,
87            frac: a.frac as u32,
88            scale: a.scale,
89            neg: a.neg,
90        }
91    }
92}