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::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/// Representation of an IDL constant.
18#[derive(Clone)]
19pub struct ConstantSpec {
20    /// name of the constant.
21    pub name: &'static CStr,
22    /// value of the constant.
23    pub value: ConstantVal,
24}
25
26/// Representation of an IDL constant value.
27#[derive(Clone)]
28#[allow(dead_code)]
29pub enum ConstantVal {
30    /// `long` constant.
31    Int(i32),
32    /// `unsigned long` constant.
33    Uint(u32),
34    /// `double` constant.
35    Double(f64),
36    /// `boolean` constant.
37    Bool(bool),
38    /// `null` constant.
39    Null,
40}
41
42impl ConstantSpec {
43    /// Returns a `JSVal` that represents the value of this `ConstantSpec`.
44    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
55/// Defines constants on `obj`.
56/// Fails on JSAPI failure.
57pub 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}