boa/builtins/set/
set_iterator.rs

1use crate::{
2    builtins::function::make_builtin_fn,
3    builtins::iterable::create_iter_result_object,
4    builtins::Array,
5    builtins::JsValue,
6    object::{JsObject, ObjectData},
7    property::{PropertyDescriptor, PropertyNameKind},
8    symbol::WellKnownSymbols,
9    BoaProfiler, Context, JsResult,
10};
11use gc::{Finalize, Trace};
12
13/// The Set Iterator object represents an iteration over a set. It implements the iterator protocol.
14///
15/// More information:
16///  - [ECMAScript reference][spec]
17///
18/// [spec]: https://tc39.es/ecma262/#sec-set-iterator-objects
19#[derive(Debug, Clone, Finalize, Trace)]
20pub struct SetIterator {
21    iterated_set: JsValue,
22    next_index: usize,
23    iteration_kind: PropertyNameKind,
24}
25
26impl SetIterator {
27    pub(crate) const NAME: &'static str = "SetIterator";
28
29    /// Constructs a new `SetIterator`, that will iterate over `set`, starting at index 0
30    fn new(set: JsValue, kind: PropertyNameKind) -> Self {
31        SetIterator {
32            iterated_set: set,
33            next_index: 0,
34            iteration_kind: kind,
35        }
36    }
37
38    /// Abstract operation CreateSetIterator( set, kind )
39    ///
40    /// Creates a new iterator over the given set.
41    ///
42    /// More information:
43    ///  - [ECMA reference][spec]
44    ///
45    /// [spec]: https://www.ecma-international.org/ecma-262/11.0/index.html#sec-createsetiterator
46    pub(crate) fn create_set_iterator(
47        set: JsValue,
48        kind: PropertyNameKind,
49        context: &Context,
50    ) -> JsValue {
51        let set_iterator = JsValue::new_object(context);
52        set_iterator.set_data(ObjectData::set_iterator(Self::new(set, kind)));
53        set_iterator
54            .as_object()
55            .expect("set iterator object")
56            .set_prototype_instance(context.iterator_prototypes().set_iterator().into());
57        set_iterator
58    }
59
60    /// %SetIteratorPrototype%.next( )
61    ///
62    /// Advances the iterator and gets the next result in the set.
63    ///
64    /// More information:
65    ///  - [ECMA reference][spec]
66    ///
67    /// [spec]: https://tc39.es/ecma262/#sec-%setiteratorprototype%.next
68    pub(crate) fn next(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
69        if let JsValue::Object(ref object) = this {
70            let mut object = object.borrow_mut();
71            if let Some(set_iterator) = object.as_set_iterator_mut() {
72                let m = &set_iterator.iterated_set;
73                let mut index = set_iterator.next_index;
74                let item_kind = &set_iterator.iteration_kind;
75
76                if set_iterator.iterated_set.is_undefined() {
77                    return Ok(create_iter_result_object(
78                        JsValue::undefined(),
79                        true,
80                        context,
81                    ));
82                }
83
84                if let JsValue::Object(ref object) = m {
85                    if let Some(entries) = object.borrow().as_set_ref() {
86                        let num_entries = entries.size();
87                        while index < num_entries {
88                            let e = entries.get_index(index);
89                            index += 1;
90                            set_iterator.next_index = index;
91                            if let Some(value) = e {
92                                match item_kind {
93                                    PropertyNameKind::Value => {
94                                        return Ok(create_iter_result_object(
95                                            value.clone(),
96                                            false,
97                                            context,
98                                        ));
99                                    }
100                                    PropertyNameKind::KeyAndValue => {
101                                        let result = Array::create_array_from_list(
102                                            [value.clone(), value.clone()],
103                                            context,
104                                        );
105                                        return Ok(create_iter_result_object(
106                                            result.into(),
107                                            false,
108                                            context,
109                                        ));
110                                    }
111                                    PropertyNameKind::Key => {
112                                        panic!("tried to collect only keys of Set")
113                                    }
114                                }
115                            }
116                        }
117                    } else {
118                        return Err(context.construct_type_error("'this' is not a Set"));
119                    }
120                } else {
121                    return Err(context.construct_type_error("'this' is not a Set"));
122                }
123
124                set_iterator.iterated_set = JsValue::undefined();
125                Ok(create_iter_result_object(
126                    JsValue::undefined(),
127                    true,
128                    context,
129                ))
130            } else {
131                context.throw_type_error("`this` is not an SetIterator")
132            }
133        } else {
134            context.throw_type_error("`this` is not an SetIterator")
135        }
136    }
137
138    /// Create the %SetIteratorPrototype% object
139    ///
140    /// More information:
141    ///  - [ECMA reference][spec]
142    ///
143    /// [spec]: https://tc39.es/ecma262/#sec-%setiteratorprototype%-object
144    pub(crate) fn create_prototype(iterator_prototype: JsValue, context: &mut Context) -> JsObject {
145        let _timer = BoaProfiler::global().start_event(Self::NAME, "init");
146
147        // Create prototype
148        let set_iterator = context.construct_object();
149        make_builtin_fn(Self::next, "next", &set_iterator, 0, context);
150        set_iterator.set_prototype_instance(iterator_prototype);
151
152        let to_string_tag = WellKnownSymbols::to_string_tag();
153        let to_string_tag_property = PropertyDescriptor::builder()
154            .value("Set Iterator")
155            .writable(false)
156            .enumerable(false)
157            .configurable(true);
158        set_iterator.insert(to_string_tag, to_string_tag_property);
159        set_iterator
160    }
161}