nanvm_lib/js/
number.rs

1use crate::mem::manager::Dealloc;
2
3use super::{any_cast::AnyCast, bitset::EXTENSION};
4
5impl<D: Dealloc> AnyCast<D> for f64 {
6    #[inline(always)]
7    unsafe fn has_same_type(u: u64) -> bool {
8        !EXTENSION.has(u)
9    }
10    #[inline(always)]
11    unsafe fn move_to_any_internal(self) -> u64 {
12        self.to_bits()
13    }
14    #[inline(always)]
15    unsafe fn from_any_internal(u: u64) -> Self {
16        Self::from_bits(u)
17    }
18}
19
20#[cfg(test)]
21pub mod test {
22    use wasm_bindgen_test::wasm_bindgen_test;
23
24    // compatible with `f64`
25    pub const INFINITY: u64 = 0x7FF0_0000_0000_0000;
26    pub const NAN: u64 = 0x7FF8_0000_0000_0000;
27    pub const NEG_INFINITY: u64 = 0xFFF0_0000_0000_0000;
28    pub const E: u64 = 0x7FF0_0000_0000_0000;
29    pub const EF: u64 = 0x7FFF_FFFF_FFFF_FFFF;
30
31    pub const fn is_valid(v: u64) -> bool {
32        v & E != E || v & EF == INFINITY || v == NAN
33    }
34
35    #[test]
36    #[wasm_bindgen_test]
37    fn test_nan() {
38        assert_eq!(f64::INFINITY.to_bits(), INFINITY);
39        assert_ne!(f64::NAN, f64::NAN);
40        assert_eq!(f64::NAN.to_bits(), NAN);
41        assert_eq!(f64::NEG_INFINITY.to_bits(), NEG_INFINITY);
42    }
43
44    #[test]
45    #[wasm_bindgen_test]
46    #[allow(clippy::zero_divided_by_zero)]
47    fn test_check() {
48        assert!(is_valid(0));
49        assert!(is_valid(1));
50        assert!(is_valid(INFINITY));
51        assert!(is_valid(NAN));
52        assert!(is_valid(NEG_INFINITY));
53        assert_eq!(f64::NAN.to_bits(), NAN);
54        assert_eq!((0.0f64 / 0.0).to_bits(), NAN);
55    }
56
57    #[test]
58    #[wasm_bindgen_test]
59    #[should_panic]
60    fn test_nan_panic() {
61        assert!(is_valid(0x7FF0_00F0_0500_0001));
62    }
63
64    #[test]
65    #[wasm_bindgen_test]
66    #[should_panic]
67    fn test_nan_panic2() {
68        assert!(is_valid(0xFFFA_FF96_5534_5781));
69    }
70}