script_bindings/
constant.rs1use std::ffi::CStr;
8
9use js::context::JSContext;
10use js::jsval::{BooleanValue, DoubleValue, Int32Value, JSVal, NullValue, UInt32Value};
11use js::rooted;
12use js::rust::HandleObject;
13
14use crate::js::{JS_DefineProperty, PropertyFlags};
15
16#[derive(Clone)]
18pub struct ConstantSpec {
19 pub name: &'static CStr,
21 pub value: ConstantVal,
23}
24
25#[derive(Clone)]
27#[expect(dead_code)]
28pub enum ConstantVal {
29 Int(i32),
31 Uint(u32),
33 Double(f64),
35 Bool(bool),
37 Null,
39}
40
41impl ConstantSpec {
42 pub fn get_value(&self) -> JSVal {
44 match self.value {
45 ConstantVal::Null => NullValue(),
46 ConstantVal::Int(i) => Int32Value(i),
47 ConstantVal::Uint(u) => UInt32Value(u),
48 ConstantVal::Double(d) => DoubleValue(d),
49 ConstantVal::Bool(b) => BooleanValue(b),
50 }
51 }
52}
53
54pub fn define_constants(cx: &mut JSContext, obj: HandleObject, constants: &[ConstantSpec]) {
57 for spec in constants {
58 rooted!(&in(cx) let value = spec.get_value());
59 assert!(JS_DefineProperty(
60 cx,
61 obj,
62 spec.name,
63 value.handle(),
64 PropertyFlags::ENUMERABLE,
65 ));
66 }
67}