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
use crate::script_runtime::JSContext;
use js::jsapi::JSPROP_READONLY;
use js::jsapi::{JSPROP_ENUMERATE, JSPROP_PERMANENT};
use js::jsval::{BooleanValue, DoubleValue, Int32Value, JSVal, NullValue, UInt32Value};
use js::rust::wrappers::JS_DefineProperty;
use js::rust::HandleObject;
#[derive(Clone)]
pub struct ConstantSpec {
pub name: &'static [u8],
pub value: ConstantVal,
}
#[derive(Clone)]
#[allow(dead_code)]
pub enum ConstantVal {
IntVal(i32),
UintVal(u32),
DoubleVal(f64),
BoolVal(bool),
NullVal,
}
impl ConstantSpec {
pub fn get_value(&self) -> JSVal {
match self.value {
ConstantVal::NullVal => NullValue(),
ConstantVal::IntVal(i) => Int32Value(i),
ConstantVal::UintVal(u) => UInt32Value(u),
ConstantVal::DoubleVal(d) => DoubleValue(d),
ConstantVal::BoolVal(b) => BooleanValue(b),
}
}
}
pub fn define_constants(cx: JSContext, obj: HandleObject, constants: &[ConstantSpec]) {
for spec in constants {
rooted!(in(*cx) let value = spec.get_value());
unsafe {
assert!(JS_DefineProperty(
*cx,
obj,
spec.name.as_ptr() as *const libc::c_char,
value.handle(),
(JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT) as u32
));
}
}
}