forked from yorkie/rust.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
console.rs
64 lines (53 loc) · 1.77 KB
/
console.rs
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
use util::v8;
use util::v8::ValueT;
use std::io::{self, Write};
fn stringify(obj: &v8::Value) -> v8::String {
let global = v8::Context::Global();
let JSON = global.Get(v8::String::NewFromUtf8("JSON")).ToObject();
let stringify: v8::Function = v8::Function::Cast(
&JSON.Get(v8::String::NewFromUtf8("stringify")));
let replacer = v8::Number::NewFromInt32(0);
let space = v8::Number::NewFromInt32(2);
stringify.Call(JSON,
&[obj, &replacer.as_val(), &space.as_val()]).ToString()
}
extern fn info(arguments: v8::FunctionCallbackInfo) {
let firstArg = arguments.At(0);
let msg;
if firstArg.IsString() || firstArg.IsFunction() {
msg = firstArg.ToString();
} else {
msg = stringify(&firstArg);
}
let stdout = io::stdout();
let mut handle = stdout.lock();
match handle.write_fmt(
format_args!("{}\n", msg.as_string())) {
Ok(v) => v,
Err(err) => println!("{:?}", err),
}
}
extern fn warn(arguments: v8::FunctionCallbackInfo) {
let firstArg = arguments.At(0);
let msg;
if firstArg.IsString() || firstArg.IsFunction() {
msg = firstArg.ToString();
} else {
msg = stringify(&firstArg);
}
let stderr = io::stderr();
let mut handle = stderr.lock();
match handle.write_fmt(
format_args!("{}\n", msg.as_string())) {
Ok(v) => v,
Err(err) => println!("{:?}", err),
}
}
pub fn Init() -> v8::Object {
let Console = v8::Object::New();
Console.Set(v8::String::NewFromUtf8("log"), v8::FunctionTemplate::New(info).GetFunction());
Console.Set(v8::String::NewFromUtf8("info"), v8::FunctionTemplate::New(info).GetFunction());
Console.Set(v8::String::NewFromUtf8("warn"), v8::FunctionTemplate::New(warn).GetFunction());
Console.Set(v8::String::NewFromUtf8("error"), v8::FunctionTemplate::New(warn).GetFunction());
Console
}