Skip to content

Commit fe967e0

Browse files
Xanewokxlc
authored andcommitted
Add a convenience no_std method to get a f64 out of NumberValue (#8)
1 parent d50dc90 commit fe967e0

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

Cargo.toml

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,10 @@ edition = "2018"
66

77
[dependencies]
88
paste = "0.1"
9+
num-traits = { version = "0.2", optional = true, default-features = false }
910

1011
[features]
1112
default = ["std"]
12-
std = []
13+
std = []
14+
# Enables converting values to floats in no-`std` environment
15+
float = ["num-traits"]

src/json.rs

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -203,9 +203,20 @@ pub struct NumberValue {
203203
pub exponent: i32,
204204
}
205205

206-
#[cfg(feature = "std")]
206+
impl NumberValue {
207+
/// Losslessly convert the inner value to `f64`.
208+
#[cfg(any(feature = "std", feature = "float"))]
209+
pub fn to_f64(self) -> f64 {
210+
self.into()
211+
}
212+
}
213+
214+
#[cfg(any(feature = "std", feature = "float"))]
207215
impl Into<f64> for NumberValue {
208216
fn into(self) -> f64 {
217+
#[cfg(not(feature = "std"))]
218+
use num_traits::float::FloatCore as _;
219+
209220
(self.integer as f64 + self.fraction as f64 / 10f64.powi(self.fraction_length as i32))
210221
* 10f64.powi(self.exponent)
211222
}

0 commit comments

Comments
 (0)