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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
use num::arithmetic::traits::{CheckedLogBase2, NegAssign, Pow, UnsignedAbs};
use num::basic::integers::PrimitiveInt;
use num::basic::signeds::PrimitiveSigned;
use num::basic::unsigneds::PrimitiveUnsigned;
use num::conversion::string::options::{SciSizeOptions, ToSciOptions};
use num::conversion::string::to_string::BaseFmtWrapper;
use num::conversion::string::to_string::{
    digit_to_display_byte_lower, digit_to_display_byte_upper,
};
use num::conversion::traits::{ExactFrom, ToSci};
use rounding_modes::RoundingMode;
use slices::slice_trailing_zeros;
use std::fmt::{Display, Formatter, Write};

/// A `struct` that can be used to format a number in scientific notation.
pub struct SciWrapper<'a, T: ToSci> {
    pub(crate) x: &'a T,
    pub(crate) options: ToSciOptions,
}

impl<'a, T: ToSci> Display for SciWrapper<'a, T> {
    #[inline]
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        self.x.fmt_sci(f, self.options)
    }
}

#[doc(hidden)]
pub fn write_exponent<T: PrimitiveInt>(
    f: &mut Formatter,
    options: ToSciOptions,
    exp: T,
) -> std::fmt::Result {
    f.write_char(if options.get_e_lowercase() { 'e' } else { 'E' })?;
    if exp > T::ZERO && (options.get_force_exponent_plus_sign() || options.get_base() >= 15) {
        f.write_char('+')?;
    }
    write!(f, "{}", exp)
}

fn write_helper<T>(x: T, f: &mut Formatter, options: ToSciOptions) -> std::fmt::Result
where
    BaseFmtWrapper<T>: Display,
{
    let w = BaseFmtWrapper {
        x,
        base: options.base,
    };
    if options.lowercase {
        Display::fmt(&w, f)
    } else {
        write!(f, "{:#}", w)
    }
}

fn fmt_sci_valid_unsigned<T: PrimitiveUnsigned>(x: T, options: ToSciOptions) -> bool {
    if x == T::ZERO || options.rounding_mode != RoundingMode::Exact {
        return true;
    }
    match options.size_options {
        SciSizeOptions::Complete | SciSizeOptions::Scale(_) => true,
        SciSizeOptions::Precision(precision) => {
            let t_base = T::from(options.base);
            let log = x.floor_log_base(t_base);
            if log < precision {
                return true;
            }
            let neg_scale = log - precision + 1;
            if let Some(base_log) = options.base.checked_log_base_2() {
                x.divisible_by_power_of_2(base_log * neg_scale)
            } else {
                x.divisible_by(Pow::pow(t_base, neg_scale))
            }
        }
    }
}

fn fmt_sci_unsigned<T: PrimitiveUnsigned>(
    mut x: T,
    f: &mut Formatter,
    options: ToSciOptions,
) -> std::fmt::Result
where
    BaseFmtWrapper<T>: Display,
{
    match options.size_options {
        SciSizeOptions::Complete | SciSizeOptions::Scale(0) => write_helper(x, f, options),
        SciSizeOptions::Scale(scale) => {
            write_helper(x, f, options)?;
            if options.include_trailing_zeros {
                f.write_char('.')?;
                for _ in 0..scale {
                    f.write_char('0')?;
                }
            }
            Ok(())
        }
        SciSizeOptions::Precision(precision) => {
            let t_base = T::from(options.base);
            let log = if x == T::ZERO {
                0
            } else {
                x.floor_log_base(t_base)
            };
            if log < precision {
                // no exponent
                write_helper(x, f, options)?;
                if options.include_trailing_zeros {
                    let extra_zeros = precision - log - 1;
                    if extra_zeros != 0 {
                        f.write_char('.')?;
                        for _ in 0..extra_zeros {
                            f.write_char('0')?;
                        }
                    }
                }
                Ok(())
            } else {
                // exponent
                let mut e = log;
                let neg_scale = log - precision + 1;
                if let Some(base_log) = options.base.checked_log_base_2() {
                    x.shr_round_assign(base_log * neg_scale, options.rounding_mode);
                } else {
                    x.div_round_assign(Pow::pow(t_base, neg_scale), options.rounding_mode);
                }
                let mut chars = x.to_digits_desc(&options.base);
                let mut len = chars.len();
                let p = usize::exact_from(precision);
                if len > p {
                    // rounded up to a power of the base, need to reduce precision
                    chars.pop();
                    len -= 1;
                    e += 1;
                }
                assert_eq!(len, p);
                if !options.include_trailing_zeros {
                    chars.truncate(len - slice_trailing_zeros(&chars));
                }
                if options.lowercase {
                    for digit in &mut chars {
                        *digit = digit_to_display_byte_lower(*digit).unwrap();
                    }
                } else {
                    for digit in &mut chars {
                        *digit = digit_to_display_byte_upper(*digit).unwrap();
                    }
                }
                len = chars.len();
                if len != 1 {
                    chars.push(b'0');
                    chars.copy_within(1..len, 2);
                    chars[1] = b'.';
                }
                f.write_str(&String::from_utf8(chars).unwrap())?;
                write_exponent(f, options, e)
            }
        }
    }
}

#[inline]
fn fmt_sci_valid_signed<T: PrimitiveSigned>(x: T, options: ToSciOptions) -> bool
where
    <T as UnsignedAbs>::Output: PrimitiveUnsigned,
{
    fmt_sci_valid_unsigned(x.unsigned_abs(), options)
}

fn fmt_sci_signed<T: PrimitiveSigned>(
    x: T,
    f: &mut Formatter,
    mut options: ToSciOptions,
) -> std::fmt::Result
where
    <T as UnsignedAbs>::Output: PrimitiveUnsigned,
{
    let abs = x.unsigned_abs();
    if x >= T::ZERO {
        abs.fmt_sci(f, options)
    } else {
        options.rounding_mode.neg_assign();
        f.write_char('-')?;
        abs.fmt_sci(f, options)
    }
}

macro_rules! impl_to_sci_unsigned {
    ($t:ident) => {
        impl ToSci for $t {
            /// Determines whether an unsigned number can be converted to a string using
            /// [`to_sci_with_options`](super::super::traits::ToSci::to_sci_with_options) and a
            /// particular set of options.
            ///
            /// # Worst-case complexity
            /// Constant time and additional memory.
            ///
            /// # Examples
            /// See [here](super::to_sci#fmt_sci_valid).
            #[inline]
            fn fmt_sci_valid(&self, options: ToSciOptions) -> bool {
                fmt_sci_valid_unsigned(*self, options)
            }

            /// Converts an unsigned number to a string using a specified base, possibly formatting
            /// the number using scientific notation.
            ///
            /// See [`ToSciOptions`](super::options::ToSciOptions) for details on the available
            /// options. Note that setting `neg_exp_threshold` has no effect, since there is never
            /// a need to use negative exponents when representing an integer.
            ///
            /// # Worst-case complexity
            /// $T(n) = O(n)$
            ///
            /// $M(n) = O(n)$
            ///
            /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
            ///
            /// # Panics
            /// Panics if `options.rounding_mode` is `Exact`, but the size options are such that
            /// the input must be rounded.
            ///
            /// # Examples
            /// See [here](super::to_sci).
            #[inline]
            fn fmt_sci(&self, f: &mut Formatter, options: ToSciOptions) -> std::fmt::Result {
                fmt_sci_unsigned(*self, f, options)
            }
        }
    };
}
apply_to_unsigneds!(impl_to_sci_unsigned);

macro_rules! impl_to_sci_signed {
    ($t:ident) => {
        impl ToSci for $t {
            /// Determines whether a signed number can be converted to a string using
            /// [`to_sci_with_options`](super::super::traits::ToSci::to_sci_with_options) and a
            /// particular set of options.
            ///
            /// # Worst-case complexity
            /// Constant time and additional memory.
            ///
            /// # Examples
            /// See [here](super::to_sci#fmt_sci_valid).
            #[inline]
            fn fmt_sci_valid(&self, options: ToSciOptions) -> bool {
                fmt_sci_valid_signed(*self, options)
            }

            /// Converts a signed number to a string using a specified base, possibly formatting
            /// the number using scientific notation.
            ///
            /// See [`ToSciOptions`](super::options::ToSciOptions) for details on the available
            /// options. Note that setting `neg_exp_threshold` has no effect, since there is never
            /// a need to use negative exponents when representing an integer.
            ///
            /// # Worst-case complexity
            /// $T(n) = O(n)$
            ///
            /// $M(n) = O(n)$
            ///
            /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
            ///
            /// # Panics
            /// Panics if `options.rounding_mode` is `Exact`, but the size options are such that
            /// the input must be rounded.
            ///
            /// # Examples
            /// See [here](super::to_sci).
            #[inline]
            fn fmt_sci(&self, f: &mut Formatter, options: ToSciOptions) -> std::fmt::Result {
                fmt_sci_signed(*self, f, options)
            }
        }
    };
}
apply_to_signeds!(impl_to_sci_signed);