ryu/common.rs
1// Translated from C to Rust. The original C code can be found at
2// https://github.com/ulfjack/ryu and carries the following license:
3//
4// Copyright 2018 Ulf Adams
5//
6// The contents of this file may be used under the terms of the Apache License,
7// Version 2.0.
8//
9// (See accompanying file LICENSE-Apache or copy at
10// http://www.apache.org/licenses/LICENSE-2.0)
11//
12// Alternatively, the contents of this file may be used under the terms of
13// the Boost Software License, Version 1.0.
14// (See accompanying file LICENSE-Boost or copy at
15// https://www.boost.org/LICENSE_1_0.txt)
16//
17// Unless required by applicable law or agreed to in writing, this software
18// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
19// KIND, either express or implied.
20
21#[cfg_attr(feature = "no-panic", inline)]
22pub fn decimal_length9(v: u32) -> u32 {
23 // Function precondition: v is not a 10-digit number.
24 // (f2s: 9 digits are sufficient for round-tripping.)
25 debug_assert!(v < 1000000000);
26
27 if v >= 100000000 {
28 9
29 } else if v >= 10000000 {
30 8
31 } else if v >= 1000000 {
32 7
33 } else if v >= 100000 {
34 6
35 } else if v >= 10000 {
36 5
37 } else if v >= 1000 {
38 4
39 } else if v >= 100 {
40 3
41 } else if v >= 10 {
42 2
43 } else {
44 1
45 }
46}
47
48// Returns e == 0 ? 1 : ceil(log_2(5^e)).
49#[cfg_attr(feature = "no-panic", inline)]
50pub fn pow5bits(e: i32) -> i32 {
51 // This approximation works up to the point that the multiplication overflows at e = 3529.
52 // If the multiplication were done in 64 bits, it would fail at 5^4004 which is just greater
53 // than 2^9297.
54 debug_assert!(e >= 0);
55 debug_assert!(e <= 3528);
56 (((e as u32 * 1217359) >> 19) + 1) as i32
57}
58
59// Returns floor(log_10(2^e)).
60#[cfg_attr(feature = "no-panic", inline)]
61pub fn log10_pow2(e: i32) -> u32 {
62 // The first value this approximation fails for is 2^1651 which is just greater than 10^297.
63 debug_assert!(e >= 0);
64 debug_assert!(e <= 1650);
65 (e as u32 * 78913) >> 18
66}
67
68// Returns floor(log_10(5^e)).
69#[cfg_attr(feature = "no-panic", inline)]
70pub fn log10_pow5(e: i32) -> u32 {
71 // The first value this approximation fails for is 5^2621 which is just greater than 10^1832.
72 debug_assert!(e >= 0);
73 debug_assert!(e <= 2620);
74 (e as u32 * 732923) >> 20
75}