Skip to main content

boa_engine/object/builtins/
jsmap_iterator.rs

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