summaryrefslogtreecommitdiffstats
path: root/js/rust/tests/callback.rs
blob: de75f97d26ea472326bfdbb7ea60a71b500335b3 (plain)
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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

#[macro_use]
extern crate js;
extern crate libc;

use js::ar::AutoRealm;
use js::glue::JSEncodeStringToUTF8;
use js::jsapi::root::JSContext;
use js::jsapi::root::JS_DefineFunction;
use js::jsapi::root::JS_NewGlobalObject;
use js::jsapi::root::JS_ReportErrorASCII;
use js::jsapi::root::JS::CallArgs;
use js::jsapi::root::JS::OnNewGlobalHookOption;
use js::jsapi::root::JS::RealmOptions;
use js::jsapi::root::JS::Value;
use js::jsval::UndefinedValue;
use js::rust::{Runtime, SIMPLE_GLOBAL_CLASS};

use std::ffi::CStr;
use std::ptr;
use std::str;

#[test]
fn callback() {
    let runtime = Runtime::new(false).unwrap();
    let context = runtime.cx();
    let h_option = OnNewGlobalHookOption::FireOnNewGlobalHook;
    let c_option = RealmOptions::default();

    unsafe {
        let global = JS_NewGlobalObject(
            context,
            &SIMPLE_GLOBAL_CLASS,
            ptr::null_mut(),
            h_option,
            &c_option,
        );
        rooted!(in(context) let global_root = global);
        let global = global_root.handle();
        let _ar = AutoRealm::with_obj(context, global.get());
        let function = JS_DefineFunction(
            context,
            global,
            b"puts\0".as_ptr() as *const libc::c_char,
            Some(puts),
            1,
            0,
        );
        assert!(!function.is_null());
        let javascript = "puts('Test Iñtërnâtiônàlizætiøn ┬─┬ノ( º _ ºノ) ');";
        rooted!(in(context) let mut rval = UndefinedValue());
        let _ = runtime.evaluate_script(global, javascript, "test.js", 0, rval.handle_mut());
    }
}

unsafe extern "C" fn puts(context: *mut JSContext, argc: u32, vp: *mut Value) -> bool {
    let args = CallArgs::from_vp(vp, argc);

    if args._base.argc_ != 1 {
        JS_ReportErrorASCII(
            context,
            b"puts() requires exactly 1 argument\0".as_ptr() as *const libc::c_char,
        );
        return false;
    }

    let arg = args.get(0);
    let js = js::rust::ToString(context, arg);
    rooted!(in(context) let message_root = js);
    let message = JSEncodeStringToUTF8(context, message_root.handle());
    let message = CStr::from_ptr(message);
    println!("{}", str::from_utf8(message.to_bytes()).unwrap());

    args.rval().set(UndefinedValue());
    return true;
}