1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
use core::fmt::Formatter;
use crate::num::BigFloatNumber;
use crate::{BigFloat, Radix, RoundingMode};
use serde::de::Error;
use serde::de::Visitor;
use serde::{Deserialize, Deserializer};
#[cfg(not(feature = "std"))]
use {alloc::format, alloc::string::String};
pub struct BigFloatVisitor {}
impl<'de> Deserialize<'de> for BigFloat {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
deserializer.deserialize_any(BigFloatVisitor {})
}
}
impl<'de> Visitor<'de> for BigFloatVisitor {
type Value = BigFloat;
fn expecting(&self, formatter: &mut Formatter) -> core::fmt::Result {
write!(formatter, "except `String`, `Number`, `Bytes`")
}
fn visit_u64<E: Error>(self, v: u64) -> Result<Self::Value, E> {
match BigFloatNumber::from_usize(v as usize) {
Ok(o) => Ok(o.into()),
Err(e) => Err(Error::custom(format!("{e:?}"))),
}
}
fn visit_f32<E: Error>(self, v: f32) -> Result<Self::Value, E> {
match BigFloatNumber::from_f32(64, v) {
Ok(o) => Ok(o.into()),
Err(e) => Err(Error::custom(format!("{e:?}"))),
}
}
fn visit_f64<E: Error>(self, v: f64) -> Result<Self::Value, E> {
match BigFloatNumber::from_f64(64, v) {
Ok(o) => Ok(o.into()),
Err(e) => Err(Error::custom(format!("{e:?}"))),
}
}
fn visit_str<E: Error>(self, v: &str) -> Result<Self::Value, E> {
match BigFloatNumber::parse(v, Radix::Dec, 64, RoundingMode::None) {
Ok(o) => Ok(o.into()),
Err(e) => Err(Error::custom(format!("{e:?}"))),
}
}
fn visit_string<E: Error>(self, v: String) -> Result<Self::Value, E> {
self.visit_str(&v)
}
}
#[cfg(test)]
mod tests {
use serde_json::from_str;
use crate::BigFloat;
#[cfg(not(feature = "std"))]
use alloc::format;
#[test]
fn from_json() {
assert_eq!("0.0", format!("{}", from_str::<BigFloat>("-0").unwrap()));
assert_eq!("0.0", format!("{}", from_str::<BigFloat>("0.0").unwrap()));
assert_eq!(
"2.99999999999999988897e-1",
format!("{}", from_str::<BigFloat>("0.3").unwrap())
);
assert_eq!(
"2.99999999999999999983e-1",
format!("{}", from_str::<BigFloat>("\"0.3\"").unwrap())
);
}
}