#[cfg(test)]
mod tests;
use super::function::{make_builtin_fn, make_constructor_fn};
use crate::{object::ObjectData, BoaProfiler, Context, Result, Value};
#[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 Context) -> Result<bool> {
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 Context,
) -> Result<Value> {
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 Context) -> Result<Value> {
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 Context) -> Result<Value> {
Ok(Value::from(Self::this_boolean_value(this, ctx)?))
}
#[inline]
pub(crate) fn init(interpreter: &mut Context) -> (&'static str, Value) {
let global = interpreter.global_object();
let _timer = BoaProfiler::global().start_event(Self::NAME, "init");
let prototype = Value::new_object(Some(global));
make_builtin_fn(Self::to_string, "toString", &prototype, 0, interpreter);
make_builtin_fn(Self::value_of, "valueOf", &prototype, 0, interpreter);
let boolean_object = make_constructor_fn(
Self::NAME,
Self::LENGTH,
Self::construct_boolean,
global,
prototype,
true,
true,
);
(Self::NAME, boolean_object)
}
}