Skip to main content

oxinum_complex/
fmt.rs

1//! Human-readable formatting for [`CBig`].
2//!
3//! [`Display`](fmt::Display) renders a complex number in the conventional
4//! `re ± im·i` form, picking the sign so the imaginary magnitude is always
5//! printed without a leading `-`. This mirrors the rendering expected by the
6//! SciRS2 `ArbitraryComplex` consumer.
7
8use crate::CBig;
9use core::fmt;
10use oxinum_float::DBig;
11
12/// Render as `"<re> + <im>i"` when the imaginary part is non-negative, and
13/// `"<re> - <|im|>i"` when it is negative.
14///
15/// # Examples
16///
17/// ```
18/// use oxinum_complex::CBig;
19/// let z = CBig::from_f64(2.0, 3.0).expect("finite parts");
20/// assert_eq!(z.to_string(), "2 + 3i");
21/// let w = CBig::from_f64(2.0, -3.0).expect("finite parts");
22/// assert_eq!(w.to_string(), "2 - 3i");
23/// ```
24impl fmt::Display for CBig {
25    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26        if self.im < DBig::from(0u32) {
27            // Print the magnitude after an explicit minus sign.
28            let mag = -self.im.clone();
29            write!(f, "{} - {}i", self.re, mag)
30        } else {
31            write!(f, "{} + {}i", self.re, self.im)
32        }
33    }
34}
35
36/// Developer-facing representation that names both components explicitly.
37///
38/// # Examples
39///
40/// ```
41/// use oxinum_complex::CBig;
42/// let z = CBig::from_f64(2.0, -3.0).expect("finite parts");
43/// assert_eq!(format!("{z:?}"), "CBig { re: 2, im: -3 }");
44/// ```
45impl fmt::Debug for CBig {
46    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47        write!(f, "CBig {{ re: {}, im: {} }}", self.re, self.im)
48    }
49}
50
51#[cfg(test)]
52mod tests {
53    use super::*;
54
55    #[test]
56    fn display_positive_imag() {
57        let z = CBig::from_f64(2.0, 3.0).expect("finite parts");
58        assert_eq!(z.to_string(), "2 + 3i");
59    }
60
61    #[test]
62    fn display_negative_imag() {
63        let z = CBig::from_f64(2.0, -3.0).expect("finite parts");
64        assert_eq!(z.to_string(), "2 - 3i");
65    }
66
67    #[test]
68    fn display_real_shows_zero_imag() {
69        let z = CBig::from_real(DBig::from(5));
70        assert_eq!(z.to_string(), "5 + 0i");
71    }
72
73    #[test]
74    fn display_fractional_components() {
75        let z = CBig::from_f64(1.5, -2.25).expect("finite parts");
76        assert_eq!(z.to_string(), "1.5 - 2.25i");
77    }
78
79    #[test]
80    fn debug_is_non_empty_and_readable() {
81        let z = CBig::from_f64(2.0, -3.0).expect("finite parts");
82        let s = format!("{z:?}");
83        assert!(!s.is_empty());
84        assert_eq!(s, "CBig { re: 2, im: -3 }");
85    }
86}