script_bindings/
constant.rs1use std::ffi::CStr;
8
9use js::jsapi::{JSPROP_ENUMERATE, JSPROP_PERMANENT, JSPROP_READONLY};
10use js::jsval::{BooleanValue, DoubleValue, Int32Value, JSVal, NullValue, UInt32Value};
11use js::rooted;
12use js::rust::HandleObject;
13use js::rust::wrappers::JS_DefineProperty;
14
15use crate::script_runtime::JSContext;
16
17#[derive(Clone)]
19pub struct ConstantSpec {
20 pub name: &'static CStr,
22 pub value: ConstantVal,
24}
25
26#[derive(Clone)]
28#[allow(dead_code)]
29pub enum ConstantVal {
30 Int(i32),
32 Uint(u32),
34 Double(f64),
36 Bool(bool),
38 Null,
40}
41
42impl ConstantSpec {
43 pub fn get_value(&self) -> JSVal {
45 match self.value {
46 ConstantVal::Null => NullValue(),
47 ConstantVal::Int(i) => Int32Value(i),
48 ConstantVal::Uint(u) => UInt32Value(u),
49 ConstantVal::Double(d) => DoubleValue(d),
50 ConstantVal::Bool(b) => BooleanValue(b),
51 }
52 }
53}
54
55pub fn define_constants(cx: JSContext, obj: HandleObject, constants: &[ConstantSpec]) {
58 for spec in constants {
59 rooted!(in(*cx) let value = spec.get_value());
60 unsafe {
61 assert!(JS_DefineProperty(
62 *cx,
63 obj,
64 spec.name.as_ptr(),
65 value.handle(),
66 (JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT) as u32
67 ));
68 }
69 }
70}