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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
use crate::jsutils::JsError;
use crate::quickjsrealmadapter::QuickJsRealmAdapter;
use crate::quickjsvalueadapter::QuickJsValueAdapter;
use core::ptr;
use libquickjs_sys as q;
use std::os::raw::c_char;

pub fn to_bool(value_ref: &QuickJsValueAdapter) -> Result<bool, JsError> {
    if value_ref.is_bool() {
        let r = value_ref.borrow_value();
        let raw = unsafe { r.u.int32 };
        let val: bool = raw > 0;
        Ok(val)
    } else {
        Err(JsError::new_str("value is not a boolean"))
    }
}

pub fn from_bool(b: bool) -> QuickJsValueAdapter {
    let raw = unsafe { q::JS_NewBool(ptr::null_mut(), b) };
    QuickJsValueAdapter::new_no_context(raw, "primitives::from_bool")
}

pub fn to_f64(value_ref: &QuickJsValueAdapter) -> Result<f64, JsError> {
    if value_ref.is_f64() {
        let r = value_ref.borrow_value();
        let val = unsafe { r.u.float64 };
        Ok(val)
    } else {
        Err(JsError::new_str("value was not a float64"))
    }
}

pub fn from_f64(f: f64) -> QuickJsValueAdapter {
    let raw = unsafe { q::JS_NewFloat64(ptr::null_mut(), f) };
    QuickJsValueAdapter::new_no_context(raw, "primitives::from_f64")
}

pub fn to_i32(value_ref: &QuickJsValueAdapter) -> Result<i32, JsError> {
    if value_ref.is_i32() {
        let r = value_ref.borrow_value();
        let val: i32 = unsafe { r.u.int32 };
        Ok(val)
    } else {
        Err(JsError::new_str("val is not an int"))
    }
}

pub fn from_i32(i: i32) -> QuickJsValueAdapter {
    let raw = unsafe { q::JS_NewInt32(ptr::null_mut(), i) };
    QuickJsValueAdapter::new_no_context(raw, "primitives::from_i32")
}

pub fn to_string_q(
    q_ctx: &QuickJsRealmAdapter,
    value_ref: &QuickJsValueAdapter,
) -> Result<String, JsError> {
    unsafe { to_string(q_ctx.context, value_ref) }
}
/// # Safety
/// When passing a context pointer please make sure the corresponding QuickJsContext is still valid
pub unsafe fn to_string(
    context: *mut q::JSContext,
    value_ref: &QuickJsValueAdapter,
) -> Result<String, JsError> {
    //log::trace!("primitives::to_string on {}", value_ref.borrow_value().tag);

    assert!(value_ref.is_string());

    let mut len = 0;

    let ptr: *const c_char = q::JS_ToCStringLen2(context, &mut len, *value_ref.borrow_value(), 0);

    if len == 0 {
        return Ok("".to_string());
    }

    if ptr.is_null() {
        return Err(JsError::new_str(
            "Could not convert string: got a null pointer",
        ));
    }

    let cstr = std::ffi::CStr::from_ptr(ptr);

    let s = cstr.to_string_lossy().into_owned();

    // Free the c string.
    q::JS_FreeCString(context, ptr);

    Ok(s)
}

/// # Safety
/// When passing a context pointer please make sure the corresponding QuickJsContext is still valid
pub unsafe fn to_str(
    context: *mut q::JSContext,
    value_ref: &QuickJsValueAdapter,
) -> Result<&str, JsError> {
    //log::trace!("primitives::to_str on {}", value_ref.borrow_value().tag);

    assert!(value_ref.is_string());

    let mut len = 0;

    let ptr: *const c_char = q::JS_ToCStringLen2(context, &mut len, *value_ref.borrow_value(), 0);
    // Free the c string.
    q::JS_FreeCString(context, ptr);
    // ptr should still be valid as long as value_ref lives

    if len == 0 {
        return Ok("");
    }

    if ptr.is_null() {
        return Err(JsError::new_str(
            "Could not convert string: got a null pointer",
        ));
    }

    let cstr = std::ffi::CStr::from_ptr(ptr);
    Ok(cstr.to_str().expect("bad cstr bad!"))

    //let s = cstr.to_string_lossy();

    //Ok(s.as_ref())
}

pub fn from_string_q(q_ctx: &QuickJsRealmAdapter, s: &str) -> Result<QuickJsValueAdapter, JsError> {
    unsafe { from_string(q_ctx.context, s) }
}
/// # Safety
/// When passing a context pointer please make sure the corresponding QuickJsContext is still valid
pub unsafe fn from_string(
    context: *mut q::JSContext,
    s: &str,
) -> Result<QuickJsValueAdapter, JsError> {
    let qval = q::JS_NewStringLen(context, s.as_ptr() as *const c_char, s.len() as _);
    let ret = QuickJsValueAdapter::new(context, qval, false, true, "primitives::from_string qval");
    if ret.is_exception() {
        return Err(JsError::new_str("Could not create string in runtime"));
    }

    Ok(ret)
}

#[cfg(test)]
pub mod tests {

    use crate::facades::tests::init_test_rt;
    use crate::jsutils::Script;

    #[tokio::test]
    async fn test_emoji() {
        let rt = init_test_rt();

        let res = rt.eval(None, Script::new("testEmoji.js", "'hi'")).await;

        match res {
            Ok(fac) => {
                assert_eq!(fac.get_str(), "hi");
            }
            Err(e) => {
                panic!("script failed: {}", e);
            }
        }

        let res = rt.eval(None, Script::new("testEmoji.js", "'👍'")).await;

        match res {
            Ok(fac) => {
                assert_eq!(fac.get_str(), "👍");
            }
            Err(e) => {
                panic!("script failed: {}", e);
            }
        }

        let res = rt.eval(None, Script::new("testEmoji.js", "'pre👍'")).await;

        match res {
            Ok(fac) => {
                assert_eq!(fac.get_str(), "pre👍");
            }
            Err(e) => {
                panic!("script failed: {}", e);
            }
        }

        let res = rt.eval(None, Script::new("testEmoji.js", "'👍post'")).await;

        match res {
            Ok(fac) => {
                assert_eq!(fac.get_str(), "👍post");
            }
            Err(e) => {
                panic!("script failed: {}", e);
            }
        }

        let res = rt
            .eval(None, Script::new("testEmoji.js", "'pre👍post'"))
            .await;

        match res {
            Ok(fac) => {
                assert_eq!(fac.get_str(), "pre👍post");
            }
            Err(e) => {
                panic!("script failed: {}", e);
            }
        }

        let res = rt
            .eval(
                None,
                Script::new("testEmoji.js", "JSON.stringify({c: '👍'})"),
            )
            .await;

        match res {
            Ok(fac) => {
                assert_eq!(fac.get_str(), "{\"c\":\"👍\"}");
            }
            Err(e) => {
                panic!("script failed: {}", e);
            }
        }
    }
}