Coverage Report

Created: 2024-07-06 06:43

/rust/registry/src/index.crates.io-6f17d22bba15001f/serde_json-1.0.120/src/number.rs
Line
Count
Source (jump to first uncovered line)
1
use crate::de::ParserNumber;
2
use crate::error::Error;
3
#[cfg(feature = "arbitrary_precision")]
4
use crate::error::ErrorCode;
5
#[cfg(feature = "arbitrary_precision")]
6
use alloc::borrow::ToOwned;
7
#[cfg(feature = "arbitrary_precision")]
8
use alloc::string::{String, ToString};
9
use core::fmt::{self, Debug, Display};
10
#[cfg(not(feature = "arbitrary_precision"))]
11
use core::hash::{Hash, Hasher};
12
use serde::de::{self, Unexpected, Visitor};
13
#[cfg(feature = "arbitrary_precision")]
14
use serde::de::{IntoDeserializer, MapAccess};
15
use serde::{forward_to_deserialize_any, Deserialize, Deserializer, Serialize, Serializer};
16
17
#[cfg(feature = "arbitrary_precision")]
18
pub(crate) const TOKEN: &str = "$serde_json::private::Number";
19
20
/// Represents a JSON number, whether integer or floating point.
21
#[derive(Clone, PartialEq, Eq, Hash)]
22
pub struct Number {
23
    n: N,
24
}
25
26
#[cfg(not(feature = "arbitrary_precision"))]
27
#[derive(Copy, Clone)]
28
enum N {
29
    PosInt(u64),
30
    /// Always less than zero.
31
    NegInt(i64),
32
    /// Always finite.
33
    Float(f64),
34
}
35
36
#[cfg(not(feature = "arbitrary_precision"))]
37
impl PartialEq for N {
38
0
    fn eq(&self, other: &Self) -> bool {
39
0
        match (self, other) {
40
0
            (N::PosInt(a), N::PosInt(b)) => a == b,
41
0
            (N::NegInt(a), N::NegInt(b)) => a == b,
42
0
            (N::Float(a), N::Float(b)) => a == b,
43
0
            _ => false,
44
        }
45
0
    }
46
}
47
48
// Implementing Eq is fine since any float values are always finite.
49
#[cfg(not(feature = "arbitrary_precision"))]
50
impl Eq for N {}
51
52
#[cfg(not(feature = "arbitrary_precision"))]
53
impl Hash for N {
54
0
    fn hash<H: Hasher>(&self, h: &mut H) {
55
0
        match *self {
56
0
            N::PosInt(i) => i.hash(h),
57
0
            N::NegInt(i) => i.hash(h),
58
0
            N::Float(f) => {
59
0
                if f == 0.0f64 {
60
0
                    // There are 2 zero representations, +0 and -0, which
61
0
                    // compare equal but have different bits. We use the +0 hash
62
0
                    // for both so that hash(+0) == hash(-0).
63
0
                    0.0f64.to_bits().hash(h);
64
0
                } else {
65
0
                    f.to_bits().hash(h);
66
0
                }
67
            }
68
        }
69
0
    }
70
}
71
72
#[cfg(feature = "arbitrary_precision")]
73
type N = String;
74
75
impl Number {
76
    /// Returns true if the `Number` is an integer between `i64::MIN` and
77
    /// `i64::MAX`.
78
    ///
79
    /// For any Number on which `is_i64` returns true, `as_i64` is guaranteed to
80
    /// return the integer value.
81
    ///
82
    /// ```
83
    /// # use serde_json::json;
84
    /// #
85
    /// let big = i64::MAX as u64 + 10;
86
    /// let v = json!({ "a": 64, "b": big, "c": 256.0 });
87
    ///
88
    /// assert!(v["a"].is_i64());
89
    ///
90
    /// // Greater than i64::MAX.
91
    /// assert!(!v["b"].is_i64());
92
    ///
93
    /// // Numbers with a decimal point are not considered integers.
94
    /// assert!(!v["c"].is_i64());
95
    /// ```
96
    #[inline]
97
0
    pub fn is_i64(&self) -> bool {
98
0
        #[cfg(not(feature = "arbitrary_precision"))]
99
0
        match self.n {
100
0
            N::PosInt(v) => v <= i64::MAX as u64,
101
0
            N::NegInt(_) => true,
102
0
            N::Float(_) => false,
103
        }
104
        #[cfg(feature = "arbitrary_precision")]
105
        self.as_i64().is_some()
106
0
    }
107
108
    /// Returns true if the `Number` is an integer between zero and `u64::MAX`.
109
    ///
110
    /// For any Number on which `is_u64` returns true, `as_u64` is guaranteed to
111
    /// return the integer value.
112
    ///
113
    /// ```
114
    /// # use serde_json::json;
115
    /// #
116
    /// let v = json!({ "a": 64, "b": -64, "c": 256.0 });
117
    ///
118
    /// assert!(v["a"].is_u64());
119
    ///
120
    /// // Negative integer.
121
    /// assert!(!v["b"].is_u64());
122
    ///
123
    /// // Numbers with a decimal point are not considered integers.
124
    /// assert!(!v["c"].is_u64());
125
    /// ```
126
    #[inline]
127
0
    pub fn is_u64(&self) -> bool {
128
0
        #[cfg(not(feature = "arbitrary_precision"))]
129
0
        match self.n {
130
0
            N::PosInt(_) => true,
131
0
            N::NegInt(_) | N::Float(_) => false,
132
        }
133
        #[cfg(feature = "arbitrary_precision")]
134
        self.as_u64().is_some()
135
0
    }
136
137
    /// Returns true if the `Number` can be represented by f64.
138
    ///
139
    /// For any Number on which `is_f64` returns true, `as_f64` is guaranteed to
140
    /// return the floating point value.
141
    ///
142
    /// Currently this function returns true if and only if both `is_i64` and
143
    /// `is_u64` return false but this is not a guarantee in the future.
144
    ///
145
    /// ```
146
    /// # use serde_json::json;
147
    /// #
148
    /// let v = json!({ "a": 256.0, "b": 64, "c": -64 });
149
    ///
150
    /// assert!(v["a"].is_f64());
151
    ///
152
    /// // Integers.
153
    /// assert!(!v["b"].is_f64());
154
    /// assert!(!v["c"].is_f64());
155
    /// ```
156
    #[inline]
157
0
    pub fn is_f64(&self) -> bool {
158
0
        #[cfg(not(feature = "arbitrary_precision"))]
159
0
        match self.n {
160
0
            N::Float(_) => true,
161
0
            N::PosInt(_) | N::NegInt(_) => false,
162
        }
163
        #[cfg(feature = "arbitrary_precision")]
164
        {
165
            for c in self.n.chars() {
166
                if c == '.' || c == 'e' || c == 'E' {
167
                    return self.n.parse::<f64>().ok().map_or(false, f64::is_finite);
168
                }
169
            }
170
            false
171
        }
172
0
    }
173
174
    /// If the `Number` is an integer, represent it as i64 if possible. Returns
175
    /// None otherwise.
176
    ///
177
    /// ```
178
    /// # use serde_json::json;
179
    /// #
180
    /// let big = i64::MAX as u64 + 10;
181
    /// let v = json!({ "a": 64, "b": big, "c": 256.0 });
182
    ///
183
    /// assert_eq!(v["a"].as_i64(), Some(64));
184
    /// assert_eq!(v["b"].as_i64(), None);
185
    /// assert_eq!(v["c"].as_i64(), None);
186
    /// ```
187
    #[inline]
188
0
    pub fn as_i64(&self) -> Option<i64> {
189
0
        #[cfg(not(feature = "arbitrary_precision"))]
190
0
        match self.n {
191
0
            N::PosInt(n) => {
192
0
                if n <= i64::MAX as u64 {
193
0
                    Some(n as i64)
194
                } else {
195
0
                    None
196
                }
197
            }
198
0
            N::NegInt(n) => Some(n),
199
0
            N::Float(_) => None,
200
        }
201
        #[cfg(feature = "arbitrary_precision")]
202
        self.n.parse().ok()
203
0
    }
204
205
    /// If the `Number` is an integer, represent it as u64 if possible. Returns
206
    /// None otherwise.
207
    ///
208
    /// ```
209
    /// # use serde_json::json;
210
    /// #
211
    /// let v = json!({ "a": 64, "b": -64, "c": 256.0 });
212
    ///
213
    /// assert_eq!(v["a"].as_u64(), Some(64));
214
    /// assert_eq!(v["b"].as_u64(), None);
215
    /// assert_eq!(v["c"].as_u64(), None);
216
    /// ```
217
    #[inline]
218
0
    pub fn as_u64(&self) -> Option<u64> {
219
0
        #[cfg(not(feature = "arbitrary_precision"))]
220
0
        match self.n {
221
0
            N::PosInt(n) => Some(n),
222
0
            N::NegInt(_) | N::Float(_) => None,
223
        }
224
        #[cfg(feature = "arbitrary_precision")]
225
        self.n.parse().ok()
226
0
    }
227
228
    /// Represents the number as f64 if possible. Returns None otherwise.
229
    ///
230
    /// ```
231
    /// # use serde_json::json;
232
    /// #
233
    /// let v = json!({ "a": 256.0, "b": 64, "c": -64 });
234
    ///
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));
238
    /// ```
239
    #[inline]
240
0
    pub fn as_f64(&self) -> Option<f64> {
241
0
        #[cfg(not(feature = "arbitrary_precision"))]
242
0
        match self.n {
243
0
            N::PosInt(n) => Some(n as f64),
244
0
            N::NegInt(n) => Some(n as f64),
245
0
            N::Float(n) => Some(n),
246
        }
247
        #[cfg(feature = "arbitrary_precision")]
248
        self.n.parse::<f64>().ok().filter(|float| float.is_finite())
249
0
    }
250
251
    /// Converts a finite `f64` to a `Number`. Infinite or NaN values are not JSON
252
    /// numbers.
253
    ///
254
    /// ```
255
    /// # use std::f64;
256
    /// #
257
    /// # use serde_json::Number;
258
    /// #
259
    /// assert!(Number::from_f64(256.0).is_some());
260
    ///
261
    /// assert!(Number::from_f64(f64::NAN).is_none());
262
    /// ```
263
    #[inline]
264
0
    pub fn from_f64(f: f64) -> Option<Number> {
265
0
        if f.is_finite() {
266
0
            let n = {
267
0
                #[cfg(not(feature = "arbitrary_precision"))]
268
0
                {
269
0
                    N::Float(f)
270
0
                }
271
0
                #[cfg(feature = "arbitrary_precision")]
272
0
                {
273
0
                    ryu::Buffer::new().format_finite(f).to_owned()
274
0
                }
275
0
            };
276
0
            Some(Number { n })
277
        } else {
278
0
            None
279
        }
280
0
    }
281
282
    /// Returns the exact original JSON representation that this Number was
283
    /// parsed from.
284
    ///
285
    /// For numbers constructed not via parsing, such as by `From<i32>`, returns
286
    /// the JSON representation that serde\_json would serialize for this
287
    /// number.
288
    ///
289
    /// ```
290
    /// # use serde_json::Number;
291
    /// for value in [
292
    ///     "7",
293
    ///     "12.34",
294
    ///     "34e-56789",
295
    ///     "0.0123456789000000012345678900000001234567890000123456789",
296
    ///     "343412345678910111213141516171819202122232425262728293034",
297
    ///     "-343412345678910111213141516171819202122232425262728293031",
298
    /// ] {
299
    ///     let number: Number = serde_json::from_str(value).unwrap();
300
    ///     assert_eq!(number.as_str(), value);
301
    /// }
302
    /// ```
303
    #[cfg(feature = "arbitrary_precision")]
304
    #[cfg_attr(docsrs, doc(cfg(feature = "arbitrary_precision")))]
305
    pub fn as_str(&self) -> &str {
306
        &self.n
307
    }
308
309
0
    pub(crate) fn as_f32(&self) -> Option<f32> {
310
0
        #[cfg(not(feature = "arbitrary_precision"))]
311
0
        match self.n {
312
0
            N::PosInt(n) => Some(n as f32),
313
0
            N::NegInt(n) => Some(n as f32),
314
0
            N::Float(n) => Some(n as f32),
315
        }
316
        #[cfg(feature = "arbitrary_precision")]
317
        self.n.parse::<f32>().ok().filter(|float| float.is_finite())
318
0
    }
319
320
0
    pub(crate) fn from_f32(f: f32) -> Option<Number> {
321
0
        if f.is_finite() {
322
0
            let n = {
323
0
                #[cfg(not(feature = "arbitrary_precision"))]
324
0
                {
325
0
                    N::Float(f as f64)
326
0
                }
327
0
                #[cfg(feature = "arbitrary_precision")]
328
0
                {
329
0
                    ryu::Buffer::new().format_finite(f).to_owned()
330
0
                }
331
0
            };
332
0
            Some(Number { n })
333
        } else {
334
0
            None
335
        }
336
0
    }
337
338
    #[cfg(feature = "arbitrary_precision")]
339
    /// Not public API. Only tests use this.
340
    #[doc(hidden)]
341
    #[inline]
342
    pub fn from_string_unchecked(n: String) -> Self {
343
        Number { n }
344
    }
345
}
346
347
impl Display for Number {
348
    #[cfg(not(feature = "arbitrary_precision"))]
349
0
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
350
0
        match self.n {
351
0
            N::PosInt(u) => formatter.write_str(itoa::Buffer::new().format(u)),
352
0
            N::NegInt(i) => formatter.write_str(itoa::Buffer::new().format(i)),
353
0
            N::Float(f) => formatter.write_str(ryu::Buffer::new().format_finite(f)),
354
        }
355
0
    }
356
357
    #[cfg(feature = "arbitrary_precision")]
358
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
359
        Display::fmt(&self.n, formatter)
360
    }
361
}
362
363
impl Debug for Number {
364
0
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
365
0
        write!(formatter, "Number({})", self)
366
0
    }
367
}
368
369
impl Serialize for Number {
370
    #[cfg(not(feature = "arbitrary_precision"))]
371
    #[inline]
372
0
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
373
0
    where
374
0
        S: Serializer,
375
0
    {
376
0
        match self.n {
377
0
            N::PosInt(u) => serializer.serialize_u64(u),
378
0
            N::NegInt(i) => serializer.serialize_i64(i),
379
0
            N::Float(f) => serializer.serialize_f64(f),
380
        }
381
0
    }
Unexecuted instantiation: <serde_json::number::Number as serde::ser::Serialize>::serialize::<&mut serde_json::ser::Serializer<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter>>
Unexecuted instantiation: <serde_json::number::Number as serde::ser::Serialize>::serialize::<&mut serde_json::ser::Serializer<&mut <serde_json::value::Value as core::fmt::Display>::fmt::WriterFormatter, serde_json::ser::PrettyFormatter>>
382
383
    #[cfg(feature = "arbitrary_precision")]
384
    #[inline]
385
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
386
    where
387
        S: Serializer,
388
    {
389
        use serde::ser::SerializeStruct;
390
391
        let mut s = tri!(serializer.serialize_struct(TOKEN, 1));
392
        tri!(s.serialize_field(TOKEN, &self.n));
393
        s.end()
394
    }
395
}
396
397
impl<'de> Deserialize<'de> for Number {
398
    #[inline]
399
0
    fn deserialize<D>(deserializer: D) -> Result<Number, D::Error>
400
0
    where
401
0
        D: Deserializer<'de>,
402
0
    {
403
0
        struct NumberVisitor;
404
0
405
0
        impl<'de> Visitor<'de> for NumberVisitor {
406
0
            type Value = Number;
407
0
408
0
            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
409
0
                formatter.write_str("a JSON number")
410
0
            }
411
0
412
0
            #[inline]
413
0
            fn visit_i64<E>(self, value: i64) -> Result<Number, E> {
414
0
                Ok(value.into())
415
0
            }
416
0
417
0
            #[inline]
418
0
            fn visit_u64<E>(self, value: u64) -> Result<Number, E> {
419
0
                Ok(value.into())
420
0
            }
421
0
422
0
            #[inline]
423
0
            fn visit_f64<E>(self, value: f64) -> Result<Number, E>
424
0
            where
425
0
                E: de::Error,
426
0
            {
427
0
                Number::from_f64(value).ok_or_else(|| de::Error::custom("not a JSON number"))
428
0
            }
429
0
430
0
            #[cfg(feature = "arbitrary_precision")]
431
0
            #[inline]
432
0
            fn visit_map<V>(self, mut visitor: V) -> Result<Number, V::Error>
433
0
            where
434
0
                V: de::MapAccess<'de>,
435
0
            {
436
0
                let value = tri!(visitor.next_key::<NumberKey>());
437
0
                if value.is_none() {
438
0
                    return Err(de::Error::invalid_type(Unexpected::Map, &self));
439
0
                }
440
0
                let v: NumberFromString = tri!(visitor.next_value());
441
0
                Ok(v.value)
442
0
            }
443
0
        }
444
0
445
0
        deserializer.deserialize_any(NumberVisitor)
446
0
    }
447
}
448
449
#[cfg(feature = "arbitrary_precision")]
450
struct NumberKey;
451
452
#[cfg(feature = "arbitrary_precision")]
453
impl<'de> de::Deserialize<'de> for NumberKey {
454
    fn deserialize<D>(deserializer: D) -> Result<NumberKey, D::Error>
455
    where
456
        D: de::Deserializer<'de>,
457
    {
458
        struct FieldVisitor;
459
460
        impl<'de> de::Visitor<'de> for FieldVisitor {
461
            type Value = ();
462
463
            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
464
                formatter.write_str("a valid number field")
465
            }
466
467
            fn visit_str<E>(self, s: &str) -> Result<(), E>
468
            where
469
                E: de::Error,
470
            {
471
                if s == TOKEN {
472
                    Ok(())
473
                } else {
474
                    Err(de::Error::custom("expected field with custom name"))
475
                }
476
            }
477
        }
478
479
        tri!(deserializer.deserialize_identifier(FieldVisitor));
480
        Ok(NumberKey)
481
    }
482
}
483
484
#[cfg(feature = "arbitrary_precision")]
485
pub struct NumberFromString {
486
    pub value: Number,
487
}
488
489
#[cfg(feature = "arbitrary_precision")]
490
impl<'de> de::Deserialize<'de> for NumberFromString {
491
    fn deserialize<D>(deserializer: D) -> Result<NumberFromString, D::Error>
492
    where
493
        D: de::Deserializer<'de>,
494
    {
495
        struct Visitor;
496
497
        impl<'de> de::Visitor<'de> for Visitor {
498
            type Value = NumberFromString;
499
500
            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
501
                formatter.write_str("string containing a number")
502
            }
503
504
            fn visit_str<E>(self, s: &str) -> Result<NumberFromString, E>
505
            where
506
                E: de::Error,
507
            {
508
                let n = tri!(s.parse().map_err(de::Error::custom));
509
                Ok(NumberFromString { value: n })
510
            }
511
        }
512
513
        deserializer.deserialize_str(Visitor)
514
    }
515
}
516
517
#[cfg(feature = "arbitrary_precision")]
518
fn invalid_number() -> Error {
519
    Error::syntax(ErrorCode::InvalidNumber, 0, 0)
520
}
521
522
macro_rules! deserialize_any {
523
    (@expand [$($num_string:tt)*]) => {
524
        #[cfg(not(feature = "arbitrary_precision"))]
525
        #[inline]
526
0
        fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error>
527
0
        where
528
0
            V: Visitor<'de>,
529
0
        {
530
0
            match self.n {
531
0
                N::PosInt(u) => visitor.visit_u64(u),
532
0
                N::NegInt(i) => visitor.visit_i64(i),
533
0
                N::Float(f) => visitor.visit_f64(f),
534
            }
535
0
        }
Unexecuted instantiation: <serde_json::number::Number as serde::de::Deserializer>::deserialize_any::<_>
Unexecuted instantiation: <&serde_json::number::Number as serde::de::Deserializer>::deserialize_any::<_>
536
537
        #[cfg(feature = "arbitrary_precision")]
538
        #[inline]
539
        fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error>
540
            where V: Visitor<'de>
541
        {
542
            if let Some(u) = self.as_u64() {
543
                return visitor.visit_u64(u);
544
            } else if let Some(i) = self.as_i64() {
545
                return visitor.visit_i64(i);
546
            } else if let Some(f) = self.as_f64() {
547
                if ryu::Buffer::new().format_finite(f) == self.n || f.to_string() == self.n {
548
                    return visitor.visit_f64(f);
549
                }
550
            }
551
552
            visitor.visit_map(NumberDeserializer {
553
                number: Some(self.$($num_string)*),
554
            })
555
        }
556
    };
557
558
    (owned) => {
559
        deserialize_any!(@expand [n]);
560
    };
561
562
    (ref) => {
563
        deserialize_any!(@expand [n.clone()]);
564
    };
565
}
566
567
macro_rules! deserialize_number {
568
    ($deserialize:ident => $visit:ident) => {
569
        #[cfg(not(feature = "arbitrary_precision"))]
570
0
        fn $deserialize<V>(self, visitor: V) -> Result<V::Value, Error>
571
0
        where
572
0
            V: Visitor<'de>,
573
0
        {
574
0
            self.deserialize_any(visitor)
575
0
        }
Unexecuted instantiation: <serde_json::number::Number as serde::de::Deserializer>::deserialize_i8::<_>
Unexecuted instantiation: <serde_json::number::Number as serde::de::Deserializer>::deserialize_i16::<_>
Unexecuted instantiation: <serde_json::number::Number as serde::de::Deserializer>::deserialize_i32::<_>
Unexecuted instantiation: <serde_json::number::Number as serde::de::Deserializer>::deserialize_i64::<_>
Unexecuted instantiation: <serde_json::number::Number as serde::de::Deserializer>::deserialize_i128::<_>
Unexecuted instantiation: <serde_json::number::Number as serde::de::Deserializer>::deserialize_u8::<_>
Unexecuted instantiation: <serde_json::number::Number as serde::de::Deserializer>::deserialize_u16::<_>
Unexecuted instantiation: <serde_json::number::Number as serde::de::Deserializer>::deserialize_u32::<_>
Unexecuted instantiation: <serde_json::number::Number as serde::de::Deserializer>::deserialize_u64::<_>
Unexecuted instantiation: <serde_json::number::Number as serde::de::Deserializer>::deserialize_u128::<_>
Unexecuted instantiation: <serde_json::number::Number as serde::de::Deserializer>::deserialize_f32::<_>
Unexecuted instantiation: <serde_json::number::Number as serde::de::Deserializer>::deserialize_f64::<_>
Unexecuted instantiation: <&serde_json::number::Number as serde::de::Deserializer>::deserialize_i8::<_>
Unexecuted instantiation: <&serde_json::number::Number as serde::de::Deserializer>::deserialize_i16::<_>
Unexecuted instantiation: <&serde_json::number::Number as serde::de::Deserializer>::deserialize_i32::<_>
Unexecuted instantiation: <&serde_json::number::Number as serde::de::Deserializer>::deserialize_i64::<_>
Unexecuted instantiation: <&serde_json::number::Number as serde::de::Deserializer>::deserialize_i128::<_>
Unexecuted instantiation: <&serde_json::number::Number as serde::de::Deserializer>::deserialize_u8::<_>
Unexecuted instantiation: <&serde_json::number::Number as serde::de::Deserializer>::deserialize_u16::<_>
Unexecuted instantiation: <&serde_json::number::Number as serde::de::Deserializer>::deserialize_u32::<_>
Unexecuted instantiation: <&serde_json::number::Number as serde::de::Deserializer>::deserialize_u64::<_>
Unexecuted instantiation: <&serde_json::number::Number as serde::de::Deserializer>::deserialize_u128::<_>
Unexecuted instantiation: <&serde_json::number::Number as serde::de::Deserializer>::deserialize_f32::<_>
Unexecuted instantiation: <&serde_json::number::Number as serde::de::Deserializer>::deserialize_f64::<_>
576
577
        #[cfg(feature = "arbitrary_precision")]
578
        fn $deserialize<V>(self, visitor: V) -> Result<V::Value, Error>
579
        where
580
            V: de::Visitor<'de>,
581
        {
582
            visitor.$visit(tri!(self.n.parse().map_err(|_| invalid_number())))
583
        }
584
    };
585
}
586
587
impl<'de> Deserializer<'de> for Number {
588
    type Error = Error;
589
590
    deserialize_any!(owned);
591
592
    deserialize_number!(deserialize_i8 => visit_i8);
593
    deserialize_number!(deserialize_i16 => visit_i16);
594
    deserialize_number!(deserialize_i32 => visit_i32);
595
    deserialize_number!(deserialize_i64 => visit_i64);
596
    deserialize_number!(deserialize_i128 => visit_i128);
597
    deserialize_number!(deserialize_u8 => visit_u8);
598
    deserialize_number!(deserialize_u16 => visit_u16);
599
    deserialize_number!(deserialize_u32 => visit_u32);
600
    deserialize_number!(deserialize_u64 => visit_u64);
601
    deserialize_number!(deserialize_u128 => visit_u128);
602
    deserialize_number!(deserialize_f32 => visit_f32);
603
    deserialize_number!(deserialize_f64 => visit_f64);
604
605
    forward_to_deserialize_any! {
606
        bool char str string bytes byte_buf option unit unit_struct
607
        newtype_struct seq tuple tuple_struct map struct enum identifier
608
        ignored_any
609
    }
610
}
611
612
impl<'de, 'a> Deserializer<'de> for &'a Number {
613
    type Error = Error;
614
615
    deserialize_any!(ref);
616
617
    deserialize_number!(deserialize_i8 => visit_i8);
618
    deserialize_number!(deserialize_i16 => visit_i16);
619
    deserialize_number!(deserialize_i32 => visit_i32);
620
    deserialize_number!(deserialize_i64 => visit_i64);
621
    deserialize_number!(deserialize_i128 => visit_i128);
622
    deserialize_number!(deserialize_u8 => visit_u8);
623
    deserialize_number!(deserialize_u16 => visit_u16);
624
    deserialize_number!(deserialize_u32 => visit_u32);
625
    deserialize_number!(deserialize_u64 => visit_u64);
626
    deserialize_number!(deserialize_u128 => visit_u128);
627
    deserialize_number!(deserialize_f32 => visit_f32);
628
    deserialize_number!(deserialize_f64 => visit_f64);
629
630
    forward_to_deserialize_any! {
631
        bool char str string bytes byte_buf option unit unit_struct
632
        newtype_struct seq tuple tuple_struct map struct enum identifier
633
        ignored_any
634
    }
635
}
636
637
#[cfg(feature = "arbitrary_precision")]
638
pub(crate) struct NumberDeserializer {
639
    pub number: Option<String>,
640
}
641
642
#[cfg(feature = "arbitrary_precision")]
643
impl<'de> MapAccess<'de> for NumberDeserializer {
644
    type Error = Error;
645
646
    fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Error>
647
    where
648
        K: de::DeserializeSeed<'de>,
649
    {
650
        if self.number.is_none() {
651
            return Ok(None);
652
        }
653
        seed.deserialize(NumberFieldDeserializer).map(Some)
654
    }
655
656
    fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Error>
657
    where
658
        V: de::DeserializeSeed<'de>,
659
    {
660
        seed.deserialize(self.number.take().unwrap().into_deserializer())
661
    }
662
}
663
664
#[cfg(feature = "arbitrary_precision")]
665
struct NumberFieldDeserializer;
666
667
#[cfg(feature = "arbitrary_precision")]
668
impl<'de> Deserializer<'de> for NumberFieldDeserializer {
669
    type Error = Error;
670
671
    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error>
672
    where
673
        V: de::Visitor<'de>,
674
    {
675
        visitor.visit_borrowed_str(TOKEN)
676
    }
677
678
    forward_to_deserialize_any! {
679
        bool u8 u16 u32 u64 u128 i8 i16 i32 i64 i128 f32 f64 char str string seq
680
        bytes byte_buf map struct option unit newtype_struct ignored_any
681
        unit_struct tuple_struct tuple enum identifier
682
    }
683
}
684
685
impl From<ParserNumber> for Number {
686
0
    fn from(value: ParserNumber) -> Self {
687
0
        let n = match value {
688
0
            ParserNumber::F64(f) => {
689
0
                #[cfg(not(feature = "arbitrary_precision"))]
690
0
                {
691
0
                    N::Float(f)
692
                }
693
                #[cfg(feature = "arbitrary_precision")]
694
                {
695
                    f.to_string()
696
                }
697
            }
698
0
            ParserNumber::U64(u) => {
699
0
                #[cfg(not(feature = "arbitrary_precision"))]
700
0
                {
701
0
                    N::PosInt(u)
702
                }
703
                #[cfg(feature = "arbitrary_precision")]
704
                {
705
                    u.to_string()
706
                }
707
            }
708
0
            ParserNumber::I64(i) => {
709
0
                #[cfg(not(feature = "arbitrary_precision"))]
710
0
                {
711
0
                    N::NegInt(i)
712
                }
713
                #[cfg(feature = "arbitrary_precision")]
714
                {
715
                    i.to_string()
716
                }
717
            }
718
            #[cfg(feature = "arbitrary_precision")]
719
            ParserNumber::String(s) => s,
720
        };
721
0
        Number { n }
722
0
    }
723
}
724
725
macro_rules! impl_from_unsigned {
726
    (
727
        $($ty:ty),*
728
    ) => {
729
        $(
730
            impl From<$ty> for Number {
731
                #[inline]
732
0
                fn from(u: $ty) -> Self {
733
0
                    let n = {
734
0
                        #[cfg(not(feature = "arbitrary_precision"))]
735
0
                        { N::PosInt(u as u64) }
736
0
                        #[cfg(feature = "arbitrary_precision")]
737
0
                        {
738
0
                            itoa::Buffer::new().format(u).to_owned()
739
0
                        }
740
0
                    };
741
0
                    Number { n }
742
0
                }
Unexecuted instantiation: <serde_json::number::Number as core::convert::From<u8>>::from
Unexecuted instantiation: <serde_json::number::Number as core::convert::From<u16>>::from
Unexecuted instantiation: <serde_json::number::Number as core::convert::From<u32>>::from
Unexecuted instantiation: <serde_json::number::Number as core::convert::From<u64>>::from
Unexecuted instantiation: <serde_json::number::Number as core::convert::From<usize>>::from
743
            }
744
        )*
745
    };
746
}
747
748
macro_rules! impl_from_signed {
749
    (
750
        $($ty:ty),*
751
    ) => {
752
        $(
753
            impl From<$ty> for Number {
754
                #[inline]
755
0
                fn from(i: $ty) -> Self {
756
0
                    let n = {
757
                        #[cfg(not(feature = "arbitrary_precision"))]
758
                        {
759
0
                            if i < 0 {
760
0
                                N::NegInt(i as i64)
761
                            } else {
762
0
                                N::PosInt(i as u64)
763
                            }
764
                        }
765
                        #[cfg(feature = "arbitrary_precision")]
766
                        {
767
                            itoa::Buffer::new().format(i).to_owned()
768
                        }
769
                    };
770
0
                    Number { n }
771
0
                }
Unexecuted instantiation: <serde_json::number::Number as core::convert::From<i8>>::from
Unexecuted instantiation: <serde_json::number::Number as core::convert::From<i16>>::from
Unexecuted instantiation: <serde_json::number::Number as core::convert::From<i32>>::from
Unexecuted instantiation: <serde_json::number::Number as core::convert::From<i64>>::from
Unexecuted instantiation: <serde_json::number::Number as core::convert::From<isize>>::from
772
            }
773
        )*
774
    };
775
}
776
777
impl_from_unsigned!(u8, u16, u32, u64, usize);
778
impl_from_signed!(i8, i16, i32, i64, isize);
779
780
#[cfg(feature = "arbitrary_precision")]
781
impl_from_unsigned!(u128);
782
#[cfg(feature = "arbitrary_precision")]
783
impl_from_signed!(i128);
784
785
impl Number {
786
    #[cfg(not(feature = "arbitrary_precision"))]
787
    #[cold]
788
0
    pub(crate) fn unexpected(&self) -> Unexpected {
789
0
        match self.n {
790
0
            N::PosInt(u) => Unexpected::Unsigned(u),
791
0
            N::NegInt(i) => Unexpected::Signed(i),
792
0
            N::Float(f) => Unexpected::Float(f),
793
        }
794
0
    }
795
796
    #[cfg(feature = "arbitrary_precision")]
797
    #[cold]
798
    pub(crate) fn unexpected(&self) -> Unexpected {
799
        Unexpected::Other("number")
800
    }
801
}