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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
use std::{collections::HashMap, fmt};

pub mod qjs_convert;

mod to_js_value;
mod try_from_js_value;

/// A safe and high level representation of a JavaScript value.
///
/// This enum implements `From` and `TryFrom` for many types, so it can be used to convert between Rust and JavaScript types.
///
/// # Example
///
/// ```
/// // Convert a &str to a JSValue::String
/// let js_value: JSValue = "hello".into();
/// assert_eq!("hello", js_value.to_string());
///
/// // Convert a JSValue::String to a String
/// let result: String = js_value.try_into().unwrap();
/// assert_eq!("hello", result);
/// ```
#[derive(Debug, PartialEq, Clone)]
pub enum JSValue {
    /// Represents the JavaScript `undefined` value
    Undefined,
    /// Represents the JavaScript `null` value
    Null,
    /// Represents a JavaScript boolean value
    Bool(bool),
    /// Represents a JavaScript integer
    Int(i32),
    /// Represents a JavaScript floating-point number
    Float(f64),
    /// Represents a JavaScript string value
    String(String),
    /// Represents a JavaScript array of `JSValue`s
    Array(Vec<JSValue>),
    /// Represents a JavaScript ArrayBuffer of bytes
    ArrayBuffer(Vec<u8>),
    /// Represents a JavaScript object, with string keys and `JSValue` values
    Object(HashMap<String, JSValue>),
}

impl JSValue {
    /// Constructs a `JSValue::Array` variant from a vec of items that can be converted to `JSValue`.
    ///
    /// # Arguments
    ///
    /// * `v` - A vec of items to be converted to `JSValue::Array`
    ///
    /// # Example
    ///
    /// ```
    /// let vec = vec![1, 2, 3];
    /// let js_arr = JSValue::from_vec(vec);
    /// ```
    pub fn from_vec<T: Into<JSValue>>(v: Vec<T>) -> JSValue {
        let js_arr: Vec<JSValue> = v.into_iter().map(|elem| elem.into()).collect();
        JSValue::Array(js_arr)
    }

    /// Constructs a `JSValue::Object` variant from a HashMap of key-value pairs that can be converted to `JSValue`.
    ///
    /// # Arguments
    ///
    /// * `hm` - A HashMap of key-value pairs to be converted to `JSValue::Object`
    ///
    /// # Example
    ///
    /// ```
    /// let mut hashmap = std::collections::HashMap::from([
    ///   ("first_name", "John"),
    ///   ("last_name", "Smith"),
    /// ]);
    ///
    /// let js_obj = JSValue::from_hashmap(hashmap);
    /// ```
    pub fn from_hashmap<T: Into<JSValue>>(hm: HashMap<&str, T>) -> JSValue {
        let js_obj: HashMap<String, JSValue> = hm
            .into_iter()
            .map(|(k, v)| (k.to_string(), v.into()))
            .collect();
        JSValue::Object(js_obj)
    }
}

/// The implementation matches the default JavaScript display format for each value.
///
/// Used <http://numcalc.com/> to determine the default display format for each type.
impl fmt::Display for JSValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            JSValue::Undefined => write!(f, "undefined"),
            JSValue::Null => write!(f, "null"),
            JSValue::Bool(b) => write!(f, "{}", b),
            JSValue::Int(i) => write!(f, "{}", i),
            JSValue::Float(n) => write!(f, "{}", n),
            JSValue::String(s) => write!(f, "{}", s),
            JSValue::ArrayBuffer(_) => write!(f, "[object ArrayBuffer]"),
            JSValue::Array(arr) => {
                write!(
                    f,
                    "{}",
                    arr.iter()
                        .map(|e| format!("{}", e))
                        .collect::<Vec<String>>()
                        .join(",")
                )
            }
            JSValue::Object(_) => write!(f, "[object Object]"),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_conversion_between_bool() {
        let js_value: JSValue = true.into();
        assert_eq!("true", js_value.to_string());

        let result: bool = js_value.try_into().unwrap();
        assert!(result);
    }

    #[test]
    fn test_conversion_between_i32() {
        let js_value: JSValue = 2.into();
        assert_eq!("2", js_value.to_string());

        let result: i32 = js_value.try_into().unwrap();
        assert_eq!(result, 2);
    }

    #[test]
    fn test_conversion_between_usize() {
        let i: usize = 1;
        let js_value: JSValue = i.into();
        assert_eq!("1", js_value.to_string());

        let result: usize = js_value.try_into().unwrap();
        assert_eq!(result, 1);
    }

    #[test]
    fn test_conversion_between_f64() {
        let js_value: JSValue = 2.3.into();
        assert_eq!("2.3", js_value.to_string());

        let result: f64 = js_value.try_into().unwrap();
        assert_eq!(result, 2.3);
    }

    #[test]
    fn test_conversion_between_str_and_string() {
        let js_value: JSValue = "hello".into();
        assert_eq!("hello", js_value.to_string());

        let js_value: JSValue = "hello".to_string().into();
        assert_eq!("hello", js_value.to_string());

        let result: String = js_value.try_into().unwrap();
        assert_eq!(result, "hello");
    }

    #[test]
    fn test_conversion_between_vec() {
        let js_value: JSValue = JSValue::from_vec(vec![1, 2]);
        assert_eq!("1,2", js_value.to_string());

        let result: Vec<JSValue> = js_value.try_into().unwrap();
        assert_eq!(result, vec![JSValue::Int(1), JSValue::Int(2)]);

        let js_value: JSValue = JSValue::from_vec(vec!["h", "w"]);
        assert_eq!("h,w", js_value.to_string());

        let result: Vec<JSValue> = js_value.try_into().unwrap();
        assert_eq!(
            result,
            vec![
                JSValue::String("h".to_string()),
                JSValue::String("w".to_string())
            ]
        );
    }

    #[test]
    fn test_conversion_between_bytes() {
        let bytes = "hi".as_bytes();
        let js_value: JSValue = bytes.into();
        assert_eq!("[object ArrayBuffer]", js_value.to_string());

        let result: Vec<u8> = js_value.try_into().unwrap();
        assert_eq!(result, bytes.to_vec());
    }

    #[test]
    fn test_conversion_between_hashmap() {
        let map = HashMap::from([("a", 1), ("b", 2)]);
        let js_value = JSValue::from_hashmap(map);
        assert_eq!("[object Object]", js_value.to_string());

        let result: HashMap<String, JSValue> = js_value.try_into().unwrap();
        assert_eq!(
            result,
            HashMap::from([
                ("a".to_string(), JSValue::Int(1)),
                ("b".to_string(), JSValue::Int(2)),
            ])
        );
    }
}