1 // Copyright 2017 Serde Developers
3 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6 // option. This file may not be copied, modified, or distributed
7 // except according to those terms.
10 use serde
::de
::{self, Visitor, Unexpected}
;
11 use serde
::{Serialize, Serializer, Deserialize, Deserializer}
;
12 use std
::fmt
::{self, Debug, Display}
;
14 use std
::str::FromStr
;
16 #[cfg(not(feature = "arbitrary_precision"))]
17 use num_traits
::{NumCast}
;
19 #[cfg(feature = "arbitrary_precision")]
21 #[cfg(feature = "arbitrary_precision")]
23 #[cfg(feature = "arbitrary_precision")]
24 use serde
::de
::{IntoDeserializer, MapAccess}
;
26 #[cfg(feature = "arbitrary_precision")]
27 use error
::{ErrorCode}
;
29 #[cfg(feature = "arbitrary_precision")]
30 /// Not public API. Should be pub(crate).
32 pub const SERDE_STRUCT_FIELD_NAME
: &'
static str = "$__serde_private_number";
34 #[cfg(feature = "arbitrary_precision")]
35 /// Not public API. Should be pub(crate).
37 pub const SERDE_STRUCT_NAME
: &'
static str = "$__serde_private_Number";
39 /// Represents a JSON number, whether integer or floating point.
40 #[derive(Clone, PartialEq)]
45 #[cfg(not(feature = "arbitrary_precision"))]
46 #[derive(Copy, Clone, PartialEq)]
49 /// Always less than zero.
55 #[cfg(feature = "arbitrary_precision")]
59 /// Returns true if the `Number` is an integer between `i64::MIN` and
62 /// For any Number on which `is_i64` returns true, `as_i64` is guaranteed to
63 /// return the integer value.
67 /// # extern crate serde_json;
72 /// let big = i64::MAX as u64 + 10;
73 /// let v = json!({ "a": 64, "b": big, "c": 256.0 });
75 /// assert!(v["a"].is_i64());
77 /// // Greater than i64::MAX.
78 /// assert!(!v["b"].is_i64());
80 /// // Numbers with a decimal point are not considered integers.
81 /// assert!(!v["c"].is_i64());
85 pub fn is_i64(&self) -> bool
{
86 #[cfg(not(feature = "arbitrary_precision"))]
88 N
::PosInt(v
) => v
<= i64::max_value() as u64,
92 #[cfg(feature = "arbitrary_precision")]
93 self.as_i64().is_some()
96 /// Returns true if the `Number` is an integer between zero and `u64::MAX`.
98 /// For any Number on which `is_u64` returns true, `as_u64` is guaranteed to
99 /// return the integer value.
103 /// # extern crate serde_json;
106 /// let v = json!({ "a": 64, "b": -64, "c": 256.0 });
108 /// assert!(v["a"].is_u64());
110 /// // Negative integer.
111 /// assert!(!v["b"].is_u64());
113 /// // Numbers with a decimal point are not considered integers.
114 /// assert!(!v["c"].is_u64());
118 pub fn is_u64(&self) -> bool
{
119 #[cfg(not(feature = "arbitrary_precision"))]
121 N
::PosInt(_
) => true,
122 N
::NegInt(_
) | N
::Float(_
) => false,
124 #[cfg(feature = "arbitrary_precision")]
125 self.as_u64().is_some()
128 /// Returns true if the `Number` can be represented by f64.
130 /// For any Number on which `is_f64` returns true, `as_f64` is guaranteed to
131 /// return the floating point value.
133 /// Currently this function returns true if and only if both `is_i64` and
134 /// `is_u64` return false but this is not a guarantee in the future.
138 /// # extern crate serde_json;
141 /// let v = json!({ "a": 256.0, "b": 64, "c": -64 });
143 /// assert!(v["a"].is_f64());
146 /// assert!(!v["b"].is_f64());
147 /// assert!(!v["c"].is_f64());
151 pub fn is_f64(&self) -> bool
{
152 #[cfg(not(feature = "arbitrary_precision"))]
155 N
::PosInt(_
) | N
::NegInt(_
) => false,
157 #[cfg(feature = "arbitrary_precision")]
159 for c
in self.n
.chars() {
160 if c
== '
.'
|| c
== 'e'
|| c
== 'E'
{
161 return self.n
.parse
::<f64>().ok()
162 .map_or(false, |f
| f
.is_finite());
169 /// If the `Number` is an integer, represent it as i64 if possible. Returns
174 /// # extern crate serde_json;
179 /// let big = i64::MAX as u64 + 10;
180 /// let v = json!({ "a": 64, "b": big, "c": 256.0 });
182 /// assert_eq!(v["a"].as_i64(), Some(64));
183 /// assert_eq!(v["b"].as_i64(), None);
184 /// assert_eq!(v["c"].as_i64(), None);
188 pub fn as_i64(&self) -> Option
<i64> {
189 #[cfg(not(feature = "arbitrary_precision"))]
191 N
::PosInt(n
) => NumCast
::from(n
),
192 N
::NegInt(n
) => Some(n
),
195 #[cfg(feature = "arbitrary_precision")]
199 /// If the `Number` is an integer, represent it as u64 if possible. Returns
204 /// # extern crate serde_json;
207 /// let v = json!({ "a": 64, "b": -64, "c": 256.0 });
209 /// assert_eq!(v["a"].as_u64(), Some(64));
210 /// assert_eq!(v["b"].as_u64(), None);
211 /// assert_eq!(v["c"].as_u64(), None);
215 pub fn as_u64(&self) -> Option
<u64> {
216 #[cfg(not(feature = "arbitrary_precision"))]
218 N
::PosInt(n
) => Some(n
),
219 N
::NegInt(n
) => NumCast
::from(n
),
222 #[cfg(feature = "arbitrary_precision")]
226 /// Represents the number as f64 if possible. Returns None otherwise.
230 /// # extern crate serde_json;
233 /// let v = json!({ "a": 256.0, "b": 64, "c": -64 });
235 /// assert_eq!(v["a"].as_f64(), Some(256.0));
236 /// assert_eq!(v["b"].as_f64(), Some(64.0));
237 /// assert_eq!(v["c"].as_f64(), Some(-64.0));
241 pub fn as_f64(&self) -> Option
<f64> {
242 #[cfg(not(feature = "arbitrary_precision"))]
244 N
::PosInt(n
) => NumCast
::from(n
),
245 N
::NegInt(n
) => NumCast
::from(n
),
246 N
::Float(n
) => Some(n
),
248 #[cfg(feature = "arbitrary_precision")]
252 /// Converts a finite `f64` to a `Number`. Infinite or NaN values are not JSON
258 /// # use serde_json::Number;
260 /// assert!(Number::from_f64(256.0).is_some());
262 /// assert!(Number::from_f64(f64::NAN).is_none());
265 pub fn from_f64(f
: f64) -> Option
<Number
> {
268 #[cfg(not(feature = "arbitrary_precision"))]
270 #[cfg(feature = "arbitrary_precision")]
272 let mut buf
= Vec
::new();
273 dtoa
::write(&mut buf
, f
).unwrap();
274 String
::from_utf8(buf
).unwrap()
277 Some(Number { n: n }
)
283 #[cfg(feature = "arbitrary_precision")]
284 /// Not public API. Only tests use this.
287 pub fn from_string_unchecked(n
: String
) -> Self {
292 impl fmt
::Display
for Number
{
293 #[cfg(not(feature = "arbitrary_precision"))]
294 fn fmt(&self, formatter
: &mut fmt
::Formatter
) -> fmt
::Result
{
296 N
::PosInt(u
) => Display
::fmt(&u
, formatter
),
297 N
::NegInt(i
) => Display
::fmt(&i
, formatter
),
298 N
::Float(f
) => Display
::fmt(&f
, formatter
),
302 #[cfg(feature = "arbitrary_precision")]
303 fn fmt(&self, formatter
: &mut fmt
::Formatter
) -> fmt
::Result
{
304 Display
::fmt(&self.n
, formatter
)
308 impl Debug
for Number
{
309 #[cfg(not(feature = "arbitrary_precision"))]
310 fn fmt(&self, formatter
: &mut fmt
::Formatter
) -> fmt
::Result
{
311 let mut debug
= formatter
.debug_tuple("Number");
326 #[cfg(feature = "arbitrary_precision")]
327 fn fmt(&self, formatter
: &mut fmt
::Formatter
) -> fmt
::Result
{
328 write
!(formatter
, "Number({})", &self.n
)
332 impl Serialize
for Number
{
333 #[cfg(not(feature = "arbitrary_precision"))]
335 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
340 N
::PosInt(u
) => serializer
.serialize_u64(u
),
341 N
::NegInt(i
) => serializer
.serialize_i64(i
),
342 N
::Float(f
) => serializer
.serialize_f64(f
),
346 #[cfg(feature = "arbitrary_precision")]
348 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
352 use serde
::ser
::SerializeStruct
;
354 let mut s
= serializer
.serialize_struct(SERDE_STRUCT_NAME
, 1)?
;
355 s
.serialize_field(SERDE_STRUCT_FIELD_NAME
, &self.n
)?
;
360 impl<'de
> Deserialize
<'de
> for Number
{
362 fn deserialize
<D
>(deserializer
: D
) -> Result
<Number
, D
::Error
>
364 D
: Deserializer
<'de
>,
366 struct NumberVisitor
;
368 impl<'de
> Visitor
<'de
> for NumberVisitor
{
371 fn expecting(&self, formatter
: &mut fmt
::Formatter
) -> fmt
::Result
{
372 formatter
.write_str("a JSON number")
376 fn visit_i64
<E
>(self, value
: i64) -> Result
<Number
, E
> {
381 fn visit_u64
<E
>(self, value
: u64) -> Result
<Number
, E
> {
386 fn visit_f64
<E
>(self, value
: f64) -> Result
<Number
, E
>
390 Number
::from_f64(value
).ok_or_else(|| de
::Error
::custom("not a JSON number"))
393 #[cfg(feature = "arbitrary_precision")]
395 fn visit_map
<V
>(self, mut visitor
: V
) -> Result
<Number
, V
::Error
>
397 V
: de
::MapAccess
<'de
>
399 let value
= visitor
.next_key
::<NumberKey
>()?
;
401 return Err(de
::Error
::invalid_type(Unexpected
::Map
, &self));
403 let v
: NumberFromString
= visitor
.next_value()?
;
408 deserializer
.deserialize_any(NumberVisitor
)
412 #[cfg(feature = "arbitrary_precision")]
415 #[cfg(feature = "arbitrary_precision")]
416 impl<'de
> de
::Deserialize
<'de
> for NumberKey
{
417 fn deserialize
<D
>(deserializer
: D
) -> Result
<NumberKey
, D
::Error
>
419 D
: de
::Deserializer
<'de
>
423 impl<'de
> de
::Visitor
<'de
> for FieldVisitor
{
426 fn expecting(&self, formatter
: &mut fmt
::Formatter
) -> fmt
::Result
{
427 formatter
.write_str("a valid number field")
430 fn visit_str
<E
>(self, s
: &str) -> Result
<(), E
>
433 if s
== SERDE_STRUCT_FIELD_NAME
{
436 Err(de
::Error
::custom("expected field with custom name"))
441 deserializer
.deserialize_identifier(FieldVisitor
)?
;
446 #[cfg(feature = "arbitrary_precision")]
447 pub struct NumberFromString
{
451 #[cfg(feature = "arbitrary_precision")]
452 impl<'de
> de
::Deserialize
<'de
> for NumberFromString
{
453 fn deserialize
<D
>(deserializer
: D
) -> Result
<NumberFromString
, D
::Error
>
455 D
: de
::Deserializer
<'de
>
459 impl<'de
> de
::Visitor
<'de
> for Visitor
{
460 type Value
= NumberFromString
;
462 fn expecting(&self, formatter
: &mut fmt
::Formatter
) -> fmt
::Result
{
463 formatter
.write_str("string containing a number")
466 fn visit_str
<E
>(self, s
: &str) -> Result
<NumberFromString
, E
>
469 let n
= try
!(s
.parse().map_err(de
::Error
::custom
));
470 Ok(NumberFromString { value: n }
)
474 deserializer
.deserialize_str(Visitor
)
478 #[cfg(feature = "arbitrary_precision")]
479 fn invalid_number() -> Error
{
480 Error
::syntax(ErrorCode
::InvalidNumber
, 0, 0)
483 macro_rules
! deserialize_any
{
484 (@expand
[$
($num_string
:tt
)*]) => {
485 #[cfg(not(feature = "arbitrary_precision"))]
487 fn deserialize_any
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Error
>
492 N
::PosInt(u
) => visitor
.visit_u64(u
),
493 N
::NegInt(i
) => visitor
.visit_i64(i
),
494 N
::Float(f
) => visitor
.visit_f64(f
),
498 #[cfg(feature = "arbitrary_precision")]
500 fn deserialize_any
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Error
>
501 where V
: Visitor
<'de
>
503 if let Some(u
) = self.as_u64() {
504 return visitor
.visit_u64(u
);
505 } else if let Some(i
) = self.as_i64() {
506 return visitor
.visit_i64(i
);
507 } else if let Some(f
) = self.as_f64() {
508 if f
.to_string() == self.n
{
509 return visitor
.visit_f64(f
);
513 visitor
.visit_map(NumberDeserializer
{
514 number
: Some(self.$
($num_string
)*),
520 deserialize_any
!(@expand
[n
]);
524 deserialize_any
!(@expand
[n
.clone()]);
528 macro_rules
! deserialize_number
{
529 ($deserialize
:ident
=> $visit
:ident
) => {
530 #[cfg(not(feature = "arbitrary_precision"))]
531 fn $deserialize
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Error
>
535 self.deserialize_any(visitor
)
538 #[cfg(feature = "arbitrary_precision")]
539 fn $deserialize
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Error
>
543 visitor
.$
visit(self.n
.parse().map_err(|_
| invalid_number())?
)
548 impl<'de
> Deserializer
<'de
> for Number
{
551 deserialize_any
!(owned
);
553 deserialize_number
!(deserialize_i8
=> visit_i8
);
554 deserialize_number
!(deserialize_i16
=> visit_i16
);
555 deserialize_number
!(deserialize_i32
=> visit_i32
);
556 deserialize_number
!(deserialize_i64
=> visit_i64
);
557 deserialize_number
!(deserialize_u8
=> visit_u8
);
558 deserialize_number
!(deserialize_u16
=> visit_u16
);
559 deserialize_number
!(deserialize_u32
=> visit_u32
);
560 deserialize_number
!(deserialize_u64
=> visit_u64
);
561 deserialize_number
!(deserialize_f32
=> visit_f32
);
562 deserialize_number
!(deserialize_f64
=> visit_f64
);
564 forward_to_deserialize_any
! {
565 bool
char str string bytes byte_buf option unit unit_struct
566 newtype_struct seq tuple tuple_struct map
struct enum identifier
571 impl<'de
, 'a
> Deserializer
<'de
> for &'a Number
{
574 deserialize_any
!(ref);
576 deserialize_number
!(deserialize_i8
=> visit_i8
);
577 deserialize_number
!(deserialize_i16
=> visit_i16
);
578 deserialize_number
!(deserialize_i32
=> visit_i32
);
579 deserialize_number
!(deserialize_i64
=> visit_i64
);
580 deserialize_number
!(deserialize_u8
=> visit_u8
);
581 deserialize_number
!(deserialize_u16
=> visit_u16
);
582 deserialize_number
!(deserialize_u32
=> visit_u32
);
583 deserialize_number
!(deserialize_u64
=> visit_u64
);
584 deserialize_number
!(deserialize_f32
=> visit_f32
);
585 deserialize_number
!(deserialize_f64
=> visit_f64
);
587 forward_to_deserialize_any
! {
588 bool
char str string bytes byte_buf option unit unit_struct
589 newtype_struct seq tuple tuple_struct map
struct enum identifier
594 #[cfg(feature = "arbitrary_precision")]
595 // Not public API. Should be pub(crate).
597 pub struct NumberDeserializer
{
598 pub number
: Option
<String
>,
601 #[cfg(feature = "arbitrary_precision")]
602 impl<'de
> MapAccess
<'de
> for NumberDeserializer
{
605 fn next_key_seed
<K
>(&mut self, seed
: K
) -> Result
<Option
<K
::Value
>, Error
>
607 K
: de
::DeserializeSeed
<'de
>,
609 if self.number
.is_none() {
612 seed
.deserialize(NumberFieldDeserializer
).map(Some
)
615 fn next_value_seed
<V
>(&mut self, seed
: V
) -> Result
<V
::Value
, Error
>
617 V
: de
::DeserializeSeed
<'de
>,
619 seed
.deserialize(self.number
.take().unwrap().into_deserializer())
623 #[cfg(feature = "arbitrary_precision")]
624 struct NumberFieldDeserializer
;
626 #[cfg(feature = "arbitrary_precision")]
627 impl<'de
> Deserializer
<'de
> for NumberFieldDeserializer
{
630 fn deserialize_any
<V
>(self, visitor
: V
) -> Result
<V
::Value
, Error
>
634 visitor
.visit_borrowed_str(SERDE_STRUCT_FIELD_NAME
)
637 forward_to_deserialize_any
! {
638 bool
u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string seq
639 bytes byte_buf map
struct option unit newtype_struct
640 ignored_any unit_struct tuple_struct tuple
enum identifier
644 impl FromStr
for Number
{
647 fn from_str(s
: &str) -> Result
<Self, Self::Err
> {
648 super::de
::Deserializer
::from_str(s
).parse_any_signed_number().map(|n
| n
.into())
652 impl From
<super::de
::Number
> for Number
{
653 fn from(value
: super::de
::Number
) -> Self {
654 let n
= match value
{
655 super::de
::Number
::F64(f
) => {
656 #[cfg(not(feature = "arbitrary_precision"))]
658 #[cfg(feature = "arbitrary_precision")]
661 super::de
::Number
::U64(u
) => {
662 #[cfg(not(feature = "arbitrary_precision"))]
664 #[cfg(feature = "arbitrary_precision")]
667 super::de
::Number
::I64(i
) => {
668 #[cfg(not(feature = "arbitrary_precision"))]
670 #[cfg(feature = "arbitrary_precision")]
673 #[cfg(feature = "arbitrary_precision")]
674 super::de
::Number
::String(s
) => s
,
680 macro_rules
! impl_from_unsigned
{
685 impl From
<$ty
> for Number
{
687 fn from(u
: $ty
) -> Self {
689 #[cfg(not(feature = "arbitrary_precision"))]
690 { N::PosInt(u as u64) }
691 #[cfg(feature = "arbitrary_precision")]
693 let mut buf
= Vec
::new();
694 itoa
::write(&mut buf
, u
).unwrap();
695 String
::from_utf8(buf
).unwrap()
705 macro_rules
! impl_from_signed
{
710 impl From
<$ty
> for Number
{
712 fn from(i
: $ty
) -> Self {
714 #[cfg(not(feature = "arbitrary_precision"))]
722 #[cfg(feature = "arbitrary_precision")]
724 let mut buf
= Vec
::new();
725 itoa
::write(&mut buf
, i
).unwrap();
726 String
::from_utf8(buf
).unwrap()
736 impl_from_unsigned
!(u8, u16, u32, u64, usize);
737 impl_from_signed
!(i8, i16, i32, i64, isize);
740 #[cfg(not(feature = "arbitrary_precision"))]
741 // Not public API. Should be pub(crate).
743 pub fn unexpected(&self) -> Unexpected
{
745 N
::PosInt(u
) => Unexpected
::Unsigned(u
),
746 N
::NegInt(i
) => Unexpected
::Signed(i
),
747 N
::Float(f
) => Unexpected
::Float(f
),
751 #[cfg(feature = "arbitrary_precision")]
752 // Not public API. Should be pub(crate).
754 pub fn unexpected(&self) -> Unexpected
{
755 Unexpected
::Other("number")