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
use super::JSValue;
use std::collections::HashMap;

/// A macro for implementing `From<T>` for `JSValue` for multiple types at once.
/// Takes a list of type-variant pairs and generates a `From<T>` implementation for `JSValue` for each type.
///
/// # Type-Variant Pairs
///
/// * `$t:ty` - The type from which the conversion is done
/// * `$variant:ident` - The corresponding variant of `JSValue` that will be created when converting
macro_rules! impl_to_jsvalue {
    ($($t:ty, $variant:ident),+ $(,)?) => {
        $(impl From<$t> for JSValue {
            fn from(value: $t) -> Self {
                JSValue::$variant(value)
            }
        })+
    };
}

impl_to_jsvalue!(
    bool, Bool,
    i32, Int,
    f64, Float,
    String, String,
    Vec<JSValue>, Array,
    Vec<u8>, ArrayBuffer,
    HashMap<String, JSValue>, Object,
);

impl From<usize> for JSValue {
    fn from(value: usize) -> Self {
        JSValue::Int(value as i32)
    }
}

impl From<&str> for JSValue {
    fn from(value: &str) -> Self {
        JSValue::String(value.to_string())
    }
}

impl From<&[u8]> for JSValue {
    fn from(value: &[u8]) -> Self {
        JSValue::ArrayBuffer(value.to_vec())
    }
}