Function core::num::flt2dec::estimate_max_buf_len
source · fn estimate_max_buf_len(exp: i16) -> usize
flt2dec
)Expand description
Returns a rather crude approximation (upper bound) for the maximum buffer size calculated from the given decoded exponent.
The exact limit is:
- when
exp < 0
, the maximum length isceil(log_10 (5^-exp * (2^64 - 1)))
. - when
exp >= 0
, the maximum length isceil(log_10 (2^exp * (2^64 - 1)))
.
ceil(log_10 (x^exp * (2^64 - 1)))
is less than ceil(log_10 (2^64 - 1)) + ceil(exp * log_10 x)
, which is in turn less than 20 + (1 + exp * log_10 x)
.
We use the facts that log_10 2 < 5/16
and log_10 5 < 12/16
, which is
enough for our purposes.
Why do we need this? format_exact
functions will fill the entire buffer
unless limited by the last digit restriction, but it is possible that
the number of digits requested is ridiculously large (say, 30,000 digits).
The vast majority of buffer will be filled with zeroes, so we don’t want to
allocate all the buffer beforehand. Consequently, for any given arguments,
826 bytes of buffer should be sufficient for f64
. Compare this with
the actual number for the worst case: 770 bytes (when exp = -1074
).