Skip to main content

boa_engine/object/builtins/
jsset_iterator.rs

1//! A Rust API wrapper for Boa's `SetIterator` Builtin ECMAScript Object
2use std::ops::Deref;
3
4use boa_gc::{Finalize, Trace};
5
6use crate::{
7    Context, JsResult, JsValue, builtins::set::SetIterator, error::JsNativeError, object::JsObject,
8    value::TryFromJs,
9};
10
11/// `JsSetIterator` provides a wrapper for Boa's implementation of the ECMAScript `SetIterator` object
12#[derive(Debug, Clone, Finalize, Trace)]
13pub struct JsSetIterator {
14    inner: JsObject,
15}
16
17impl JsSetIterator {
18    /// Create a `JsSetIterator` from a `JsObject`.
19    /// If object is not a `SetIterator`, throw `TypeError`.
20    pub fn from_object(object: JsObject) -> JsResult<Self> {
21        if object.is::<SetIterator>() {
22            Ok(Self { inner: object })
23        } else {
24            Err(JsNativeError::typ()
25                .with_message("object is not a SetIterator")
26                .into())
27        }
28    }
29    /// Advances the `JsSetIterator` and gets the next result in the `JsSet`.
30    pub fn next(&self, context: &mut Context) -> JsResult<JsValue> {
31        SetIterator::next(&self.inner.clone().into(), &[JsValue::null()], context)
32    }
33}
34
35impl From<JsSetIterator> for JsObject {
36    #[inline]
37    fn from(o: JsSetIterator) -> Self {
38        o.inner.clone()
39    }
40}
41
42impl From<JsSetIterator> for JsValue {
43    #[inline]
44    fn from(o: JsSetIterator) -> Self {
45        o.inner.clone().into()
46    }
47}
48
49impl Deref for JsSetIterator {
50    type Target = JsObject;
51
52    #[inline]
53    fn deref(&self) -> &Self::Target {
54        &self.inner
55    }
56}
57
58impl TryFromJs for JsSetIterator {
59    fn try_from_js(value: &JsValue, _context: &mut Context) -> JsResult<Self> {
60        if let Some(o) = value.as_object() {
61            Self::from_object(o.clone())
62        } else {
63            Err(JsNativeError::typ()
64                .with_message("value is not a SetIterator object")
65                .into())
66        }
67    }
68}