wasm_bridge_js/no_bindgen/
val.rs

1#[derive(Debug, Clone)]
2pub enum Val {
3    I32(i32),
4    I64(i64),
5
6    // raw values, use f32::to_bits to fill it
7    F32(u32),
8    F64(u64),
9}
10
11impl Val {
12    pub fn i32(&self) -> Option<i32> {
13        match self {
14            Self::I32(val) => Some(*val),
15            // Can be f64, because we can't tell from JS's number type
16            // TODO: check for overflows
17            Self::F64(val) => Some(f64::from_bits(*val) as _),
18            _ => None,
19        }
20    }
21    pub fn i64(&self) -> Option<i64> {
22        match self {
23            Self::I64(val) => Some(*val),
24            _ => None,
25        }
26    }
27    pub fn f32(&self) -> Option<f32> {
28        match self {
29            Self::F32(val) => Some(f32::from_bits(*val)),
30            // Can be f64, because we can't tell from JS's number type
31            // TODO: check for overflows
32            Self::F64(val) => Some(f64::from_bits(*val) as _),
33            _ => None,
34        }
35    }
36
37    pub fn f64(&self) -> Option<f64> {
38        match self {
39            Self::F64(val) => Some(f64::from_bits(*val)),
40            _ => None,
41        }
42    }
43}
44
45impl From<i32> for Val {
46    fn from(value: i32) -> Self {
47        Self::I32(value)
48    }
49}
50
51impl From<i64> for Val {
52    fn from(value: i64) -> Self {
53        Self::I64(value)
54    }
55}
56
57impl From<f32> for Val {
58    fn from(value: f32) -> Self {
59        Self::F32(value.to_bits())
60    }
61}
62
63impl From<f64> for Val {
64    fn from(value: f64) -> Self {
65        Self::F64(value.to_bits())
66    }
67}