Skip to content

Truly independent web browser

LibJS: Keep the values of a Set in the Set itself

Andreas Kling52b23ec803fc
diff --git a/Libraries/LibJS/Rust/src/runtime/map.rs b/Libraries/LibJS/Rust/src/runtime/map.rs
index 8b37bb5de84..944f7fca23f 100644
--- a/Libraries/LibJS/Rust/src/runtime/map.rs
+++ b/Libraries/LibJS/Rust/src/runtime/map.rs
@@ -22,14 +22,32 @@ use crate::runtime::object::MayInterfereWithIndexedPropertyAccess;
use crate::runtime::realm::Realm;
use crate::runtime::value_traits::ValueTraitsKey;
+/// What a keyed collection keeps with each of its keys: a Map keeps a value, and a Set keeps nothing.
+pub(crate) trait StoredValue: Copy + Trace {
+ /// What the entry of a removed key holds.
+ const REMOVED: Self;
+}
+
+impl StoredValue for Value {
+ const REMOVED: Self = Value::UNDEFINED;
+}
+
+/// What a Set keeps with each of its values.
+#[derive(Clone, Copy, Trace)]
+pub(crate) struct NoValue;
+
+impl StoredValue for NoValue {
+ const REMOVED: Self = NoValue;
+}
+
#[derive(Trace)]
-struct StoredEntry {
+struct StoredEntry<V: StoredValue> {
key: Value,
- value: Value,
+ value: V,
insertion_id: u64,
}
-impl StoredEntry {
+impl<V: StoredValue> StoredEntry<V> {
fn is_removed(&self) -> bool {
self.key.is_empty()
}
@@ -42,53 +60,179 @@ const MAX_ENTRY_COUNT_WITHOUT_INDICES: usize = 8;
type Indices = HashMap<ValueTraitsKey, usize, foldhash::fast::RandomState>;
-#[derive(Default)]
-struct MapStorage {
+/// The entries of a Map or a Set.
+pub(crate) struct Storage<V: StoredValue> {
/// All entries in insertion order. Removed entries stay in place (as holes) until the next compaction, so the
/// positions held by iterators stay valid. Compacting or clearing moves entries, which bumps generation.
- entries: Vec<StoredEntry>,
+ entries: Vec<StoredEntry<V>>,
/// The position of every live entry by its key. None while there are few enough entries to search through.
- indices: Option<Indices>,
+ indices: Option<Box<Indices>>,
removed_entry_count: usize,
next_insertion_id: u64,
generation: u64,
- external_memory_size: usize,
}
// SAFETY: Visits the key and value of every entry. The keys of the indices are the keys of the live entries.
-unsafe impl Trace for MapStorage {
+unsafe impl<V: StoredValue> Trace for Storage<V> {
fn trace(&self, visitor: &mut Visitor) {
self.entries.trace(visitor);
}
}
-impl MapStorage {
- fn update_external_memory_size(&mut self) -> (usize, usize) {
- let old_size = self.external_memory_size;
- self.external_memory_size =
- (self.entries.capacity() * size_of::<StoredEntry>()).saturating_add(self.indices_allocation_size());
- (old_size, self.external_memory_size)
+impl<V: StoredValue> Storage<V> {
+ pub(crate) fn new(_: &DeferGc<'_>) -> Self {
+ Self {
+ entries: Vec::new(),
+ indices: None,
+ removed_entry_count: 0,
+ next_insertion_id: 0,
+ generation: 0,
+ }
+ }
+
+ /// Frees the entries of a collection that is finalized.
+ pub(crate) fn release(storage: &GcRefCell<Self>) {
+ drop(storage.replace(Self {
+ entries: Vec::new(),
+ indices: None,
+ removed_entry_count: 0,
+ next_insertion_id: 0,
+ generation: 0,
+ }));
}
- fn indices_allocation_size(&self) -> usize {
- self.indices.as_ref().map_or(0, |indices| indices.allocation_size())
+ /// Changes the storage of a collection, and tells the heap how much the memory of the storage changed.
+ pub(crate) fn modify<R>(storage: &GcRefCell<Self>, vm: &Vm, modify: impl FnOnce(&mut Self) -> R) -> R {
+ let mut storage = storage.borrow_mut(vm);
+ let old_size = storage.external_memory_size();
+ let result = modify(&mut storage);
+ let new_size = storage.external_memory_size();
+ drop(storage);
+ vm.heap().account_external_memory_change(old_size, new_size);
+ result
}
- fn live_entry_count(&self) -> usize {
+ /// Calls the callback with the key and value of every entry, in insertion order.
+ /// The callback must not modify the collection.
+ pub(crate) fn for_each_entry(storage: &GcRefCell<Self>, mut callback: impl FnMut(Value, V)) {
+ let (generation, entry_count) = {
+ let storage = storage.borrow();
+ (storage.generation, storage.entries.len())
+ };
+ for index in 0..entry_count {
+ let (key, value) = {
+ let entry = &storage.borrow().entries[index];
+ (entry.key, entry.value)
+ };
+ if !key.is_empty() {
+ callback(key, value);
+ }
+ }
+ let storage = storage.borrow();
+ assert!(generation == storage.generation && entry_count == storage.entries.len());
+ }
+
+ pub(crate) fn external_memory_size(&self) -> usize {
+ let indices_size = self.indices.as_ref().map_or(0, |indices| {
+ size_of::<Indices>().saturating_add(indices.allocation_size())
+ });
+ (self.entries.capacity() * size_of::<StoredEntry<V>>()).saturating_add(indices_size)
+ }
+
+ pub(crate) fn len(&self) -> usize {
self.entries.len() - self.removed_entry_count
}
+ pub(crate) fn clear(&mut self) {
+ self.entries = Vec::new();
+ self.indices = None;
+ self.removed_entry_count = 0;
+ self.generation += 1;
+ }
+
+ pub(crate) fn remove(&mut self, key: Value) -> bool {
+ let index = match &mut self.indices {
+ Some(indices) => indices.remove(&ValueTraitsKey(key)),
+ None => self.index_of(key),
+ };
+ let Some(index) = index else {
+ return false;
+ };
+
+ let entry = &mut self.entries[index];
+ entry.key = Value::EMPTY;
+ entry.value = V::REMOVED;
+ self.removed_entry_count += 1;
+
+ // Compact once removed entries outnumber the live ones, so removal stays amortized O(1).
+ const MINIMUM_REMOVED_ENTRY_COUNT_FOR_COMPACTION: usize = 8;
+ if self.removed_entry_count >= MINIMUM_REMOVED_ENTRY_COUNT_FOR_COMPACTION
+ && self.removed_entry_count > self.len()
+ {
+ self.compact_entries();
+ }
+ true
+ }
+
+ pub(crate) fn get(&self, key: Value) -> Option<V> {
+ let index = self.index_of(key)?;
+ Some(self.entries[index].value)
+ }
+
+ pub(crate) fn contains(&self, key: Value) -> bool {
+ self.index_of(key).is_some()
+ }
+
+ pub(crate) fn set(&mut self, key: Value, value: V) {
+ if let Some(indices) = &mut self.indices {
+ let new_index = self.entries.len();
+ let index = *indices.entry(ValueTraitsKey(key)).or_insert(new_index);
+ if index != new_index {
+ self.entries[index].value = value;
+ return;
+ }
+ } else {
+ if let Some(index) = self.index_of(key) {
+ self.entries[index].value = value;
+ return;
+ }
+ if self.entries.len() == MAX_ENTRY_COUNT_WITHOUT_INDICES {
+ if self.removed_entry_count > 0 {
+ self.compact_entries();
+ } else {
+ self.build_indices();
+ let new_index = self.entries.len();
+ self.indices
+ .as_mut()
+ .expect("the indices were just built")
+ .insert(ValueTraitsKey(key), new_index);
+ }
+ }
+ }
+ self.reserve_one_entry();
+ let insertion_id = self.next_insertion_id;
+ self.next_insertion_id += 1;
+ self.entries.push(StoredEntry {
+ key,
+ value,
+ insertion_id,
+ });
+ }
+
fn index_of(&self, key: Value) -> Option<usize> {
let key = ValueTraitsKey(key);
match &self.indices {
Some(indices) => indices.get(&key).copied(),
None => {
- // Most keys are found by identity. Only strings, BigInts, and NaNs can be the same value with
- // different bits.
+ // NB: The key of a removed entry is the empty value, so an empty key would find a removed entry.
+ assert!(!key.0.is_empty());
+
+ // Most keys are found by identity. Only strings and BigInts can be the same value with different
+ // bits: every NaN is the canonical NaN.
if let Some(index) = self.entries.iter().position(|entry| entry.key.0 == key.0.0) {
return Some(index);
}
- if !(key.0.is_string() || key.0.is_bigint() || key.0.is_nan()) {
+ if !(key.0.is_string() || key.0.is_bigint()) {
return None;
}
self.entries
@@ -109,10 +253,10 @@ impl MapStorage {
fn build_indices(&mut self) {
// NB: The indices hold keys, so they are built in place, where the entries keep those keys alive.
- let indices = self.indices.insert(Indices::with_capacity_and_hasher(
+ let indices = self.indices.insert(Box::new(Indices::with_capacity_and_hasher(
self.entries.len() + 1,
Default::default(),
- ));
+ )));
for (index, entry) in self.entries.iter().enumerate() {
if !entry.is_removed() {
indices.insert(ValueTraitsKey(entry.key), index);
@@ -126,30 +270,35 @@ impl MapStorage {
}
fn compact_entries(&mut self) {
- let mut new_indices = vec![0usize; self.entries.len()];
-
- let mut live_entry_count = 0;
- for (i, new_index) in new_indices.iter_mut().enumerate() {
- if self.entries[i].is_removed() {
- continue;
- }
- *new_index = live_entry_count;
- self.entries.swap(live_entry_count, i);
- live_entry_count += 1;
- }
- self.entries.truncate(live_entry_count);
- if self.entries.capacity() > live_entry_count * 2 {
- self.entries.shrink_to_fit();
- }
+ let live_entry_count = self.len();
// NB: A collection that keeps its indices until it is well below the limit does not build them again and again
// when its size moves around the limit.
if live_entry_count <= MAX_ENTRY_COUNT_WITHOUT_INDICES / 2 {
self.indices = None;
- } else if let Some(indices) = &mut self.indices {
+ }
+
+ if let Some(indices) = &mut self.indices {
+ let mut new_indices = vec![0usize; self.entries.len()];
+ let mut new_entry_count = 0;
+ for (i, new_index) in new_indices.iter_mut().enumerate() {
+ if self.entries[i].is_removed() {
+ continue;
+ }
+ *new_index = new_entry_count;
+ self.entries.swap(new_entry_count, i);
+ new_entry_count += 1;
+ }
+ self.entries.truncate(new_entry_count);
for index in indices.values_mut() {
*index = new_indices[*index];
}
+ } else {
+ self.entries.retain(|entry| !entry.is_removed());
+ }
+ assert!(self.entries.len() == live_entry_count);
+ if self.entries.capacity() > live_entry_count * 2 {
+ self.entries.shrink_to_fit();
}
self.removed_entry_count = 0;
@@ -157,6 +306,84 @@ impl MapStorage {
}
}
+/// A position in the entries of a collection that stays valid while the collection is modified, with the visiting rules
+/// of the spec's index-based loops: entries added during iteration are visited, removed entries are skipped, and
+/// entries that were moved by a compaction or cleared are found again by their insertion ID.
+#[derive(Trace)]
+pub(crate) struct Position {
+ /// The position of the current entry in the entries. Only meaningful while generation matches the storage.
+ index: Cell<usize>,
+ generation: Cell<u64>,
+
+ /// Every entry with a smaller insertion ID has already been visited or skipped.
+ next_insertion_id: Cell<u64>,
+ current_insertion_id: Cell<Option<u64>>,
+}
+
+impl Position {
+ pub(crate) fn first<V: StoredValue>(storage: &Storage<V>) -> Self {
+ Self {
+ index: Cell::new(0),
+ generation: Cell::new(storage.generation),
+ next_insertion_id: Cell::new(0),
+ current_insertion_id: Cell::new(None),
+ }
+ }
+
+ pub(crate) fn is_end<V: StoredValue>(&self, storage: &Storage<V>) -> bool {
+ self.find_current_entry(storage);
+ self.index.get() >= storage.entries.len()
+ }
+
+ /// This moves past the entry that is_end() or current() found last, even if that entry has been removed since, so
+ /// removing the current entry during iteration does not skip the entry after it.
+ pub(crate) fn advance<V: StoredValue>(&self, storage: &Storage<V>) {
+ if self.current_insertion_id.get().is_none() {
+ self.find_current_entry(storage);
+ if self.current_insertion_id.get().is_none() {
+ return;
+ }
+ }
+ let current_insertion_id = self
+ .current_insertion_id
+ .take()
+ .expect("the current entry was just found");
+ self.next_insertion_id.set(current_insertion_id + 1);
+ let index = self.index.get();
+ if self.generation.get() == storage.generation
+ && index < storage.entries.len()
+ && storage.entries[index].insertion_id < self.next_insertion_id.get()
+ {
+ self.index.set(index + 1);
+ }
+ }
+
+ pub(crate) fn current<V: StoredValue>(&self, storage: &Storage<V>) -> (Value, V) {
+ self.find_current_entry(storage);
+ let entry = &storage.entries[self.index.get()];
+ (entry.key, entry.value)
+ }
+
+ fn find_current_entry<V: StoredValue>(&self, storage: &Storage<V>) {
+ let entries = &storage.entries;
+ if self.generation.get() != storage.generation {
+ self.index
+ .set(storage.index_of_first_entry_not_inserted_before(self.next_insertion_id.get()));
+ self.generation.set(storage.generation);
+ }
+ let mut index = self.index.get();
+ while index < entries.len() && entries[index].is_removed() {
+ index += 1;
+ }
+ self.index.set(index);
+ if index < entries.len() {
+ self.current_insertion_id.set(Some(entries[index].insertion_id));
+ } else {
+ self.current_insertion_id.set(None);
+ }
+ }
+}
+
/// The key and value of a Map entry.
#[derive(Clone, Copy)]
pub struct Entry {
@@ -168,7 +395,7 @@ pub struct Entry {
#[derive(Trace)]
pub struct Map {
base: Object,
- storage: GcRefCell<MapStorage>,
+ storage: GcRefCell<Storage<Value>>,
}
define_cell!(
@@ -183,7 +410,7 @@ impl ExternalMemorySize for Map {
fn external_memory_size(&self) -> usize {
self.base
.external_memory_size()
- .saturating_add(self.storage.borrow().external_memory_size)
+ .saturating_add(self.storage.borrow().external_memory_size())
}
}
@@ -197,12 +424,12 @@ impl Deref for Map {
impl Finalize for Map {
fn finalize(&self) {
- drop(self.storage.replace(MapStorage::default()));
+ Storage::release(&self.storage);
}
}
impl Map {
- pub fn new(_: &DeferGc<'_>, vm: &Vm, realm: Gc<Realm>, prototype: Gc<Object>) -> Map {
+ pub fn new(defer_gc: &DeferGc<'_>, vm: &Vm, realm: Gc<Realm>, prototype: Gc<Object>) -> Map {
Map {
base: Object::new_with_prototype(
vm,
@@ -211,7 +438,7 @@ impl Map {
Some(prototype),
MayInterfereWithIndexedPropertyAccess::No,
),
- storage: GcRefCell::new(MapStorage::default()),
+ storage: GcRefCell::new(Storage::new(defer_gc)),
}
}
@@ -223,210 +450,67 @@ impl Map {
// 24.1.3.1 Map.prototype.clear ( ), https://tc39.es/ecma262/#sec-map.prototype.clear
pub fn map_clear(&self, vm: &Vm) {
- let mut storage = self.storage.borrow_mut(vm);
- storage.entries = Vec::new();
- storage.indices = None;
- storage.removed_entry_count = 0;
- storage.generation += 1;
- let (old_size, new_size) = storage.update_external_memory_size();
- drop(storage);
- vm.heap().account_external_memory_change(old_size, new_size);
+ Storage::modify(&self.storage, vm, Storage::clear);
}
// 24.1.3.3 Map.prototype.delete ( key ), https://tc39.es/ecma262/#sec-map.prototype.delete
pub fn map_remove(&self, vm: &Vm, key: Value) -> bool {
- let mut storage = self.storage.borrow_mut(vm);
- let index = match &mut storage.indices {
- Some(indices) => indices.remove(&ValueTraitsKey(key)),
- None => storage.index_of(key),
- };
- let Some(index) = index else {
- return false;
- };
-
- let entry = &mut storage.entries[index];
- entry.key = Value::EMPTY;
- entry.value = Value::UNDEFINED;
- storage.removed_entry_count += 1;
-
- // Compact once removed entries outnumber the live ones, so removal stays amortized O(1).
- const MINIMUM_REMOVED_ENTRY_COUNT_FOR_COMPACTION: usize = 8;
- if storage.removed_entry_count >= MINIMUM_REMOVED_ENTRY_COUNT_FOR_COMPACTION
- && storage.removed_entry_count > storage.live_entry_count()
- {
- storage.compact_entries();
- }
- let (old_size, new_size) = storage.update_external_memory_size();
- drop(storage);
- vm.heap().account_external_memory_change(old_size, new_size);
-
- true
+ Storage::modify(&self.storage, vm, |storage| storage.remove(key))
}
// 24.1.3.6 Map.prototype.get ( key ), https://tc39.es/ecma262/#sec-map.prototype.get
pub fn map_get(&self, key: Value) -> Option<Value> {
- let storage = self.storage.borrow();
- let index = storage.index_of(key)?;
- Some(storage.entries[index].value)
+ self.storage.borrow().get(key)
}
// 24.1.3.7 Map.prototype.has ( key ), https://tc39.es/ecma262/#sec-map.prototype.has
pub fn map_has(&self, key: Value) -> bool {
- self.storage.borrow().index_of(key).is_some()
+ self.storage.borrow().contains(key)
}
// 24.1.3.9 Map.prototype.set ( key, value ), https://tc39.es/ecma262/#sec-map.prototype.set
pub fn map_set(&self, vm: &Vm, key: Value, value: Value) {
- let mut storage_guard = self.storage.borrow_mut(vm);
- let storage = &mut *storage_guard;
- if let Some(indices) = &mut storage.indices {
- let new_index = storage.entries.len();
- let index = *indices.entry(ValueTraitsKey(key)).or_insert(new_index);
- if index != new_index {
- storage.entries[index].value = value;
- return;
- }
- } else {
- if let Some(index) = storage.index_of(key) {
- storage.entries[index].value = value;
- return;
- }
- if storage.entries.len() == MAX_ENTRY_COUNT_WITHOUT_INDICES {
- if storage.removed_entry_count > 0 {
- storage.compact_entries();
- } else {
- storage.build_indices();
- let new_index = storage.entries.len();
- storage
- .indices
- .as_mut()
- .expect("the indices were just built")
- .insert(ValueTraitsKey(key), new_index);
- }
- }
- }
- storage.reserve_one_entry();
- let insertion_id = storage.next_insertion_id;
- storage.next_insertion_id += 1;
- storage.entries.push(StoredEntry {
- key,
- value,
- insertion_id,
- });
- let (old_size, new_size) = storage.update_external_memory_size();
- drop(storage_guard);
- vm.heap().account_external_memory_change(old_size, new_size);
+ Storage::modify(&self.storage, vm, |storage| storage.set(key, value));
}
pub fn map_size(&self) -> usize {
- self.storage.borrow().live_entry_count()
+ self.storage.borrow().len()
}
/// Calls the callback with the key and value of every entry, in insertion order.
/// The callback must not modify the map.
- pub fn for_each_entry(&self, mut callback: impl FnMut(Value, Value)) {
- let (generation, entry_count) = {
- let storage = self.storage.borrow();
- (storage.generation, storage.entries.len())
- };
- for index in 0..entry_count {
- let (key, value) = {
- let entry = &self.storage.borrow().entries[index];
- (entry.key, entry.value)
- };
- if !key.is_empty() {
- callback(key, value);
- }
- }
- let storage = self.storage.borrow();
- assert!(generation == storage.generation && entry_count == storage.entries.len());
+ pub fn for_each_entry(&self, callback: impl FnMut(Value, Value)) {
+ Storage::for_each_entry(&self.storage, callback);
}
pub fn begin(&self) -> ConstIterator {
ConstIterator {
map: Gc::from_ref(self),
- index: Cell::new(0),
- generation: Cell::new(self.storage.borrow().generation),
- next_insertion_id: Cell::new(0),
- current_insertion_id: Cell::new(None),
+ position: Position::first(&self.storage.borrow()),
}
}
}
-/// An iterator that stays valid while the map is modified, with the visiting rules of the spec's index-based loops:
-/// entries added during iteration are visited, removed entries are skipped, and entries that were moved by a compaction
-/// or cleared are found again by their insertion ID.
+/// An iterator that stays valid while the map is modified, with the visiting rules of Position.
#[derive(Trace)]
pub struct ConstIterator {
map: Gc<Map>,
-
- /// The position of the current entry in the entries. Only meaningful while generation matches the map.
- index: Cell<usize>,
- generation: Cell<u64>,
-
- /// Every entry with a smaller insertion ID has already been visited or skipped.
- next_insertion_id: Cell<u64>,
- current_insertion_id: Cell<Option<u64>>,
+ position: Position,
}
impl ConstIterator {
pub fn is_end(&self) -> bool {
- self.find_current_entry();
- self.index.get() >= self.map.storage.borrow().entries.len()
+ self.position.is_end(&self.map.storage.borrow())
}
- /// operator++. This moves past the entry that is_end() or current() found last, even if that entry has been
- /// removed since, so removing the current entry during iteration does not skip the entry after it.
+ /// operator++.
pub fn advance(&self) {
- if self.current_insertion_id.get().is_none() {
- self.find_current_entry();
- if self.current_insertion_id.get().is_none() {
- return;
- }
- }
- let current_insertion_id = self
- .current_insertion_id
- .take()
- .expect("the current entry was just found");
- self.next_insertion_id.set(current_insertion_id + 1);
- let storage = self.map.storage.borrow();
- let index = self.index.get();
- if self.generation.get() == storage.generation
- && index < storage.entries.len()
- && storage.entries[index].insertion_id < self.next_insertion_id.get()
- {
- self.index.set(index + 1);
- }
+ self.position.advance(&self.map.storage.borrow());
}
/// operator*.
pub fn current(&self) -> Entry {
- self.find_current_entry();
- let storage = self.map.storage.borrow();
- let entry = &storage.entries[self.index.get()];
- Entry {
- key: entry.key,
- value: entry.value,
- }
- }
-
- fn find_current_entry(&self) {
- let storage = self.map.storage.borrow();
- let entries = &storage.entries;
- if self.generation.get() != storage.generation {
- self.index
- .set(storage.index_of_first_entry_not_inserted_before(self.next_insertion_id.get()));
- self.generation.set(storage.generation);
- }
- let mut index = self.index.get();
- while index < entries.len() && entries[index].is_removed() {
- index += 1;
- }
- self.index.set(index);
- if index < entries.len() {
- self.current_insertion_id.set(Some(entries[index].insertion_id));
- } else {
- self.current_insertion_id.set(None);
- }
+ let (key, value) = self.position.current(&self.map.storage.borrow());
+ Entry { key, value }
}
}
diff --git a/Libraries/LibJS/Rust/src/runtime/set.rs b/Libraries/LibJS/Rust/src/runtime/set.rs
index c6761a0b418..526635b3fde 100644
--- a/Libraries/LibJS/Rust/src/runtime/set.rs
+++ b/Libraries/LibJS/Rust/src/runtime/set.rs
@@ -4,11 +4,13 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-use core::cell::Cell;
+use core::ops::Deref;
use libjs_runtime_macros::Trace;
-use crate::gc::class::{GcCell, define_cell};
+use crate::gc::class::{ExternalMemorySize, Finalize, GcCell, define_cell};
+use crate::gc::defer_gc::DeferGc;
+use crate::gc::gc_ref_cell::GcRefCell;
use crate::interpreter::vm::Vm;
use crate::layout::cell::Gc;
use crate::layout::object::Object;
@@ -18,24 +20,49 @@ use crate::runtime::error::ErrorKind;
use crate::runtime::error_types::ErrorType;
use crate::runtime::function_object::FunctionObject;
use crate::runtime::keyed_collections::canonicalize_keyed_collection_key;
-use crate::runtime::map::{self, Map};
-use crate::runtime::object::{MayInterfereWithIndexedPropertyAccess, ORDINARY_OBJECT_METHODS, define_object_class};
+use crate::runtime::map::{NoValue, Position, Storage};
+use crate::runtime::object::MayInterfereWithIndexedPropertyAccess;
use crate::runtime::realm::Realm;
#[repr(C)]
#[derive(Trace)]
pub struct Set {
base: Object,
- values: Cell<Option<Gc<Map>>>,
+ storage: GcRefCell<Storage<NoValue>>,
}
-define_object_class!(Set, extends: [Object], methods: {
- initialize: Set::initialize,
- ..ORDINARY_OBJECT_METHODS
-});
+define_cell!(
+ Set,
+ Object,
+ extends: [Object],
+ finalize: finalize,
+ external_memory_size: external_memory_size
+);
+
+impl ExternalMemorySize for Set {
+ fn external_memory_size(&self) -> usize {
+ self.base
+ .external_memory_size()
+ .saturating_add(self.storage.borrow().external_memory_size())
+ }
+}
+
+impl Deref for Set {
+ type Target = Object;
+
+ fn deref(&self) -> &Object {
+ &self.base
+ }
+}
+
+impl Finalize for Set {
+ fn finalize(&self) {
+ Storage::release(&self.storage);
+ }
+}
impl Set {
- pub fn new(vm: &Vm, realm: Gc<Realm>, prototype: Gc<Object>) -> Set {
+ pub fn new(defer_gc: &DeferGc<'_>, vm: &Vm, realm: Gc<Realm>, prototype: Gc<Object>) -> Set {
Set {
base: Object::new_with_prototype(
vm,
@@ -44,62 +71,55 @@ impl Set {
Some(prototype),
MayInterfereWithIndexedPropertyAccess::No,
),
- values: Cell::new(None),
+ storage: GcRefCell::new(Storage::new(defer_gc)),
}
}
pub fn create(vm: &Vm, realm: Gc<Realm>) -> Gc<Set> {
- realm.create_object(vm, |_| Set::new(vm, realm, realm.intrinsics().set_prototype(vm)))
- }
-
- fn initialize(object: &Object, vm: &Vm, realm: Gc<Realm>) {
- let set = object.as_gc().downcast::<Set>().expect("initializing a Set");
- set.values.set(Some(Map::create(vm, realm)));
- }
-
- fn values(&self) -> Gc<Map> {
- self.values.get().expect("a Set creates its map when it is initialized")
+ realm.create_object(vm, |defer_gc| {
+ Set::new(defer_gc, vm, realm, realm.intrinsics().set_prototype(vm))
+ })
}
- // NOTE: Unlike what the spec says, we implement Sets using an underlying map,
- // so all the functions below do not directly implement the operations as
- // defined by the specification.
+ // NB: Unlike what the spec says, we implement Sets with the storage of a Map that keeps no values, so all the
+ // functions below do not directly implement the operations as defined by the specification.
pub fn set_clear(&self, vm: &Vm) {
- self.values().map_clear(vm);
+ Storage::modify(&self.storage, vm, Storage::clear);
}
pub fn set_remove(&self, vm: &Vm, value: Value) -> bool {
- self.values().map_remove(vm, value)
+ Storage::modify(&self.storage, vm, |storage| storage.remove(value))
}
pub fn set_has(&self, key: Value) -> bool {
- self.values().map_has(key)
+ self.storage.borrow().contains(key)
}
pub fn set_add(&self, vm: &Vm, key: Value) {
- self.values().map_set(vm, key, Value::UNDEFINED);
+ Storage::modify(&self.storage, vm, |storage| storage.set(key, NoValue));
}
pub fn set_size(&self) -> usize {
- self.values().map_size()
+ self.storage.borrow().len()
}
/// Calls the callback with every value, in insertion order. The callback must not modify the set.
pub fn for_each_value(&self, mut callback: impl FnMut(Value)) {
- self.values().for_each_entry(|key, _| callback(key));
+ Storage::for_each_entry(&self.storage, |key, _| callback(key));
}
pub fn begin(&self) -> ConstIterator {
ConstIterator {
- iterator: self.values().begin(),
+ set: Gc::from_ref(self),
+ position: Position::first(&self.storage.borrow()),
}
}
pub fn copy(&self, vm: &Vm) -> Gc<Set> {
let realm = vm.current_realm().expect("a Set is copied in a realm");
- // FIXME: This is very inefficient, but there's no better way to do this at the moment, as the underlying Map
- // implementation of m_values uses a non-copyable RedBlackTree.
+ // FIXME: This is inefficient: it searches the result for every value. Copy the live entries of the storage
+ // instead.
let result = Set::create(vm, realm);
let iterator = self.begin();
while !iterator.is_end() {
@@ -110,25 +130,26 @@ impl Set {
}
}
-/// An iterator that stays valid while the set is modified, with the visiting rules of map::ConstIterator.
+/// An iterator that stays valid while the set is modified, with the visiting rules of Position.
#[derive(Trace)]
pub struct ConstIterator {
- iterator: map::ConstIterator,
+ set: Gc<Set>,
+ position: Position,
}
impl ConstIterator {
pub fn is_end(&self) -> bool {
- self.iterator.is_end()
+ self.position.is_end(&self.set.storage.borrow())
}
/// operator++.
pub fn advance(&self) {
- self.iterator.advance();
+ self.position.advance(&self.set.storage.borrow());
}
/// operator*.
pub fn current(&self) -> Value {
- self.iterator.current().key
+ self.position.current(&self.set.storage.borrow()).0
}
}
diff --git a/Libraries/LibJS/Rust/src/runtime/set_constructor.rs b/Libraries/LibJS/Rust/src/runtime/set_constructor.rs
index a45eb109cac..bf547f47e5f 100644
--- a/Libraries/LibJS/Rust/src/runtime/set_constructor.rs
+++ b/Libraries/LibJS/Rust/src/runtime/set_constructor.rs
@@ -93,10 +93,13 @@ impl SetConstructor {
let iterable = vm.argument(0);
// 2. Let set be ? OrdinaryCreateFromConstructor(NewTarget, "%Set.prototype%", « [[SetData]] »).
- let set =
- ordinary_create_from_constructor_of(vm, realm, new_target, Intrinsics::set_prototype, |_, prototype| {
- Set::new(vm, realm, prototype)
- })?;
+ let set = ordinary_create_from_constructor_of(
+ vm,
+ realm,
+ new_target,
+ Intrinsics::set_prototype,
+ |defer_gc, prototype| Set::new(defer_gc, vm, realm, prototype),
+ )?;
// 3. Set set.[[SetData]] to a new empty List.