malachite_float/float/conversion/string/get_str.rs
1// Copyright © 2026 Mikhail Hogrefe
2//
3// Uses code adopted from the GNU MPFR Library.
4//
5// Copyright © 1999-2024 Free Software Foundation, Inc.
6//
7// Contributed by the AriC and Caramba projects, INRIA.
8//
9// This file is part of Malachite.
10//
11// Malachite is free software: you can redistribute it and/or modify it under the terms of the GNU
12// Lesser General Public License (LGPL) as published by the Free Software Foundation; either version
13// 3 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>.
14
15use crate::Float;
16use crate::InnerFloat::{Finite, Infinity, NaN, Zero};
17use crate::float::conversion::string::get_str_data::MPFR_L2B;
18use crate::floor_and_ceiling;
19use alloc::vec;
20use alloc::vec::Vec;
21use core::cmp::Ordering::{self, Equal};
22use malachite_base::fail_on_untested_path;
23use malachite_base::num::arithmetic::traits::{CeilingLogBase2, CheckedLogBase2, NegAssign, Sign};
24use malachite_base::num::basic::integers::PrimitiveInt;
25use malachite_base::num::conversion::traits::{ExactFrom, RoundingFrom};
26use malachite_base::rounding_modes::RoundingMode::{self, Ceiling, Exact, Floor};
27use malachite_nz::natural::Natural;
28use malachite_nz::natural::arithmetic::float_extras::{limbs_get_str, limbs_get_str_power_of_2};
29
30// Returns `ceil(e * log2(beta) ^ ((-1) ^ i))`, or that plus 1. For `i == 0` it uses a 23-bit upper
31// approximation to `log(beta) / log(2)`; for `i == 1` a 77-bit upper approximation to `log(2) /
32// log(beta)`. Both approximations are entries of `MPFR_L2B`.
33//
34// This is `mpfr_ceil_mul` from `get_str.c`, MPFR 4.2.2.
35pub_crate_test! {ceil_mul(e: i64, beta: u64, i: usize) -> i64 {
36 const WIDTH_MINUS_1: u64 = i64::WIDTH - 1;
37 // p = mantissa * 2 ^ (exp - 128): the l2b approximation as an exact `Float`.
38 let (mantissa, exp) = MPFR_L2B[usize::exact_from(beta) - 2][i];
39 let p = Float::from_natural_prec(Natural::from(mantissa), 128).0
40 >> u64::exact_from(128 - i64::from(exp));
41 // t = e * p, with e as a `Float` with the precision of an `mpfr_exp_t` minus one, both
42 // roundings up.
43 let t = Float::from_signed_prec_round(e, WIDTH_MINUS_1, Ceiling)
44 .0
45 .mul_prec_round(p, WIDTH_MINUS_1, Ceiling)
46 .0;
47 // ceil(t).
48 i64::rounding_from(&t, Ceiling).0
49}}
50
51pub_crate_test! {
52// Returns at least `1 + ceil(bit_len * log(2) / log(base))` digits, where `bit_len` is the number
53// of bits of the mantissa, ensuring that converting the output back gives the same `Float`.
54//
55// `base` must be between 2 and 62, inclusive.
56//
57// This is `mpfr_get_str_ndigits` from `get_str.c`, MPFR 4.2.2.
58get_str_ndigits(base: u64, bit_len: u64) -> usize {
59 assert!((2..=62).contains(&base));
60 // Deal first with power-of-two bases, since even for those, `ceil_mul` might return a value too
61 // large by 1. For `base = 2 ^ k`, this is `1 + ceil((bit_len - 1) / k) = 2 + floor((bit_len -
62 // 2) / k)`.
63 if let Some(k) = base.checked_log_base_2() {
64 return usize::exact_from(1 + (bit_len + k - 2) / k);
65 }
66 // `ceil_mul` is guaranteed to give `1 + ceil(bit_len * log(2) / log(base))` for `bit_len` below
67 // this bound (for `bit_len = 186564318007` and `base = 7` or `49` it returns one more).
68 let ret = if bit_len < 186_564_318_007 {
69 u64::exact_from(ceil_mul(i64::exact_from(bit_len), base, 1))
70 } else {
71 // `bit_len` is large and `base` is not a power of two, so `bit_len * log(2) / log(base)`
72 // cannot be an integer and Ziv's loop terminates. `w` is the working precision; `ceil_mul`
73 // used a 77-bit upper approximation to `log(2) / log(base)`. Reaching here needs a mantissa
74 // of at least ~1.86e11 bits, far beyond any `Float` the test suite builds.
75 fail_on_untested_path("get_str_ndigits, Ziv loop for huge bit_len");
76 let mut w = 77;
77 loop {
78 w <<= 1;
79 // lower (rounding down) and upper (rounding up) approximations to `log2(base)`
80 let (log_lo, log_hi) =
81 floor_and_ceiling(Float::from_unsigned_prec(base, w).0.log_base_2_round(Floor));
82 // lower (`bit_len / log_hi`, rounding down) and upper (`bit_len / log_lo`, rounding up)
83 // bounds on `bit_len * log(2) / log(base)`, each rounded up to an integer
84 let pf = Float::from_unsigned_prec(bit_len, w).0;
85 let lo = u64::rounding_from(&pf.div_round_ref_val(log_hi, Floor).0, Ceiling).0;
86 let hi = u64::rounding_from(&pf.div_round(log_lo, Ceiling).0, Ceiling).0;
87 if lo == hi {
88 break lo;
89 }
90 }
91 };
92 usize::exact_from(1 + ret)
93}}
94
95/// Converts a [`Float`] to base-`base` mantissa digits and an exponent, rounding to `digit_len`
96/// digits with the rounding mode `rm`.
97///
98/// The digits are returned as ASCII characters (`0`–`9`, then lowercase `a`–`z`, then uppercase
99/// `A`–`Z`, supporting a `base` of up to 62; a negative `base` in `-36..=-2` uses base `|base|`
100/// with `0`–`9` and uppercase `A`–`Z`), preceded by `-` when `x` is negative. With the returned
101/// exponent $e$, the value represented is $0.d_1 d_2 \ldots \times \mathrm{base}^e$, where $d_1 d_2
102/// \ldots$ are the digits. If `digit_len` is 0, the fewest digits that round-trip back to `x` are
103/// used.
104///
105/// `base` must be in `2..=62` or `-36..=-2`; any other value returns `None`.
106///
107/// The returned [`Ordering`] reports whether the rounded result is less than, equal to, or greater
108/// than the exact value of `x`. The special values NaN, $\infty$, and $-\infty$ produce the strings
109/// `@NaN@`, `@Inf@`, and `-@Inf@`, each with exponent 0 and `Equal`.
110///
111/// # Worst-case complexity
112/// $T(n) = O(n (\log n)^2 \log\log n)$
113///
114/// $M(n) = O(n \log n)$
115///
116/// where $T$ is time, $M$ is additional memory, and $n$ is `max(x.complexity(), digit_len)`.
117///
118/// # Panics
119/// Panics if `rm` is `Exact` but `x` cannot be represented exactly in `digit_len` base-`base`
120/// digits.
121///
122/// # Examples
123/// ```
124/// use core::cmp::Ordering::*;
125/// use malachite_base::rounding_modes::RoundingMode::{self, *};
126/// use malachite_float::float::conversion::string::get_str::get_str;
127/// use malachite_float::Float;
128/// use malachite_q::Rational;
129///
130/// // Render the returned digit bytes as a `String` for readability.
131/// let s = |x: &Float, base: i64, n: usize, rm: RoundingMode| {
132/// get_str(x, base, n, rm)
133/// .map(|(digits, exp, ord)| (String::from_utf8(digits).unwrap(), exp, ord))
134/// };
135///
136/// // 1.25 to 3 digits: 0.125 * 10^1 in base 10, 0.101 * 2^1 in base 2, both exact.
137/// assert_eq!(
138/// s(&Float::from(1.25), 10, 3, Nearest),
139/// Some(("125".to_string(), 1, Equal))
140/// );
141/// assert_eq!(
142/// s(&Float::from(1.25), 2, 3, Nearest),
143/// Some(("101".to_string(), 1, Equal))
144/// );
145///
146/// // A negative value gets a leading `-`.
147/// assert_eq!(
148/// s(&Float::from(-1.25), 10, 3, Nearest),
149/// Some(("-125".to_string(), 1, Equal))
150/// );
151///
152/// // 1/3 (to 53 bits) has no finite base-10 expansion, so the result is rounded and the
153/// // `Ordering` gives the direction.
154/// let third = Float::from_rational_prec(Rational::from_unsigneds(1u32, 3u32), 53).0;
155/// assert_eq!(s(&third, 10, 4, Floor), Some(("3333".to_string(), 0, Less)));
156/// assert_eq!(
157/// s(&third, 10, 4, Ceiling),
158/// Some(("3334".to_string(), 0, Greater))
159/// );
160///
161/// // Special values produce fixed strings; an invalid base gives `None`.
162/// assert_eq!(
163/// s(&Float::from(f64::NAN), 2, 0, Down),
164/// Some(("@NaN@".to_string(), 0, Equal))
165/// );
166/// assert_eq!(
167/// s(&Float::from(f64::INFINITY), 2, 0, Down),
168/// Some(("@Inf@".to_string(), 0, Equal))
169/// );
170/// assert_eq!(s(&Float::from(1.25), 100, 0, Nearest), None);
171/// ```
172///
173/// This is mpfr_get_str from get_str.c, MPFR 4.2.2.
174pub fn get_str(
175 x: &Float,
176 base: i64,
177 digit_len: usize,
178 mut rm: RoundingMode,
179) -> Option<(Vec<u8>, i64, Ordering)> {
180 // valid bases are -36..=-2 and 2..=62
181 if !(-36..=-2).contains(&base) && !(2..=62).contains(&base) {
182 return None;
183 }
184 let b = base.unsigned_abs();
185 // `dir` is the direction in which the magnitude of `x` was rounded to the result (-1, 0, or 1).
186 let (neg, mut s, e, dir) = match &x.0 {
187 NaN => return Some((b"@NaN@".to_vec(), 0, Equal)),
188 Infinity { sign } => {
189 let s = if *sign {
190 b"@Inf@".to_vec()
191 } else {
192 b"-@Inf@".to_vec()
193 };
194 return Some((s, 0, Equal));
195 }
196 Zero { sign } => {
197 // Malachite's zero carries no precision, so the digit_len == 0 default
198 // (get_str_ndigits) does not apply; use a single digit.
199 (
200 !*sign,
201 vec![b'0'; if digit_len == 0 { 1 } else { digit_len }],
202 0,
203 0,
204 )
205 }
206 Finite {
207 sign,
208 exponent,
209 precision,
210 significand,
211 } => {
212 let m = if digit_len == 0 {
213 get_str_ndigits(b, *precision)
214 } else {
215 digit_len
216 };
217 // For a negative x, reduce to the magnitude by inverting the rounding direction (the
218 // mpfr_get_str MPFR_INVERT_RND step).
219 let neg = !*sign;
220 if neg {
221 rm.neg_assign();
222 }
223 // Malachite's `exponent` is MPFR's EXP (the scientific exponent plus one).
224 let xp = significand.to_limbs_asc();
225 let x_exp = i64::from(*exponent);
226 let (s, e, dir) = if b.is_power_of_two() {
227 limbs_get_str_power_of_2(&xp, x_exp, *precision, b, base, m, rm)
228 } else {
229 let g = ceil_mul(x_exp - 1, b, 1);
230 let exp = (i64::exact_from(m) - g).unsigned_abs();
231 // radix-2 precision needed for m digits in base b, plus guard bits
232 let mut prec = u64::exact_from(ceil_mul(i64::exact_from(m), b, 0)) + 1;
233 prec += prec.ceiling_log_base_2();
234 if exp != 0 {
235 // add the maximal exponentiation error
236 prec += 3 * exp.ceiling_log_base_2();
237 }
238 limbs_get_str(&xp, x_exp, b, base, m, rm, g, prec, i64::exact_from(exp))
239 };
240 (neg, s, e, dir)
241 }
242 };
243 // `Exact` demands that the digits represent `x` exactly; a nonzero `dir` means rounding was
244 // needed, which violates the contract. (For odd bases this is common, since a dyadic `Float`
245 // rarely has a finite expansion there; and `digit_len == 0` picks the round-trip digit count,
246 // which is generally fewer than the exact expansion needs.)
247 assert!(
248 rm != Exact || dir == 0,
249 "get_str: Exact rounding was requested, but {x} is not exactly representable in the \
250 requested number of base-{base} digits"
251 );
252 // `dir` orders the result's magnitude against `|x|`; negating both reverses the order.
253 let o = dir.sign();
254 Some(if neg {
255 s.insert(0, b'-');
256 (s, e, o.reverse())
257 } else {
258 (s, e, o)
259 })
260}