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 http://mozilla.org/MPL/2.0/. */
4 
5 //! WebIDL constants.
6 
7 use js::jsapi::{HandleObject, JSContext, JSPROP_ENUMERATE, JSPROP_PERMANENT};
8 use js::jsapi::{JSPROP_READONLY, JS_DefineProperty};
9 use js::jsval::{BooleanValue, DoubleValue, Int32Value, JSVal, NullValue, UInt32Value};
10 use libc;
11 
12 /// Representation of an IDL constant.
13 #[derive(Clone)]
14 pub struct ConstantSpec {
15     /// name of the constant.
16     pub name: &'static [u8],
17     /// value of the constant.
18     pub value: ConstantVal,
19 }
20 
21 /// Representation of an IDL constant value.
22 #[derive(Clone)]
23 #[allow(dead_code)]
24 pub enum ConstantVal {
25     /// `long` constant.
26     IntVal(i32),
27     /// `unsigned long` constant.
28     UintVal(u32),
29     /// `double` constant.
30     DoubleVal(f64),
31     /// `boolean` constant.
32     BoolVal(bool),
33     /// `null` constant.
34     NullVal,
35 }
36 
37 impl ConstantSpec {
38     /// Returns a `JSVal` that represents the value of this `ConstantSpec`.
get_value(&self) -> JSVal39     pub fn get_value(&self) -> JSVal {
40         match self.value {
41             ConstantVal::NullVal => NullValue(),
42             ConstantVal::IntVal(i) => Int32Value(i),
43             ConstantVal::UintVal(u) => UInt32Value(u),
44             ConstantVal::DoubleVal(d) => DoubleValue(d),
45             ConstantVal::BoolVal(b) => BooleanValue(b),
46         }
47     }
48 }
49 
50 /// Defines constants on `obj`.
51 /// Fails on JSAPI failure.
define_constants( cx: *mut JSContext, obj: HandleObject, constants: &[ConstantSpec])52 pub unsafe fn define_constants(
53         cx: *mut JSContext,
54         obj: HandleObject,
55         constants: &[ConstantSpec]) {
56     for spec in constants {
57         rooted!(in(cx) let value = spec.get_value());
58         assert!(JS_DefineProperty(cx,
59                                   obj,
60                                   spec.name.as_ptr() as *const libc::c_char,
61                                   value.handle(),
62                                   JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT,
63                                   None,
64                                   None));
65     }
66 }
67