boa_engine/object/builtins/
jsweakset.rs1use std::ops::Deref;
3
4use boa_gc::{Finalize, Trace};
5
6use crate::{
7 Context, JsResult, JsValue,
8 builtins::weak_set::{NativeWeakSet, WeakSet},
9 error::JsNativeError,
10 object::JsObject,
11 value::TryFromJs,
12};
13
14#[derive(Debug, Clone, Trace, Finalize)]
16pub struct JsWeakSet {
17 inner: JsObject,
18}
19
20impl JsWeakSet {
21 #[inline]
28 pub fn new(context: &mut Context) -> Self {
29 Self {
30 inner: JsObject::from_proto_and_data_with_shared_shape(
31 context.root_shape(),
32 context.intrinsics().constructors().weak_set().prototype(),
33 NativeWeakSet::new(),
34 )
35 .upcast(),
36 }
37 }
38
39 #[inline]
47 pub fn add(&self, value: &JsObject, context: &mut Context) -> JsResult<Self> {
48 WeakSet::add(&self.inner.clone().into(), &[value.clone().into()], context)?;
49 Ok(self.clone())
50 }
51
52 #[inline]
60 pub fn delete(&self, value: &JsObject, context: &mut Context) -> JsResult<bool> {
61 WeakSet::delete(&self.inner.clone().into(), &[value.clone().into()], context)
62 .map(|v| v.as_boolean().unwrap_or(false))
63 }
64
65 #[inline]
72 pub fn has(&self, value: &JsObject, context: &mut Context) -> JsResult<bool> {
73 WeakSet::has(&self.inner.clone().into(), &[value.clone().into()], context)
74 .map(|v| v.as_boolean().unwrap_or(false))
75 }
76
77 #[inline]
80 pub fn from_object(object: JsObject) -> Result<Self, JsObject> {
81 if object.downcast_ref::<NativeWeakSet>().is_some() {
82 Ok(Self { inner: object })
83 } else {
84 Err(object)
85 }
86 }
87}
88
89impl From<JsWeakSet> for JsObject {
90 #[inline]
91 fn from(o: JsWeakSet) -> Self {
92 o.inner.clone()
93 }
94}
95
96impl From<JsWeakSet> for JsValue {
97 #[inline]
98 fn from(o: JsWeakSet) -> Self {
99 o.inner.clone().into()
100 }
101}
102
103impl Deref for JsWeakSet {
104 type Target = JsObject;
105 #[inline]
106 fn deref(&self) -> &Self::Target {
107 &self.inner
108 }
109}
110
111impl TryFromJs for JsWeakSet {
112 fn try_from_js(value: &JsValue, _context: &mut Context) -> JsResult<Self> {
113 if let Some(o) = value.as_object()
114 && let Ok(weak_set) = Self::from_object(o.clone())
115 {
116 Ok(weak_set)
117 } else {
118 Err(JsNativeError::typ()
119 .with_message("value is not a WeakSet object")
120 .into())
121 }
122 }
123}