#[cfg(test)]
mod tests;
use super::function::{make_builtin_fn, make_constructor_fn};
use crate::{
builtins::{
object::ObjectData,
value::{ResultValue, Value},
},
exec::Interpreter,
BoaProfiler,
};
#[derive(Debug, Clone, Copy)]
pub(crate) struct Boolean;
impl Boolean {
pub(crate) const NAME: &'static str = "Boolean";
pub(crate) const LENGTH: usize = 1;
fn this_boolean_value(value: &Value, ctx: &mut Interpreter) -> Result<bool, Value> {
match value {
Value::Boolean(boolean) => return Ok(*boolean),
Value::Object(ref object) => {
let object = object.borrow();
if let Some(boolean) = object.as_boolean() {
return Ok(boolean);
}
}
_ => {}
}
Err(ctx.construct_type_error("'this' is not a boolean"))
}
pub(crate) fn construct_boolean(
this: &Value,
args: &[Value],
_: &mut Interpreter,
) -> ResultValue {
let data = args.get(0).map(|x| x.to_boolean()).unwrap_or(false);
this.set_data(ObjectData::Boolean(data));
Ok(Value::from(data))
}
#[allow(clippy::wrong_self_convention)]
pub(crate) fn to_string(this: &Value, _: &[Value], ctx: &mut Interpreter) -> ResultValue {
let boolean = Self::this_boolean_value(this, ctx)?;
Ok(Value::from(boolean.to_string()))
}
#[inline]
pub(crate) fn value_of(this: &Value, _: &[Value], ctx: &mut Interpreter) -> ResultValue {
Ok(Value::from(Self::this_boolean_value(this, ctx)?))
}
pub(crate) fn create(global: &Value) -> Value {
let prototype = Value::new_object(Some(global));
make_builtin_fn(Self::to_string, "toString", &prototype, 0);
make_builtin_fn(Self::value_of, "valueOf", &prototype, 0);
make_constructor_fn(
Self::NAME,
Self::LENGTH,
Self::construct_boolean,
global,
prototype,
true,
)
}
#[inline]
pub(crate) fn init(global: &Value) -> (&str, Value) {
let _timer = BoaProfiler::global().start_event(Self::NAME, "init");
(Self::NAME, Self::create(global))
}
}