Skip to main content

script_bindings/
constant.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5//! WebIDL constants.
6
7use std::ffi::CStr;
8
9use js::context::JSContext;
10use js::jsapi::{JSPROP_ENUMERATE, JSPROP_PERMANENT, JSPROP_READONLY};
11use js::jsval::{BooleanValue, DoubleValue, Int32Value, JSVal, NullValue, UInt32Value};
12use js::rooted;
13use js::rust::HandleObject;
14use js::rust::wrappers2::JS_DefineProperty;
15
16/// Representation of an IDL constant.
17#[derive(Clone)]
18pub struct ConstantSpec {
19    /// name of the constant.
20    pub name: &'static CStr,
21    /// value of the constant.
22    pub value: ConstantVal,
23}
24
25/// Representation of an IDL constant value.
26#[derive(Clone)]
27#[expect(dead_code)]
28pub enum ConstantVal {
29    /// `long` constant.
30    Int(i32),
31    /// `unsigned long` constant.
32    Uint(u32),
33    /// `double` constant.
34    Double(f64),
35    /// `boolean` constant.
36    Bool(bool),
37    /// `null` constant.
38    Null,
39}
40
41impl ConstantSpec {
42    /// Returns a `JSVal` that represents the value of this `ConstantSpec`.
43    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
54/// Defines constants on `obj`.
55/// Fails on JSAPI failure.
56pub 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        unsafe {
60            assert!(JS_DefineProperty(
61                cx,
62                obj,
63                spec.name.as_ptr(),
64                value.handle(),
65                (JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT) as u32
66            ));
67        }
68    }
69}