#[cfg(test)]
mod tests;
use crate::{
builtins::BuiltIn,
object::{ConstructorBuilder, ObjectData, PROTOTYPE},
property::Attribute,
BoaProfiler, Context, Result, Value,
};
#[derive(Debug, Clone, Copy)]
pub(crate) struct Boolean;
impl BuiltIn for Boolean {
const NAME: &'static str = "Boolean";
fn attribute() -> Attribute {
Attribute::WRITABLE | Attribute::NON_ENUMERABLE | Attribute::CONFIGURABLE
}
fn init(context: &mut Context) -> (&'static str, Value, Attribute) {
let _timer = BoaProfiler::global().start_event(Self::NAME, "init");
let boolean_object = ConstructorBuilder::with_standard_object(
context,
Self::constructor,
context.standard_objects().boolean_object().clone(),
)
.name(Self::NAME)
.length(Self::LENGTH)
.method(Self::to_string, "toString", 0)
.method(Self::value_of, "valueOf", 0)
.build();
(Self::NAME, boolean_object.into(), Self::attribute())
}
}
impl Boolean {
pub(crate) const LENGTH: usize = 1;
pub(crate) fn constructor(
new_target: &Value,
args: &[Value],
context: &mut Context,
) -> Result<Value> {
let data = args.get(0).map(|x| x.to_boolean()).unwrap_or(false);
if new_target.is_undefined() {
return Ok(Value::from(data));
}
let prototype = new_target
.as_object()
.and_then(|obj| {
obj.get(&PROTOTYPE.into(), obj.clone().into(), context)
.map(|o| o.as_object())
.transpose()
})
.transpose()?
.unwrap_or_else(|| context.standard_objects().object_object().prototype());
let boolean = Value::new_object(context);
boolean
.as_object()
.expect("this should be an object")
.set_prototype_instance(prototype.into());
boolean.set_data(ObjectData::Boolean(data));
Ok(boolean)
}
fn this_boolean_value(value: &Value, context: &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(context.construct_type_error("'this' is not a boolean"))
}
#[allow(clippy::wrong_self_convention)]
pub(crate) fn to_string(this: &Value, _: &[Value], context: &mut Context) -> Result<Value> {
let boolean = Self::this_boolean_value(this, context)?;
Ok(Value::from(boolean.to_string()))
}
#[inline]
pub(crate) fn value_of(this: &Value, _: &[Value], context: &mut Context) -> Result<Value> {
Ok(Value::from(Self::this_boolean_value(this, context)?))
}
}