ryu_ecmascript/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
21use core::ptr;
22
23// Returns e == 0 ? 1 : ceil(log_2(5^e)).
24#[cfg_attr(feature = "no-panic", inline)]
25pub fn pow5bits(e: i32) -> u32 {
26 // This approximation works up to the point that the multiplication overflows at e = 3529.
27 // If the multiplication were done in 64 bits, it would fail at 5^4004 which is just greater
28 // than 2^9297.
29 debug_assert!(e >= 0);
30 debug_assert!(e <= 3528);
31 ((e as u32 * 1217359) >> 19) + 1
32}
33
34// Returns floor(log_10(2^e)).
35#[cfg_attr(feature = "no-panic", inline)]
36pub fn log10_pow2(e: i32) -> i32 {
37 // The first value this approximation fails for is 2^1651 which is just greater than 10^297.
38 debug_assert!(e >= 0);
39 debug_assert!(e <= 1650);
40 ((e as u32 * 78913) >> 18) as i32
41}
42
43// Returns floor(log_10(5^e)).
44#[cfg_attr(feature = "no-panic", inline)]
45pub fn log10_pow5(e: i32) -> i32 {
46 // The first value this approximation fails for is 5^2621 which is just greater than 10^1832.
47 debug_assert!(e >= 0);
48 debug_assert!(e <= 2620);
49 ((e as u32 * 732923) >> 20) as i32
50}
51
52#[cfg_attr(feature = "no-panic", inline)]
53pub unsafe fn copy_special_str(result: *mut u8,
54 sign: bool,
55 exponent: bool,
56 mantissa: bool)
57 -> usize {
58 if mantissa {
59 ptr::copy_nonoverlapping(b"NaN".as_ptr(), result, 3);
60 return 3;
61 }
62 if sign {
63 *result = b'-';
64 }
65 if exponent {
66 ptr::copy_nonoverlapping(b"Infinity".as_ptr(), result.offset(sign as isize), 8);
67 return sign as usize + 8;
68 }
69 ptr::copy_nonoverlapping(b"0E0".as_ptr(), result.offset(sign as isize), 3);
70 sign as usize + 3
71}