malachite_float/conversion/string/
to_string.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
// Copyright © 2025 Mikhail Hogrefe
//
// This file is part of Malachite.
//
// Malachite is free software: you can redistribute it and/or modify it under the terms of the GNU
// Lesser General Public License (LGPL) as published by the Free Software Foundation; either version
// 3 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>.

use crate::alloc::string::ToString;
use crate::InnerFloat::{Finite, Infinity, NaN, Zero};
use crate::{ComparableFloat, ComparableFloatRef, Float};
use alloc::string::String;
use core::fmt::{Debug, Display, Formatter, LowerHex, Result, Write};
use malachite_base::num::arithmetic::traits::{
    Abs, ModPowerOf2, RoundToMultipleOfPowerOf2, ShrRound,
};
use malachite_base::num::conversion::string::options::ToSciOptions;
use malachite_base::num::conversion::traits::{ExactFrom, ToSci, WrappingFrom};
use malachite_base::rounding_modes::RoundingMode::*;
use malachite_q::Rational;

fn replace_exponent_in_hex_string(s: &str, new_exponent: i32) -> String {
    let exp_index = s.find('E').unwrap_or_else(|| panic!("{s}"));
    let mut new_s = s[..exp_index].to_string();
    if new_exponent > 0 {
        write!(new_s, "E+{new_exponent}").unwrap();
    } else {
        write!(new_s, "E{new_exponent}").unwrap();
    }
    new_s
}

impl Display for Float {
    fn fmt(&self, f: &mut Formatter) -> Result {
        match self {
            float_nan!() => write!(f, "NaN"),
            float_infinity!() => write!(f, "Infinity"),
            float_negative_infinity!() => write!(f, "-Infinity"),
            float_zero!() => write!(f, "0.0"),
            float_negative_zero!() => write!(f, "-0.0"),
            _ => {
                let exp = self.get_exponent().unwrap();
                if exp.unsigned_abs() > 10000 {
                    // The current slow implementation would take forever to try to convert a Float
                    // with a very large or small exponent to a decimal string. Best to
                    // short-circuit it for now.
                    if *self < 0u32 {
                        write!(f, "-")?;
                    }
                    return write!(f, "{}", if exp >= 0 { "too_big" } else { "too_small" });
                }
                let mut lower = self.clone();
                let mut higher = self.clone();
                lower.decrement();
                higher.increment();
                let self_q = Rational::exact_from(self);
                let lower_q = Rational::exact_from(lower);
                let higher_q = Rational::exact_from(higher);
                let mut options = ToSciOptions::default();
                for precision in 1.. {
                    options.set_precision(precision);
                    let s = self_q.to_sci_with_options(options).to_string();
                    let s_lower = lower_q.to_sci_with_options(options).to_string();
                    let s_higher = higher_q.to_sci_with_options(options).to_string();
                    if s != s_lower && s != s_higher {
                        return if s.contains('.') {
                            write!(f, "{s}")
                        } else if let Some(i) = s.find('e') {
                            write!(f, "{}.0e{}", &s[..i], &s[i + 1..])
                        } else {
                            write!(f, "{s}.0")
                        };
                    }
                }
                panic!();
            }
        }
    }
}

impl Debug for Float {
    #[inline]
    fn fmt(&self, f: &mut Formatter) -> Result {
        Display::fmt(self, f)
    }
}

impl LowerHex for Float {
    #[inline]
    fn fmt(&self, f: &mut Formatter) -> Result {
        match self {
            float_zero!() => f.write_str(if f.alternate() { "0x0.0" } else { "0.0" }),
            float_negative_zero!() => f.write_str(if f.alternate() { "-0x0.0" } else { "-0.0" }),
            Float(Finite {
                exponent,
                precision,
                ..
            }) => {
                if self.is_sign_negative() {
                    f.write_char('-')?;
                }
                let mut options = ToSciOptions::default();
                options.set_base(16);
                let m = u64::from(exponent.mod_power_of_2(2));
                let mut p = precision.saturating_sub(m).shr_round(2, Ceiling).0;
                if m != 0 {
                    p += 1;
                }
                options.set_precision(p);
                options.set_e_uppercase();
                options.set_include_trailing_zeros(true);
                if f.alternate() {
                    f.write_str("0x")?;
                }
                let pr = precision.round_to_multiple_of_power_of_2(5, Up).0;
                let s = if u64::from(exponent.unsigned_abs()) > (pr << 2) {
                    let new_exponent = if *exponent > 0 {
                        i32::exact_from(pr << 1)
                    } else {
                        -i32::exact_from(pr << 1)
                    } + i32::wrapping_from(exponent.mod_power_of_2(2));
                    let mut s = Rational::exact_from(self >> (exponent - new_exponent))
                        .abs()
                        .to_sci_with_options(options)
                        .to_string();
                    s = replace_exponent_in_hex_string(&s, (exponent - 1).shr_round(2, Floor).0);
                    s
                } else {
                    Rational::exact_from(self)
                        .abs()
                        .to_sci_with_options(options)
                        .to_string()
                };
                if s.contains('.') {
                    write!(f, "{s}")
                } else if let Some(i) = s.find('E') {
                    write!(f, "{}.0E{}", &s[..i], &s[i + 1..])
                } else {
                    write!(f, "{s}.0")
                }
            }
            _ => Display::fmt(&self, f),
        }
    }
}

impl Display for ComparableFloat {
    #[inline]
    fn fmt(&self, f: &mut Formatter) -> Result {
        Display::fmt(&ComparableFloatRef(&self.0), f)
    }
}

impl Debug for ComparableFloat {
    #[inline]
    fn fmt(&self, f: &mut Formatter) -> Result {
        Debug::fmt(&ComparableFloatRef(&self.0), f)
    }
}

impl LowerHex for ComparableFloat {
    #[inline]
    fn fmt(&self, f: &mut Formatter) -> Result {
        LowerHex::fmt(&ComparableFloatRef(&self.0), f)
    }
}

impl Display for ComparableFloatRef<'_> {
    fn fmt(&self, f: &mut Formatter) -> Result {
        if let x @ Float(Finite { precision, .. }) = &self.0 {
            write!(f, "{x}")?;
            f.write_char('#')?;
            write!(f, "{precision}")
        } else {
            Display::fmt(&self.0, f)
        }
    }
}

impl LowerHex for ComparableFloatRef<'_> {
    fn fmt(&self, f: &mut Formatter) -> Result {
        if let x @ Float(Finite { precision, .. }) = &self.0 {
            if f.alternate() {
                write!(f, "{x:#x}")?;
            } else {
                write!(f, "{x:x}")?;
            }
            f.write_char('#')?;
            write!(f, "{precision}")
        } else {
            LowerHex::fmt(&self.0, f)
        }
    }
}

impl Debug for ComparableFloatRef<'_> {
    #[inline]
    fn fmt(&self, f: &mut Formatter) -> Result {
        Display::fmt(self, f)
    }
}