File: uint.rs

package info (click to toggle)
rust-js-int 0.2.2-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 172 kB
  • sloc: makefile: 2
file content (72 lines) | stat: -rw-r--r-- 2,250 bytes parent folder | download
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
#![cfg(feature = "serde")]

use core::convert::TryFrom;
use js_int::{uint, UInt};
use serde::{de::IntoDeserializer, Deserialize};
use serde_test::{assert_ser_tokens, Token};

#[test]
fn serialize() {
    assert_serialize(100);
    assert_serialize(0);
}

fn assert_serialize(number: u32) {
    assert_ser_tokens(
        &UInt::from(number),
        &[Token::NewtypeStruct { name: "UInt" }, Token::U64(number as _)],
    )
}

#[test]
fn deserialize() {
    assert_eq!(deserialize_from(100).unwrap(), uint!(100));
    assert_eq!(deserialize_from(0).unwrap(), uint!(0));
    assert_eq!(deserialize_from(9007199254740991i64).unwrap(), UInt::MAX);
    assert!(deserialize_from(9007199254740992i64).is_err());
}

#[test]
#[cfg_attr(feature = "float_deserialize", ignore)]
fn dont_deserialize_integral_float() {
    assert!(deserialize_from(1.0).is_err());
    assert!(deserialize_from(9007199254740991.0).is_err());
    assert!(deserialize_from(9007199254740992.0).is_err());
}

#[test]
#[cfg_attr(feature = "lax_deserialize", ignore)]
fn dont_deserialize_fractional_float() {
    assert!(deserialize_from(0.5).is_err());
    assert!(deserialize_from(42.1337).is_err());
}

#[test]
#[cfg_attr(not(feature = "float_deserialize"), ignore)]
fn deserialize_integral_float() {
    assert_eq!(deserialize_from(1.0).unwrap(), uint!(1));
    assert_eq!(deserialize_from(9007199254740991.0).unwrap(), UInt::MAX);
    assert!(deserialize_from(9007199254740992.0).is_err());
    // NOTE: This still ends up as integral because the .49 exceeds the representable range of f64
    assert_eq!(
        deserialize_from(9007199254740991.49).unwrap(),
        UInt::try_from(9007199254740991i64).unwrap()
    );

    assert!(deserialize_from(f64::NAN).is_err());
    assert!(deserialize_from(f64::INFINITY).is_err());
    assert!(deserialize_from(f64::NEG_INFINITY).is_err());
}

#[test]
#[cfg_attr(not(feature = "lax_deserialize"), ignore)]
fn deserialize_fractional_float() {
    assert_eq!(deserialize_from(0.5).unwrap(), uint!(0));
    assert_eq!(deserialize_from(42.1337).unwrap(), uint!(42));
}

fn deserialize_from<'de, Value: IntoDeserializer<'de>>(
    value: Value,
) -> Result<UInt, serde::de::value::Error> {
    UInt::deserialize(value.into_deserializer())
}