ryu_floating_decimal/
lib.rs

1//! This crate copies the internals of the [ryu rust crate](https://github.com/dtolnay/ryu), exposing some useful functions and types for more flexible float printing.
2//! This crate exposes the functions `d2d` and `f2d`, which convert from `f64` to `FloatingDecimal64` and `f32` to `FloatingDecimal32` respectively. These floating decimals can be converted to strings in a custom way.
3
4// License note: this main file is mostly unchanged, except for removing modules that
5// are no longer exported, and adding the exposed d2d and f2d functions. This module
6// is similarly provided under the terms of the Apache License, Version 2.0.
7
8#![no_std]
9#![doc(html_root_url = "https://docs.rs/ryu-floating-decimal/1.0.4")]
10#![cfg_attr(feature = "cargo-clippy", allow(renamed_and_removed_lints))]
11#![cfg_attr(
12    feature = "cargo-clippy",
13    allow(cast_lossless, many_single_char_names, unreadable_literal,)
14)]
15
16#[cfg(feature = "no-panic")]
17extern crate no_panic;
18
19mod common;
20mod d2s;
21#[cfg(not(feature = "small"))]
22mod d2s_full_table;
23mod d2s_intrinsics;
24#[cfg(feature = "small")]
25mod d2s_small_table;
26mod f2s;
27
28#[cfg(feature = "no-panic")]
29use no_panic::no_panic;
30
31pub use d2s::FloatingDecimal64;
32use core::mem;
33
34/// Convert an `f64` to a floating decimal using the ryu algorithm
35///
36/// # Example
37///
38/// ```
39/// use ryu_floating_decimal::d2d;
40/// let value: f64 = 3.14;
41/// let decimal = d2d(value);
42/// assert_eq!(decimal.mantissa, 314);
43/// assert_eq!(decimal.exponent, -2);
44/// ```
45#[cfg_attr(feature = "no-panic", inline)]
46#[cfg_attr(feature = "no-panic", no_panic)]
47pub fn d2d(val: f64) -> FloatingDecimal64 {
48    let bits: u64 = unsafe { mem::transmute(val) };
49    let ieee_mantissa = bits & ((1u64 << d2s::DOUBLE_MANTISSA_BITS) - 1);
50    let ieee_exponent =
51        (bits >> d2s::DOUBLE_MANTISSA_BITS) as u32 & ((1u32 << d2s::DOUBLE_EXPONENT_BITS) - 1);
52    d2s::d2d(ieee_mantissa, ieee_exponent)
53}
54
55pub use f2s::FloatingDecimal32;
56
57/// Convert an `f32` to a floating decimal using the ryu algorithm
58///
59/// # Example
60///
61/// ```
62/// use ryu_floating_decimal::f2d;
63/// let value: f32 = 12.091;
64/// let decimal = f2d(value);
65/// assert_eq!(decimal.mantissa, 12091);
66/// assert_eq!(decimal.exponent, -3);
67/// ```
68#[cfg_attr(feature = "no-panic", inline)]
69#[cfg_attr(feature = "no-panic", no_panic)]
70pub fn f2d(val: f32) -> FloatingDecimal32 {
71    let bits: u32 = unsafe { mem::transmute(val) };
72    let ieee_mantissa = bits & ((1u32 << f2s::FLOAT_MANTISSA_BITS) - 1);
73    let ieee_exponent =
74        (bits >> f2s::FLOAT_MANTISSA_BITS) as u32 & ((1u32 << f2s::FLOAT_EXPONENT_BITS) - 1);
75    f2s::f2d(ieee_mantissa, ieee_exponent)
76}