| 1 |
use crate::Decimal; |
| 2 |
use alloc::string::ToString; |
| 3 |
use core::{fmt, str::FromStr}; |
| 4 |
use num_traits::FromPrimitive; |
| 5 |
use serde::{self, de::Unexpected}; |
| 6 |
|
| 7 |
/// Serialize/deserialize Decimals as arbitrary precision numbers in JSON using the `arbitrary_precision` feature within `serde_json`. |
| 8 |
/// |
| 9 |
/// ``` |
| 10 |
/// # use serde::{Serialize, Deserialize}; |
| 11 |
/// # use rust_decimal::Decimal; |
| 12 |
/// # use std::str::FromStr; |
| 13 |
/// |
| 14 |
/// #[derive(Serialize, Deserialize)] |
| 15 |
/// pub struct ArbitraryExample { |
| 16 |
/// #[serde(with = "rust_decimal::serde::arbitrary_precision")] |
| 17 |
/// value: Decimal, |
| 18 |
/// } |
| 19 |
/// |
| 20 |
/// let value = ArbitraryExample { value: Decimal::from_str("123.400").unwrap() }; |
| 21 |
/// assert_eq!( |
| 22 |
/// &serde_json::to_string(&value).unwrap(), |
| 23 |
/// r#"{"value":123.400}"# |
| 24 |
/// ); |
| 25 |
/// ``` |
| 26 |
#[cfg(feature = "serde-with-arbitrary-precision")] |
| 27 |
pub mod arbitrary_precision { |
| 28 |
use super::*; |
| 29 |
use serde::Serialize; |
| 30 |
|
| 31 |
pub fn deserialize<'de, D>(deserializer: D) -> Result<Decimal, D::Error> |
| 32 |
where |
| 33 |
D: serde::de::Deserializer<'de>, |
| 34 |
{ |
| 35 |
deserializer.deserialize_any(DecimalVisitor) |
| 36 |
} |
| 37 |
|
| 38 |
pub fn serialize<S>(value: &Decimal, serializer: S) -> Result<S::Ok, S::Error> |
| 39 |
where |
| 40 |
S: serde::Serializer, |
| 41 |
{ |
| 42 |
serde_json::Number::from_str(&value.to_string()) |
| 43 |
.map_err(serde::ser::Error::custom)? |
| 44 |
.serialize(serializer) |
| 45 |
} |
| 46 |
} |
| 47 |
|
| 48 |
/// Serialize/deserialize optional Decimals as arbitrary precision numbers in JSON using the `arbitrary_precision` feature within `serde_json`. |
| 49 |
/// |
| 50 |
/// ``` |
| 51 |
/// # use serde::{Serialize, Deserialize}; |
| 52 |
/// # use rust_decimal::Decimal; |
| 53 |
/// # use std::str::FromStr; |
| 54 |
/// |
| 55 |
/// #[derive(Serialize, Deserialize)] |
| 56 |
/// pub struct ArbitraryExample { |
| 57 |
/// #[serde(with = "rust_decimal::serde::arbitrary_precision_option")] |
| 58 |
/// value: Option<Decimal>, |
| 59 |
/// } |
| 60 |
/// |
| 61 |
/// let value = ArbitraryExample { value: Some(Decimal::from_str("123.400").unwrap()) }; |
| 62 |
/// assert_eq!( |
| 63 |
/// &serde_json::to_string(&value).unwrap(), |
| 64 |
/// r#"{"value":123.400}"# |
| 65 |
/// ); |
| 66 |
/// |
| 67 |
/// let value = ArbitraryExample { value: None }; |
| 68 |
/// assert_eq!( |
| 69 |
/// &serde_json::to_string(&value).unwrap(), |
| 70 |
/// r#"{"value":null}"# |
| 71 |
/// ); |
| 72 |
/// ``` |
| 73 |
#[cfg(feature = "serde-with-arbitrary-precision")] |
| 74 |
pub mod arbitrary_precision_option { |
| 75 |
use super::*; |
| 76 |
use serde::Serialize; |
| 77 |
|
| 78 |
pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<Decimal>, D::Error> |
| 79 |
where |
| 80 |
D: serde::de::Deserializer<'de>, |
| 81 |
{ |
| 82 |
deserializer.deserialize_option(OptionDecimalVisitor) |
| 83 |
} |
| 84 |
|
| 85 |
pub fn serialize<S>(value: &Option<Decimal>, serializer: S) -> Result<S::Ok, S::Error> |
| 86 |
where |
| 87 |
S: serde::Serializer, |
| 88 |
{ |
| 89 |
match *value { |
| 90 |
Some(ref decimal) => serde_json::Number::from_str(&decimal.to_string()) |
| 91 |
.map_err(serde::ser::Error::custom)? |
| 92 |
.serialize(serializer), |
| 93 |
None => serializer.serialize_none(), |
| 94 |
} |
| 95 |
} |
| 96 |
} |
| 97 |
|
| 98 |
/// Serialize/deserialize Decimals as floats. |
| 99 |
/// |
| 100 |
/// ``` |
| 101 |
/// # use serde::{Serialize, Deserialize}; |
| 102 |
/// # use rust_decimal::Decimal; |
| 103 |
/// # use std::str::FromStr; |
| 104 |
/// |
| 105 |
/// #[derive(Serialize, Deserialize)] |
| 106 |
/// pub struct FloatExample { |
| 107 |
/// #[serde(with = "rust_decimal::serde::float")] |
| 108 |
/// value: Decimal, |
| 109 |
/// } |
| 110 |
/// |
| 111 |
/// let value = FloatExample { value: Decimal::from_str("123.400").unwrap() }; |
| 112 |
/// assert_eq!( |
| 113 |
/// &serde_json::to_string(&value).unwrap(), |
| 114 |
/// r#"{"value":123.4}"# |
| 115 |
/// ); |
| 116 |
/// ``` |
| 117 |
#[cfg(feature = "serde-with-float")] |
| 118 |
pub mod float { |
| 119 |
use super::*; |
| 120 |
use serde::Serialize; |
| 121 |
|
| 122 |
pub fn deserialize<'de, D>(deserializer: D) -> Result<Decimal, D::Error> |
| 123 |
where |
| 124 |
D: serde::de::Deserializer<'de>, |
| 125 |
{ |
| 126 |
deserializer.deserialize_any(DecimalVisitor) |
| 127 |
} |
| 128 |
|
| 129 |
pub fn serialize<S>(value: &Decimal, serializer: S) -> Result<S::Ok, S::Error> |
| 130 |
where |
| 131 |
S: serde::Serializer, |
| 132 |
{ |
| 133 |
use num_traits::ToPrimitive; |
| 134 |
value.to_f64().unwrap().serialize(serializer) |
| 135 |
} |
| 136 |
} |
| 137 |
|
| 138 |
/// Serialize/deserialize optional Decimals as floats. |
| 139 |
/// |
| 140 |
/// ``` |
| 141 |
/// # use serde::{Serialize, Deserialize}; |
| 142 |
/// # use rust_decimal::Decimal; |
| 143 |
/// # use std::str::FromStr; |
| 144 |
/// |
| 145 |
/// #[derive(Serialize, Deserialize)] |
| 146 |
/// pub struct FloatExample { |
| 147 |
/// #[serde(with = "rust_decimal::serde::float_option")] |
| 148 |
/// value: Option<Decimal>, |
| 149 |
/// } |
| 150 |
/// |
| 151 |
/// let value = FloatExample { value: Some(Decimal::from_str("123.400").unwrap()) }; |
| 152 |
/// assert_eq!( |
| 153 |
/// &serde_json::to_string(&value).unwrap(), |
| 154 |
/// r#"{"value":123.4}"# |
| 155 |
/// ); |
| 156 |
/// |
| 157 |
/// let value = FloatExample { value: None }; |
| 158 |
/// assert_eq!( |
| 159 |
/// &serde_json::to_string(&value).unwrap(), |
| 160 |
/// r#"{"value":null}"# |
| 161 |
/// ); |
| 162 |
/// ``` |
| 163 |
#[cfg(feature = "serde-with-float")] |
| 164 |
pub mod float_option { |
| 165 |
use super::*; |
| 166 |
use serde::Serialize; |
| 167 |
|
| 168 |
pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<Decimal>, D::Error> |
| 169 |
where |
| 170 |
D: serde::de::Deserializer<'de>, |
| 171 |
{ |
| 172 |
deserializer.deserialize_option(OptionDecimalVisitor) |
| 173 |
} |
| 174 |
|
| 175 |
pub fn serialize<S>(value: &Option<Decimal>, serializer: S) -> Result<S::Ok, S::Error> |
| 176 |
where |
| 177 |
S: serde::Serializer, |
| 178 |
{ |
| 179 |
match *value { |
| 180 |
Some(ref decimal) => { |
| 181 |
use num_traits::ToPrimitive; |
| 182 |
decimal.to_f64().unwrap().serialize(serializer) |
| 183 |
} |
| 184 |
None => serializer.serialize_none(), |
| 185 |
} |
| 186 |
} |
| 187 |
} |
| 188 |
|
| 189 |
/// Serialize/deserialize Decimals as strings. This is particularly useful when using binary encoding formats. |
| 190 |
/// |
| 191 |
/// ``` |
| 192 |
/// # use serde::{Serialize, Deserialize}; |
| 193 |
/// # use rust_decimal::Decimal; |
| 194 |
/// # use std::str::FromStr; |
| 195 |
/// |
| 196 |
/// #[derive(Serialize, Deserialize)] |
| 197 |
/// pub struct StringExample { |
| 198 |
/// #[serde(with = "rust_decimal::serde::str")] |
| 199 |
/// value: Decimal, |
| 200 |
/// } |
| 201 |
/// |
| 202 |
/// let value = StringExample { value: Decimal::from_str("123.400").unwrap() }; |
| 203 |
/// assert_eq!( |
| 204 |
/// &serde_json::to_string(&value).unwrap(), |
| 205 |
/// r#"{"value":"123.400"}"# |
| 206 |
/// ); |
| 207 |
/// |
| 208 |
/// ``` |
| 209 |
#[cfg(feature = "serde-with-str")] |
| 210 |
pub mod str { |
| 211 |
use super::*; |
| 212 |
|
| 213 |
pub fn deserialize<'de, D>(deserializer: D) -> Result<Decimal, D::Error> |
| 214 |
where |
| 215 |
D: serde::de::Deserializer<'de>, |
| 216 |
{ |
| 217 |
deserializer.deserialize_str(DecimalVisitor) |
| 218 |
} |
| 219 |
|
| 220 |
pub fn serialize<S>(value: &Decimal, serializer: S) -> Result<S::Ok, S::Error> |
| 221 |
where |
| 222 |
S: serde::Serializer, |
| 223 |
{ |
| 224 |
let value = crate::str::to_str_internal(value, true, None); |
| 225 |
serializer.serialize_str(value.0.as_ref()) |
| 226 |
} |
| 227 |
} |
| 228 |
|
| 229 |
/// Serialize/deserialize optional Decimals as strings. This is particularly useful when using binary encoding formats. |
| 230 |
/// |
| 231 |
/// ``` |
| 232 |
/// # use serde::{Serialize, Deserialize}; |
| 233 |
/// # use rust_decimal::Decimal; |
| 234 |
/// # use std::str::FromStr; |
| 235 |
/// |
| 236 |
/// #[derive(Serialize, Deserialize)] |
| 237 |
/// pub struct StringExample { |
| 238 |
/// #[serde(with = "rust_decimal::serde::str_option")] |
| 239 |
/// value: Option<Decimal>, |
| 240 |
/// } |
| 241 |
/// |
| 242 |
/// let value = StringExample { value: Some(Decimal::from_str("123.400").unwrap()) }; |
| 243 |
/// assert_eq!( |
| 244 |
/// &serde_json::to_string(&value).unwrap(), |
| 245 |
/// r#"{"value":"123.400"}"# |
| 246 |
/// ); |
| 247 |
/// |
| 248 |
/// let value = StringExample { value: None }; |
| 249 |
/// assert_eq!( |
| 250 |
/// &serde_json::to_string(&value).unwrap(), |
| 251 |
/// r#"{"value":null}"# |
| 252 |
/// ); |
| 253 |
/// ``` |
| 254 |
#[cfg(feature = "serde-with-str")] |
| 255 |
pub mod str_option { |
| 256 |
use super::*; |
| 257 |
|
| 258 |
pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<Decimal>, D::Error> |
| 259 |
where |
| 260 |
D: serde::de::Deserializer<'de>, |
| 261 |
{ |
| 262 |
deserializer.deserialize_option(OptionDecimalStrVisitor) |
| 263 |
} |
| 264 |
|
| 265 |
pub fn serialize<S>(value: &Option<Decimal>, serializer: S) -> Result<S::Ok, S::Error> |
| 266 |
where |
| 267 |
S: serde::Serializer, |
| 268 |
{ |
| 269 |
match *value { |
| 270 |
Some(ref decimal) => { |
| 271 |
let decimal = crate::str::to_str_internal(decimal, true, None); |
| 272 |
serializer.serialize_some(decimal.0.as_ref()) |
| 273 |
} |
| 274 |
None => serializer.serialize_none(), |
| 275 |
} |
| 276 |
} |
| 277 |
} |
| 278 |
|
| 279 |
#[cfg(not(feature = "serde-str"))] |
| 280 |
impl<'de> serde::Deserialize<'de> for Decimal { |
| 281 |
fn deserialize<D>(deserializer: D) -> Result<Decimal, D::Error> |
| 282 |
where |
| 283 |
D: serde::de::Deserializer<'de>, |
| 284 |
{ |
| 285 |
deserializer.deserialize_any(DecimalVisitor) |
| 286 |
} |
| 287 |
} |
| 288 |
|
| 289 |
#[cfg(all(feature = "serde-str", not(feature = "serde-float")))] |
| 290 |
impl<'de> serde::Deserialize<'de> for Decimal { |
| 291 |
fn deserialize<D>(deserializer: D) -> Result<Decimal, D::Error> |
| 292 |
where |
| 293 |
D: serde::de::Deserializer<'de>, |
| 294 |
{ |
| 295 |
deserializer.deserialize_str(DecimalVisitor) |
| 296 |
} |
| 297 |
} |
| 298 |
|
| 299 |
#[cfg(all(feature = "serde-str", feature = "serde-float"))] |
| 300 |
impl<'de> serde::Deserialize<'de> for Decimal { |
| 301 |
fn deserialize<D>(deserializer: D) -> Result<Decimal, D::Error> |
| 302 |
where |
| 303 |
D: serde::de::Deserializer<'de>, |
| 304 |
{ |
| 305 |
deserializer.deserialize_f64(DecimalVisitor) |
| 306 |
} |
| 307 |
} |
| 308 |
|
| 309 |
// It's a shame this needs to be redefined for this feature and not able to be referenced directly |
| 310 |
#[cfg(feature = "serde-with-arbitrary-precision")] |
| 311 |
const DECIMAL_KEY_TOKEN: &str = "$serde_json::private::Number"; |
| 312 |
|
| 313 |
struct DecimalVisitor; |
| 314 |
|
| 315 |
impl<'de> serde::de::Visitor<'de> for DecimalVisitor { |
| 316 |
type Value = Decimal; |
| 317 |
|
| 318 |
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { |
| 319 |
write!(formatter, "a Decimal type representing a fixed-point number") |
| 320 |
} |
| 321 |
|
| 322 |
fn visit_i64<E>(self, value: i64) -> Result<Decimal, E> |
| 323 |
where |
| 324 |
E: serde::de::Error, |
| 325 |
{ |
| 326 |
match Decimal::from_i64(value) { |
| 327 |
Some(s) => Ok(s), |
| 328 |
None => Err(E::invalid_value(Unexpected::Signed(value), &self)), |
| 329 |
} |
| 330 |
} |
| 331 |
|
| 332 |
fn visit_u64<E>(self, value: u64) -> Result<Decimal, E> |
| 333 |
where |
| 334 |
E: serde::de::Error, |
| 335 |
{ |
| 336 |
match Decimal::from_u64(value) { |
| 337 |
Some(s) => Ok(s), |
| 338 |
None => Err(E::invalid_value(Unexpected::Unsigned(value), &self)), |
| 339 |
} |
| 340 |
} |
| 341 |
|
| 342 |
fn visit_f64<E>(self, value: f64) -> Result<Decimal, E> |
| 343 |
where |
| 344 |
E: serde::de::Error, |
| 345 |
{ |
| 346 |
Decimal::from_str(&value.to_string()).map_err(|_| E::invalid_value(Unexpected::Float(value), &self)) |
| 347 |
} |
| 348 |
|
| 349 |
fn visit_str<E>(self, value: &str) -> Result<Decimal, E> |
| 350 |
where |
| 351 |
E: serde::de::Error, |
| 352 |
{ |
| 353 |
Decimal::from_str(value) |
| 354 |
.or_else(|_| Decimal::from_scientific(value)) |
| 355 |
.map_err(|_| E::invalid_value(Unexpected::Str(value), &self)) |
| 356 |
} |
| 357 |
|
| 358 |
#[cfg(feature = "serde-with-arbitrary-precision")] |
| 359 |
fn visit_map<A>(self, map: A) -> Result<Decimal, A::Error> |
| 360 |
where |
| 361 |
A: serde::de::MapAccess<'de>, |
| 362 |
{ |
| 363 |
let mut map = map; |
| 364 |
let value = map.next_key::<DecimalKey>()?; |
| 365 |
if value.is_none() { |
| 366 |
return Err(serde::de::Error::invalid_type(Unexpected::Map, &self)); |
| 367 |
} |
| 368 |
let v: DecimalFromString = map.next_value()?; |
| 369 |
Ok(v.value) |
| 370 |
} |
| 371 |
} |
| 372 |
|
| 373 |
struct OptionDecimalVisitor; |
| 374 |
|
| 375 |
impl<'de> serde::de::Visitor<'de> for OptionDecimalVisitor { |
| 376 |
type Value = Option<Decimal>; |
| 377 |
|
| 378 |
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { |
| 379 |
formatter.write_str("a Decimal type representing a fixed-point number") |
| 380 |
} |
| 381 |
|
| 382 |
fn visit_none<E>(self) -> Result<Option<Decimal>, E> |
| 383 |
where |
| 384 |
E: serde::de::Error, |
| 385 |
{ |
| 386 |
Ok(None) |
| 387 |
} |
| 388 |
|
| 389 |
#[cfg(all(feature = "serde-str", feature = "serde-float"))] |
| 390 |
fn visit_some<D>(self, d: D) -> Result<Option<Decimal>, D::Error> |
| 391 |
where |
| 392 |
D: serde::de::Deserializer<'de>, |
| 393 |
{ |
| 394 |
// We've got multiple types that we may see so we need to use any |
| 395 |
d.deserialize_any(DecimalVisitor).map(Some) |
| 396 |
} |
| 397 |
|
| 398 |
#[cfg(not(all(feature = "serde-str", feature = "serde-float")))] |
| 399 |
fn visit_some<D>(self, d: D) -> Result<Option<Decimal>, D::Error> |
| 400 |
where |
| 401 |
D: serde::de::Deserializer<'de>, |
| 402 |
{ |
| 403 |
<Decimal as serde::Deserialize>::deserialize(d).map(Some) |
| 404 |
} |
| 405 |
} |
| 406 |
|
| 407 |
#[cfg(feature = "serde-with-str")] |
| 408 |
struct OptionDecimalStrVisitor; |
| 409 |
|
| 410 |
#[cfg(feature = "serde-with-str")] |
| 411 |
impl<'de> serde::de::Visitor<'de> for OptionDecimalStrVisitor { |
| 412 |
type Value = Option<Decimal>; |
| 413 |
|
| 414 |
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { |
| 415 |
formatter.write_str("a Decimal type representing a fixed-point number") |
| 416 |
} |
| 417 |
|
| 418 |
fn visit_none<E>(self) -> Result<Option<Decimal>, E> |
| 419 |
where |
| 420 |
E: serde::de::Error, |
| 421 |
{ |
| 422 |
Ok(None) |
| 423 |
} |
| 424 |
|
| 425 |
fn visit_some<D>(self, d: D) -> Result<Option<Decimal>, D::Error> |
| 426 |
where |
| 427 |
D: serde::de::Deserializer<'de>, |
| 428 |
{ |
| 429 |
d.deserialize_str(DecimalVisitor).map(Some) |
| 430 |
} |
| 431 |
} |
| 432 |
|
| 433 |
#[cfg(feature = "serde-with-arbitrary-precision")] |
| 434 |
struct DecimalKey; |
| 435 |
|
| 436 |
#[cfg(feature = "serde-with-arbitrary-precision")] |
| 437 |
impl<'de> serde::de::Deserialize<'de> for DecimalKey { |
| 438 |
fn deserialize<D>(deserializer: D) -> Result<DecimalKey, D::Error> |
| 439 |
where |
| 440 |
D: serde::de::Deserializer<'de>, |
| 441 |
{ |
| 442 |
struct FieldVisitor; |
| 443 |
|
| 444 |
impl<'de> serde::de::Visitor<'de> for FieldVisitor { |
| 445 |
type Value = (); |
| 446 |
|
| 447 |
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { |
| 448 |
formatter.write_str("a valid decimal field") |
| 449 |
} |
| 450 |
|
| 451 |
fn visit_str<E>(self, s: &str) -> Result<(), E> |
| 452 |
where |
| 453 |
E: serde::de::Error, |
| 454 |
{ |
| 455 |
if s == DECIMAL_KEY_TOKEN { |
| 456 |
Ok(()) |
| 457 |
} else { |
| 458 |
Err(serde::de::Error::custom("expected field with custom name")) |
| 459 |
} |
| 460 |
} |
| 461 |
} |
| 462 |
|
| 463 |
deserializer.deserialize_identifier(FieldVisitor)?; |
| 464 |
Ok(DecimalKey) |
| 465 |
} |
| 466 |
} |
| 467 |
|
| 468 |
#[cfg(feature = "serde-with-arbitrary-precision")] |
| 469 |
pub struct DecimalFromString { |
| 470 |
pub value: Decimal, |
| 471 |
} |
| 472 |
|
| 473 |
#[cfg(feature = "serde-with-arbitrary-precision")] |
| 474 |
impl<'de> serde::de::Deserialize<'de> for DecimalFromString { |
| 475 |
fn deserialize<D>(deserializer: D) -> Result<DecimalFromString, D::Error> |
| 476 |
where |
| 477 |
D: serde::de::Deserializer<'de>, |
| 478 |
{ |
| 479 |
struct Visitor; |
| 480 |
|
| 481 |
impl<'de> serde::de::Visitor<'de> for Visitor { |
| 482 |
type Value = DecimalFromString; |
| 483 |
|
| 484 |
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { |
| 485 |
formatter.write_str("string containing a decimal") |
| 486 |
} |
| 487 |
|
| 488 |
fn visit_str<E>(self, value: &str) -> Result<DecimalFromString, E> |
| 489 |
where |
| 490 |
E: serde::de::Error, |
| 491 |
{ |
| 492 |
let d = Decimal::from_str(value) |
| 493 |
.or_else(|_| Decimal::from_scientific(value)) |
| 494 |
.map_err(serde::de::Error::custom)?; |
| 495 |
Ok(DecimalFromString { value: d }) |
| 496 |
} |
| 497 |
} |
| 498 |
|
| 499 |
deserializer.deserialize_str(Visitor) |
| 500 |
} |
| 501 |
} |
| 502 |
|
| 503 |
#[cfg(not(feature = "serde-float"))] |
| 504 |
impl serde::Serialize for Decimal { |
| 505 |
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> |
| 506 |
where |
| 507 |
S: serde::Serializer, |
| 508 |
{ |
| 509 |
let value = crate::str::to_str_internal(self, true, None); |
| 510 |
serializer.serialize_str(value.0.as_ref()) |
| 511 |
} |
| 512 |
} |
| 513 |
|
| 514 |
#[cfg(all(feature = "serde-float", not(feature = "serde-arbitrary-precision")))] |
| 515 |
impl serde::Serialize for Decimal { |
| 516 |
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> |
| 517 |
where |
| 518 |
S: serde::Serializer, |
| 519 |
{ |
| 520 |
use num_traits::ToPrimitive; |
| 521 |
serializer.serialize_f64(self.to_f64().unwrap()) |
| 522 |
} |
| 523 |
} |
| 524 |
|
| 525 |
#[cfg(all(feature = "serde-float", feature = "serde-arbitrary-precision"))] |
| 526 |
impl serde::Serialize for Decimal { |
| 527 |
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> |
| 528 |
where |
| 529 |
S: serde::Serializer, |
| 530 |
{ |
| 531 |
serde_json::Number::from_str(&self.to_string()) |
| 532 |
.map_err(serde::ser::Error::custom)? |
| 533 |
.serialize(serializer) |
| 534 |
} |
| 535 |
} |
| 536 |
|
| 537 |
#[cfg(test)] |
| 538 |
mod test { |
| 539 |
use super::*; |
| 540 |
use serde::{Deserialize, Serialize}; |
| 541 |
|
| 542 |
#[derive(Serialize, Deserialize, Debug)] |
| 543 |
struct Record { |
| 544 |
amount: Decimal, |
| 545 |
} |
| 546 |
|
| 547 |
#[test] |
| 548 |
#[cfg(not(feature = "serde-str"))] |
| 549 |
fn deserialize_valid_decimal() { |
| 550 |
let data = [ |
| 551 |
("{\"amount\":\"1.234\"}", "1.234"), |
| 552 |
("{\"amount\":1234}", "1234"), |
| 553 |
("{\"amount\":1234.56}", "1234.56"), |
| 554 |
("{\"amount\":\"1.23456e3\"}", "1234.56"), |
| 555 |
]; |
| 556 |
for &(serialized, value) in data.iter() { |
| 557 |
let result = serde_json::from_str(serialized); |
| 558 |
assert_eq!( |
| 559 |
true, |
| 560 |
result.is_ok(), |
| 561 |
"expected successful deserialization for {}. Error: {:?}", |
| 562 |
serialized, |
| 563 |
result.err().unwrap() |
| 564 |
); |
| 565 |
let record: Record = result.unwrap(); |
| 566 |
assert_eq!( |
| 567 |
value, |
| 568 |
record.amount.to_string(), |
| 569 |
"expected: {}, actual: {}", |
| 570 |
value, |
| 571 |
record.amount.to_string() |
| 572 |
); |
| 573 |
} |
| 574 |
} |
| 575 |
|
| 576 |
#[test] |
| 577 |
#[cfg(feature = "serde-arbitrary-precision")] |
| 578 |
fn deserialize_basic_decimal() { |
| 579 |
let d: Decimal = serde_json::from_str("1.1234127836128763").unwrap(); |
| 580 |
// Typically, this would not work without this feature enabled due to rounding |
| 581 |
assert_eq!(d.to_string(), "1.1234127836128763"); |
| 582 |
} |
| 583 |
|
| 584 |
#[test] |
| 585 |
#[should_panic] |
| 586 |
fn deserialize_invalid_decimal() { |
| 587 |
let serialized = "{\"amount\":\"foo\"}"; |
| 588 |
let _: Record = serde_json::from_str(serialized).unwrap(); |
| 589 |
} |
| 590 |
|
| 591 |
#[test] |
| 592 |
#[cfg(not(feature = "serde-float"))] |
| 593 |
fn serialize_decimal() { |
| 594 |
let record = Record { |
| 595 |
amount: Decimal::new(1234, 3), |
| 596 |
}; |
| 597 |
let serialized = serde_json::to_string(&record).unwrap(); |
| 598 |
assert_eq!("{\"amount\":\"1.234\"}", serialized); |
| 599 |
} |
| 600 |
|
| 601 |
#[test] |
| 602 |
#[cfg(not(feature = "serde-float"))] |
| 603 |
fn serialize_negative_zero() { |
| 604 |
let record = Record { amount: -Decimal::ZERO }; |
| 605 |
let serialized = serde_json::to_string(&record).unwrap(); |
| 606 |
assert_eq!("{\"amount\":\"-0\"}", serialized); |
| 607 |
} |
| 608 |
|
| 609 |
#[test] |
| 610 |
#[cfg(feature = "serde-float")] |
| 611 |
fn serialize_decimal() { |
| 612 |
let record = Record { |
| 613 |
amount: Decimal::new(1234, 3), |
| 614 |
}; |
| 615 |
let serialized = serde_json::to_string(&record).unwrap(); |
| 616 |
assert_eq!("{\"amount\":1.234}", serialized); |
| 617 |
} |
| 618 |
|
| 619 |
#[test] |
| 620 |
#[cfg(all(feature = "serde-float", feature = "serde-arbitrary-precision"))] |
| 621 |
fn serialize_decimal_roundtrip() { |
| 622 |
let record = Record { |
| 623 |
// 4.81 is intentionally chosen as it is unrepresentable as a floating point number, meaning this test |
| 624 |
// would fail if the `serde-arbitrary-precision` was not activated. |
| 625 |
amount: Decimal::new(481, 2), |
| 626 |
}; |
| 627 |
let serialized = serde_json::to_string(&record).unwrap(); |
| 628 |
assert_eq!("{\"amount\":4.81}", serialized); |
| 629 |
let deserialized: Record = serde_json::from_str(&serialized).unwrap(); |
| 630 |
assert_eq!(record.amount, deserialized.amount); |
| 631 |
} |
| 632 |
|
| 633 |
#[test] |
| 634 |
#[cfg(all(feature = "serde-str", not(feature = "serde-float")))] |
| 635 |
fn serialize_decimal_roundtrip() { |
| 636 |
let record = Record { |
| 637 |
amount: Decimal::new(481, 2), |
| 638 |
}; |
| 639 |
let serialized = serde_json::to_string(&record).unwrap(); |
| 640 |
assert_eq!("{\"amount\":\"4.81\"}", serialized); |
| 641 |
let deserialized: Record = serde_json::from_str(&serialized).unwrap(); |
| 642 |
assert_eq!(record.amount, deserialized.amount); |
| 643 |
} |
| 644 |
|
| 645 |
#[test] |
| 646 |
#[cfg(all(feature = "serde-str", not(feature = "serde-float")))] |
| 647 |
fn bincode_serialization() { |
| 648 |
use bincode::{deserialize, serialize}; |
| 649 |
|
| 650 |
let data = [ |
| 651 |
"0", |
| 652 |
"0.00", |
| 653 |
"3.14159", |
| 654 |
"-3.14159", |
| 655 |
"1234567890123.4567890", |
| 656 |
"-1234567890123.4567890", |
| 657 |
"5233.9008808150288439427720175", |
| 658 |
"-5233.9008808150288439427720175", |
| 659 |
]; |
| 660 |
for &raw in data.iter() { |
| 661 |
let value = Decimal::from_str(raw).unwrap(); |
| 662 |
let encoded = serialize(&value).unwrap(); |
| 663 |
let decoded: Decimal = deserialize(&encoded[..]).unwrap(); |
| 664 |
assert_eq!(value, decoded); |
| 665 |
assert_eq!(8usize + raw.len(), encoded.len()); |
| 666 |
} |
| 667 |
} |
| 668 |
|
| 669 |
#[test] |
| 670 |
#[cfg(all(feature = "serde-str", feature = "serde-float"))] |
| 671 |
fn bincode_serialization() { |
| 672 |
use bincode::{deserialize, serialize}; |
| 673 |
|
| 674 |
let data = [ |
| 675 |
("0", "0"), |
| 676 |
("0.00", "0.00"), |
| 677 |
("3.14159", "3.14159"), |
| 678 |
("-3.14159", "-3.14159"), |
| 679 |
("1234567890123.4567890", "1234567890123.4568"), |
| 680 |
("-1234567890123.4567890", "-1234567890123.4568"), |
| 681 |
]; |
| 682 |
for &(value, expected) in data.iter() { |
| 683 |
let value = Decimal::from_str(value).unwrap(); |
| 684 |
let expected = Decimal::from_str(expected).unwrap(); |
| 685 |
let encoded = serialize(&value).unwrap(); |
| 686 |
let decoded: Decimal = deserialize(&encoded[..]).unwrap(); |
| 687 |
assert_eq!(expected, decoded); |
| 688 |
assert_eq!(8usize, encoded.len()); |
| 689 |
} |
| 690 |
} |
| 691 |
|
| 692 |
#[test] |
| 693 |
#[cfg(all(feature = "serde-str", not(feature = "serde-float")))] |
| 694 |
fn bincode_nested_serialization() { |
| 695 |
// Issue #361 |
| 696 |
#[derive(Deserialize, Serialize, Debug)] |
| 697 |
pub struct Foo { |
| 698 |
value: Decimal, |
| 699 |
} |
| 700 |
|
| 701 |
let s = Foo { |
| 702 |
value: Decimal::new(-1, 3).round_dp(0), |
| 703 |
}; |
| 704 |
let ser = bincode::serialize(&s).unwrap(); |
| 705 |
let des: Foo = bincode::deserialize(&ser).unwrap(); |
| 706 |
assert_eq!(des.value, s.value); |
| 707 |
} |
| 708 |
|
| 709 |
#[test] |
| 710 |
#[cfg(feature = "serde-with-arbitrary-precision")] |
| 711 |
fn with_arbitrary_precision() { |
| 712 |
#[derive(Serialize, Deserialize)] |
| 713 |
pub struct ArbitraryExample { |
| 714 |
#[serde(with = "crate::serde::arbitrary_precision")] |
| 715 |
value: Decimal, |
| 716 |
} |
| 717 |
|
| 718 |
let value = ArbitraryExample { |
| 719 |
value: Decimal::from_str("123.400").unwrap(), |
| 720 |
}; |
| 721 |
assert_eq!(&serde_json::to_string(&value).unwrap(), r#"{"value":123.400}"#); |
| 722 |
} |
| 723 |
|
| 724 |
#[test] |
| 725 |
#[cfg(feature = "serde-with-arbitrary-precision")] |
| 726 |
fn with_arbitrary_precision_from_string() { |
| 727 |
#[derive(Serialize, Deserialize)] |
| 728 |
pub struct ArbitraryExample { |
| 729 |
#[serde(with = "crate::serde::arbitrary_precision")] |
| 730 |
value: Decimal, |
| 731 |
} |
| 732 |
|
| 733 |
let value: ArbitraryExample = serde_json::from_str(r#"{"value":"1.1234127836128763"}"#).unwrap(); |
| 734 |
assert_eq!(value.value.to_string(), "1.1234127836128763"); |
| 735 |
} |
| 736 |
|
| 737 |
#[test] |
| 738 |
#[cfg(feature = "serde-with-float")] |
| 739 |
fn with_float() { |
| 740 |
#[derive(Serialize, Deserialize)] |
| 741 |
pub struct FloatExample { |
| 742 |
#[serde(with = "crate::serde::float")] |
| 743 |
value: Decimal, |
| 744 |
} |
| 745 |
|
| 746 |
let value = FloatExample { |
| 747 |
value: Decimal::from_str("123.400").unwrap(), |
| 748 |
}; |
| 749 |
assert_eq!(&serde_json::to_string(&value).unwrap(), r#"{"value":123.4}"#); |
| 750 |
} |
| 751 |
|
| 752 |
#[test] |
| 753 |
#[cfg(feature = "serde-with-str")] |
| 754 |
fn with_str() { |
| 755 |
#[derive(Serialize, Deserialize)] |
| 756 |
pub struct StringExample { |
| 757 |
#[serde(with = "crate::serde::str")] |
| 758 |
value: Decimal, |
| 759 |
} |
| 760 |
|
| 761 |
let value = StringExample { |
| 762 |
value: Decimal::from_str("123.400").unwrap(), |
| 763 |
}; |
| 764 |
assert_eq!(&serde_json::to_string(&value).unwrap(), r#"{"value":"123.400"}"#); |
| 765 |
} |
| 766 |
|
| 767 |
#[test] |
| 768 |
#[cfg(feature = "serde-with-str")] |
| 769 |
fn with_str_bincode() { |
| 770 |
use bincode::{deserialize, serialize}; |
| 771 |
|
| 772 |
#[derive(Serialize, Deserialize)] |
| 773 |
struct BincodeExample { |
| 774 |
#[serde(with = "crate::serde::str")] |
| 775 |
value: Decimal, |
| 776 |
} |
| 777 |
|
| 778 |
let data = [ |
| 779 |
("0", "0"), |
| 780 |
("0.00", "0.00"), |
| 781 |
("1.234", "1.234"), |
| 782 |
("3.14159", "3.14159"), |
| 783 |
("-3.14159", "-3.14159"), |
| 784 |
("1234567890123.4567890", "1234567890123.4567890"), |
| 785 |
("-1234567890123.4567890", "-1234567890123.4567890"), |
| 786 |
]; |
| 787 |
for &(value, expected) in data.iter() { |
| 788 |
let value = Decimal::from_str(value).unwrap(); |
| 789 |
let expected = Decimal::from_str(expected).unwrap(); |
| 790 |
let input = BincodeExample { value }; |
| 791 |
|
| 792 |
let encoded = serialize(&input).unwrap(); |
| 793 |
let decoded: BincodeExample = deserialize(&encoded[..]).unwrap(); |
| 794 |
assert_eq!(expected, decoded.value); |
| 795 |
} |
| 796 |
} |
| 797 |
|
| 798 |
#[test] |
| 799 |
#[cfg(feature = "serde-with-str")] |
| 800 |
fn with_str_bincode_optional() { |
| 801 |
use bincode::{deserialize, serialize}; |
| 802 |
|
| 803 |
#[derive(Serialize, Deserialize)] |
| 804 |
struct BincodeExample { |
| 805 |
#[serde(with = "crate::serde::str_option")] |
| 806 |
value: Option<Decimal>, |
| 807 |
} |
| 808 |
|
| 809 |
// Some(value) |
| 810 |
let value = Some(Decimal::new(1234, 3)); |
| 811 |
let input = BincodeExample { value }; |
| 812 |
let encoded = serialize(&input).unwrap(); |
| 813 |
let decoded: BincodeExample = deserialize(&encoded[..]).unwrap(); |
| 814 |
assert_eq!(value, decoded.value, "Some(value)"); |
| 815 |
|
| 816 |
// None |
| 817 |
let input = BincodeExample { value: None }; |
| 818 |
let encoded = serialize(&input).unwrap(); |
| 819 |
let decoded: BincodeExample = deserialize(&encoded[..]).unwrap(); |
| 820 |
assert_eq!(None, decoded.value, "None"); |
| 821 |
} |
| 822 |
|
| 823 |
#[test] |
| 824 |
#[cfg(feature = "serde-with-str")] |
| 825 |
fn with_str_optional() { |
| 826 |
#[derive(Serialize, Deserialize)] |
| 827 |
pub struct StringExample { |
| 828 |
#[serde(with = "crate::serde::str_option")] |
| 829 |
value: Option<Decimal>, |
| 830 |
} |
| 831 |
|
| 832 |
let original = StringExample { |
| 833 |
value: Some(Decimal::from_str("123.400").unwrap()), |
| 834 |
}; |
| 835 |
assert_eq!(&serde_json::to_string(&original).unwrap(), r#"{"value":"123.400"}"#); |
| 836 |
let deserialized: StringExample = serde_json::from_str(r#"{"value":"123.400"}"#).unwrap(); |
| 837 |
assert_eq!(deserialized.value, original.value); |
| 838 |
assert!(deserialized.value.is_some()); |
| 839 |
assert_eq!(deserialized.value.unwrap().unpack(), original.value.unwrap().unpack()); |
| 840 |
|
| 841 |
// Null tests |
| 842 |
let original = StringExample { value: None }; |
| 843 |
assert_eq!(&serde_json::to_string(&original).unwrap(), r#"{"value":null}"#); |
| 844 |
let deserialized: StringExample = serde_json::from_str(r#"{"value":null}"#).unwrap(); |
| 845 |
assert_eq!(deserialized.value, original.value); |
| 846 |
assert!(deserialized.value.is_none()); |
| 847 |
} |
| 848 |
|
| 849 |
#[test] |
| 850 |
#[cfg(feature = "serde-with-float")] |
| 851 |
fn with_float_optional() { |
| 852 |
#[derive(Serialize, Deserialize)] |
| 853 |
pub struct StringExample { |
| 854 |
#[serde(with = "crate::serde::float_option")] |
| 855 |
value: Option<Decimal>, |
| 856 |
} |
| 857 |
|
| 858 |
let original = StringExample { |
| 859 |
value: Some(Decimal::from_str("123.400").unwrap()), |
| 860 |
}; |
| 861 |
assert_eq!(&serde_json::to_string(&original).unwrap(), r#"{"value":123.4}"#); |
| 862 |
let deserialized: StringExample = serde_json::from_str(r#"{"value":123.4}"#).unwrap(); |
| 863 |
assert_eq!(deserialized.value, original.value); |
| 864 |
assert!(deserialized.value.is_some()); // Scale is different! |
| 865 |
|
| 866 |
// Null tests |
| 867 |
let original = StringExample { value: None }; |
| 868 |
assert_eq!(&serde_json::to_string(&original).unwrap(), r#"{"value":null}"#); |
| 869 |
let deserialized: StringExample = serde_json::from_str(r#"{"value":null}"#).unwrap(); |
| 870 |
assert_eq!(deserialized.value, original.value); |
| 871 |
assert!(deserialized.value.is_none()); |
| 872 |
} |
| 873 |
|
| 874 |
#[test] |
| 875 |
#[cfg(feature = "serde-with-arbitrary-precision")] |
| 876 |
fn with_arbitrary_precision_optional() { |
| 877 |
#[derive(Serialize, Deserialize)] |
| 878 |
pub struct StringExample { |
| 879 |
#[serde(with = "crate::serde::arbitrary_precision_option")] |
| 880 |
value: Option<Decimal>, |
| 881 |
} |
| 882 |
|
| 883 |
let original = StringExample { |
| 884 |
value: Some(Decimal::from_str("123.400").unwrap()), |
| 885 |
}; |
| 886 |
assert_eq!(&serde_json::to_string(&original).unwrap(), r#"{"value":123.400}"#); |
| 887 |
let deserialized: StringExample = serde_json::from_str(r#"{"value":123.400}"#).unwrap(); |
| 888 |
assert_eq!(deserialized.value, original.value); |
| 889 |
assert!(deserialized.value.is_some()); |
| 890 |
assert_eq!(deserialized.value.unwrap().unpack(), original.value.unwrap().unpack()); |
| 891 |
|
| 892 |
// Null tests |
| 893 |
let original = StringExample { value: None }; |
| 894 |
assert_eq!(&serde_json::to_string(&original).unwrap(), r#"{"value":null}"#); |
| 895 |
let deserialized: StringExample = serde_json::from_str(r#"{"value":null}"#).unwrap(); |
| 896 |
assert_eq!(deserialized.value, original.value); |
| 897 |
assert!(deserialized.value.is_none()); |
| 898 |
} |
| 899 |
} |