Truly independent web browser
LibWeb: Make forking the render state cost next to nothing
Andreas Klinge6f6cb3b8345
diff --git a/Libraries/LibWeb/Rust/src/cow_column.rs b/Libraries/LibWeb/Rust/src/cow_column.rsindex 4fa2cd5060b..b4a74c5af12 100644--- a/Libraries/LibWeb/Rust/src/cow_column.rs+++ b/Libraries/LibWeb/Rust/src/cow_column.rs@@ -505,6 +505,11 @@ impl<T: Clone + Default, const CHUNK: usize> CowVec<T, CHUNK> {self.column.heap_size(sizer, row_heap)}+ /// The bytes of the rows themselves, without what they hold on the heap.+ pub(crate) fn row_bytes(&self) -> usize {+ self.column.len() * size_of::<T>()+ }+/// Every row, in order.pub(crate) fn iter(&self) -> impl Iterator<Item = &T> {(0..self.len).filter_map(|index| self.column.get(index))@@ -533,6 +538,13 @@ impl<T: Clone + Default, const CHUNK: usize> CowVec<T, CHUNK> {self[index] = value;}+ /// Empties the vector, answering its rows in order.+ pub(crate) fn take_rows(&mut self) -> Vec<T> {+ let rows = self.iter().cloned().collect();+ *self = Self::default();+ rows+ }+/// Grows the vector to `len` rows, the new ones default, or truncates it to them.pub(crate) fn resize_with_default(&mut self, len: usize) {if len < self.len {@@ -547,6 +559,16 @@ impl<T: Clone + Default, const CHUNK: usize> CowVec<T, CHUNK> {}}+impl<T: Clone + Default, const CHUNK: usize> FromIterator<T> for CowVec<T, CHUNK> {+ fn from_iter<I: IntoIterator<Item = T>>(rows: I) -> Self {+ let mut vector = Self::default();+ for row in rows {+ vector.push(row);+ }+ vector+ }+}+impl<T: Clone + Default, const CHUNK: usize> std::ops::Index<usize> for CowVec<T, CHUNK> {type Output = T;diff --git a/Libraries/LibWeb/Rust/src/cow_map.rs b/Libraries/LibWeb/Rust/src/cow_map.rsnew file mode 100644index 00000000000..2f36bfa1095--- /dev/null+++ b/Libraries/LibWeb/Rust/src/cow_map.rs@@ -0,0 +1,556 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Maps and sets whose fork shares their storage.+//!+//! A [`CowMap`] keeps its entries in a hash trie behind [`Arc`]s, so cloning it costs one reference count however many+//! entries it holds. A write copies only the nodes on the way to its key that a fork still shares: at most one small node+//! a level, of which a 64-bit hash has 13. Leaves hold a few entries each, so what a node costs is spread over them. Keys+//! hash with a fixed seed, so a map and its forks agree on where a key lives.++use smallvec::SmallVec;+use std::borrow::Borrow;+use std::hash::{BuildHasher, Hash};+use std::sync::Arc;++/// How many bits of a key's hash pick a child at each level of the trie.+const BITS_PER_LEVEL: u32 = 5;+const LEVEL_MASK: u64 = (1 << BITS_PER_LEVEL) - 1;++/// How many entries a leaf holds before it splits, which is also how many a write to it copies.+const ENTRIES_PER_LEAF: usize = 8;++#[derive(Clone)]+enum Node<K, V> {+ Leaf(Vec<(K, V)>),+ /// The children of the slots set in `occupied`, in slot order.+ Branch {+ occupied: u32,+ children: Vec<Arc<Self>>,+ },+}++fn hash_of<Q: Hash + ?Sized>(key: &Q) -> u64 {+ foldhash::fast::FixedState::default().hash_one(key)+}++fn slot_of(hash: u64, shift: u32) -> u32 {+ ((hash >> shift) & LEVEL_MASK) as u32+}++fn position_of(occupied: u32, slot: u32) -> usize {+ (occupied & ((1 << slot) - 1)).count_ones() as usize+}++impl<K: Clone + Eq + Hash, V: Clone> Node<K, V> {+ /// Replaces the leaf `node` with a branch over `entries`, which were the leaf's.+ fn split_into_branch(node: &mut Arc<Self>, entries: Vec<(K, V)>, shift: u32) {+ *node = Arc::new(Self::Branch {+ occupied: 0,+ children: Vec::new(),+ });+ for (key, value) in entries {+ Self::insert(node, hash_of(&key), shift, key, value);+ }+ }++ fn insert(node: &mut Arc<Self>, hash: u64, shift: u32, key: K, value: V) -> Option<V> {+ match Arc::make_mut(node) {+ Self::Leaf(entries) => {+ if let Some((_, existing)) = entries.iter_mut().find(|(existing, _)| *existing == key) {+ return Some(std::mem::replace(existing, value));+ }+ entries.push((key, value));+ // NB: Keys that share what is left of their hash stay together.+ if entries.len() > ENTRIES_PER_LEAF && shift + BITS_PER_LEVEL < u64::BITS {+ let entries = std::mem::take(entries);+ Self::split_into_branch(node, entries, shift);+ }+ None+ }+ Self::Branch { occupied, children } => {+ let slot = slot_of(hash, shift);+ let position = position_of(*occupied, slot);+ if *occupied & (1 << slot) != 0 {+ return Self::insert(&mut children[position], hash, shift + BITS_PER_LEVEL, key, value);+ }+ *occupied |= 1 << slot;+ children.insert(position, Arc::new(Self::Leaf(vec![(key, value)])));+ None+ }+ }+ }++ fn get<'a, Q>(mut node: &'a Self, hash: u64, key: &Q) -> Option<&'a V>+ where+ K: Borrow<Q>,+ Q: Eq + ?Sized,+ {+ let mut shift = 0;+ loop {+ match node {+ Self::Leaf(entries) => {+ return entries+ .iter()+ .find(|(existing, _)| existing.borrow() == key)+ .map(|(_, value)| value);+ }+ Self::Branch { occupied, children } => {+ let slot = slot_of(hash, shift);+ if *occupied & (1 << slot) == 0 {+ return None;+ }+ node = &children[position_of(*occupied, slot)];+ shift += BITS_PER_LEVEL;+ }+ }+ }+ }++ /// The value of `key`, for writing. Nodes on the way to a key the node does not hold are copied as for one it does.+ fn get_mut<'a, Q>(node: &'a mut Arc<Self>, hash: u64, shift: u32, key: &Q) -> Option<&'a mut V>+ where+ K: Borrow<Q>,+ Q: Eq + ?Sized,+ {+ match Arc::make_mut(node) {+ Self::Leaf(entries) => entries+ .iter_mut()+ .find(|(existing, _)| (*existing).borrow() == key)+ .map(|(_, value)| value),+ Self::Branch { occupied, children } => {+ let slot = slot_of(hash, shift);+ if *occupied & (1 << slot) == 0 {+ return None;+ }+ let position = position_of(*occupied, slot);+ Self::get_mut(&mut children[position], hash, shift + BITS_PER_LEVEL, key)+ }+ }+ }++ /// The value of `key`, inserting what `make` answers where the node holds none, and whether it did.+ fn get_or_insert_with(+ node: &mut Arc<Self>,+ hash: u64,+ shift: u32,+ key: K,+ make: impl FnOnce() -> V,+ ) -> (&mut V, bool) {+ let splits = matches!(&**node, Self::Leaf(entries)+ if entries.len() >= ENTRIES_PER_LEAF+ && shift + BITS_PER_LEVEL < u64::BITS+ && !entries.iter().any(|(existing, _)| *existing == key));+ if splits {+ let Self::Leaf(entries) = Arc::make_mut(node) else {+ unreachable!("the node was just found to be a leaf");+ };+ let entries = std::mem::take(entries);+ Self::split_into_branch(node, entries, shift);+ }+ match Arc::make_mut(node) {+ Self::Leaf(entries) => match entries.iter().position(|(existing, _)| *existing == key) {+ Some(index) => (&mut entries[index].1, false),+ None => {+ entries.push((key, make()));+ (&mut entries.last_mut().expect("an entry was just pushed").1, true)+ }+ },+ Self::Branch { occupied, children } => {+ let slot = slot_of(hash, shift);+ let position = position_of(*occupied, slot);+ if *occupied & (1 << slot) == 0 {+ *occupied |= 1 << slot;+ children.insert(position, Arc::new(Self::Leaf(Vec::new())));+ }+ Self::get_or_insert_with(&mut children[position], hash, shift + BITS_PER_LEVEL, key, make)+ }+ }+ }++ /// Removes `key`, which the node must hold, answering its value.+ fn remove<Q>(node: &mut Arc<Self>, hash: u64, shift: u32, key: &Q) -> Option<V>+ where+ K: Borrow<Q>,+ Q: Eq + ?Sized,+ {+ match Arc::make_mut(node) {+ Self::Leaf(entries) => {+ let index = entries.iter().position(|(existing, _)| existing.borrow() == key)?;+ Some(entries.remove(index).1)+ }+ Self::Branch { occupied, children } => {+ let slot = slot_of(hash, shift);+ let position = position_of(*occupied, slot);+ let removed = Self::remove(&mut children[position], hash, shift + BITS_PER_LEVEL, key);+ if children[position].is_empty() {+ children.remove(position);+ *occupied &= !(1 << slot);+ }+ removed+ }+ }+ }++ fn is_empty(&self) -> bool {+ match self {+ Self::Leaf(entries) => entries.is_empty(),+ Self::Branch { children, .. } => children.is_empty(),+ }+ }++ fn heap_size(&self) -> usize {+ crate::heap_size::ARC_HEADER_BYTES+ + size_of::<Self>()+ + match self {+ Self::Leaf(entries) => entries.capacity() * size_of::<(K, V)>(),+ Self::Branch { children, .. } => {+ children.capacity() * size_of::<Arc<Self>>()+ + children.iter().map(|child| child.heap_size()).sum::<usize>()+ }+ }+ }+}++/// A hash map whose clone shares its storage. See the [module documentation](self).+pub(crate) struct CowMap<K, V> {+ root: Option<Arc<Node<K, V>>>,+ len: usize,+}++impl<K, V> Default for CowMap<K, V> {+ fn default() -> Self {+ Self { root: None, len: 0 }+ }+}++impl<K, V> Clone for CowMap<K, V> {+ fn clone(&self) -> Self {+ Self {+ root: self.root.clone(),+ len: self.len,+ }+ }+}++impl<K: Clone + Eq + Hash, V: Clone> CowMap<K, V> {+ pub(crate) fn len(&self) -> usize {+ self.len+ }++ pub(crate) fn is_empty(&self) -> bool {+ self.len == 0+ }++ /// The bytes of the trie, whose entries hold nothing else on the heap.+ pub(crate) fn heap_size(&self) -> usize {+ self.root.as_ref().map_or(0, |root| root.heap_size())+ }++ pub(crate) fn clear(&mut self) {+ *self = Self::default();+ }++ pub(crate) fn get<Q>(&self, key: &Q) -> Option<&V>+ where+ K: Borrow<Q>,+ Q: Eq + Hash + ?Sized,+ {+ Node::get(self.root.as_deref()?, hash_of(key), key)+ }++ pub(crate) fn contains_key<Q>(&self, key: &Q) -> bool+ where+ K: Borrow<Q>,+ Q: Eq + Hash + ?Sized,+ {+ self.get(key).is_some()+ }++ /// The value of `key`, for writing, copying what a fork shares on the way to it.+ pub(crate) fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>+ where+ K: Borrow<Q>,+ Q: Eq + Hash + ?Sized,+ {+ Node::get_mut(self.root.as_mut()?, hash_of(key), 0, key)+ }++ pub(crate) fn insert(&mut self, key: K, value: V) -> Option<V> {+ let hash = hash_of(&key);+ let Some(root) = &mut self.root else {+ self.root = Some(Arc::new(Node::Leaf(vec![(key, value)])));+ self.len = 1;+ return None;+ };+ let previous = Node::insert(root, hash, 0, key, value);+ self.len += usize::from(previous.is_none());+ previous+ }++ pub(crate) fn remove<Q>(&mut self, key: &Q) -> Option<V>+ where+ K: Borrow<Q>,+ Q: Eq + Hash + ?Sized,+ {+ let hash = hash_of(key);+ let root = self.root.as_mut()?;+ Node::get(root.as_ref(), hash, key)?;+ let removed = Node::remove(root, hash, 0, key);+ self.len -= 1;+ if root.is_empty() {+ self.root = None;+ }+ removed+ }++ /// The value of `key`, inserting what `make` answers where the map holds none.+ pub(crate) fn get_or_insert_with(&mut self, key: K, make: impl FnOnce() -> V) -> &mut V {+ let hash = hash_of(&key);+ let root = self.root.get_or_insert_with(|| Arc::new(Node::Leaf(Vec::new())));+ let (value, inserted) = Node::get_or_insert_with(root, hash, 0, key, make);+ self.len += usize::from(inserted);+ value+ }++ pub(crate) fn entry(&mut self, key: K) -> Entry<'_, K, V> {+ Entry { map: self, key }+ }++ /// Every entry, in no particular order.+ pub(crate) fn iter(&self) -> impl Iterator<Item = (&K, &V)> {+ let mut stack: SmallVec<[&Node<K, V>; 16]> = self.root.as_deref().into_iter().collect();+ let mut entries: std::slice::Iter<'_, (K, V)> = [].iter();+ std::iter::from_fn(move || {+ loop {+ if let Some((key, value)) = entries.next() {+ return Some((key, value));+ }+ match stack.pop()? {+ Node::Leaf(leaf) => entries = leaf.iter(),+ Node::Branch { children, .. } => stack.extend(children.iter().map(|child| &**child)),+ }+ }+ })+ }++ pub(crate) fn keys(&self) -> impl Iterator<Item = &K> {+ self.iter().map(|(key, _)| key)+ }++ pub(crate) fn values(&self) -> impl Iterator<Item = &V> {+ self.iter().map(|(_, value)| value)+ }++ /// Keeps the entries `keep` answers true for.+ pub(crate) fn retain(&mut self, mut keep: impl FnMut(&K, &V) -> bool) {+ let gone: Vec<K> = self+ .iter()+ .filter(|(key, value)| !keep(key, value))+ .map(|(key, _)| key.clone())+ .collect();+ for key in &gone {+ self.remove(key);+ }+ }+}++/// A key of a [`CowMap`], and what it holds, for writing.+pub(crate) struct Entry<'a, K, V> {+ map: &'a mut CowMap<K, V>,+ key: K,+}++impl<'a, K: Clone + Eq + Hash, V: Clone> Entry<'a, K, V> {+ pub(crate) fn or_insert_with(self, make: impl FnOnce() -> V) -> &'a mut V {+ self.map.get_or_insert_with(self.key, make)+ }++ pub(crate) fn or_default(self) -> &'a mut V+ where+ V: Default,+ {+ self.or_insert_with(V::default)+ }+}++impl<K: Clone + Eq + Hash, V: Clone> std::ops::Index<&K> for CowMap<K, V> {+ type Output = V;++ fn index(&self, key: &K) -> &V {+ self.get(key).expect("the map holds the key")+ }+}++impl<K: Clone + Eq + Hash, V: Clone> Extend<(K, V)> for CowMap<K, V> {+ fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, entries: I) {+ for (key, value) in entries {+ self.insert(key, value);+ }+ }+}++/// A hash set whose clone shares its storage. See the [module documentation](self).+pub(crate) struct CowSet<T>(CowMap<T, ()>);++impl<T> Default for CowSet<T> {+ fn default() -> Self {+ Self(CowMap::default())+ }+}++impl<T> Clone for CowSet<T> {+ fn clone(&self) -> Self {+ Self(self.0.clone())+ }+}++impl<T: Clone + Eq + Hash> CowSet<T> {+ /// The bytes of the trie, whose values hold nothing else on the heap.+ pub(crate) fn heap_size(&self) -> usize {+ self.0.heap_size()+ }++ pub(crate) fn is_empty(&self) -> bool {+ self.0.is_empty()+ }++ pub(crate) fn clear(&mut self) {+ self.0.clear();+ }++ pub(crate) fn contains<Q>(&self, value: &Q) -> bool+ where+ T: Borrow<Q>,+ Q: Eq + Hash + ?Sized,+ {+ self.0.contains_key(value)+ }++ /// Answers whether the set did not hold `value` yet.+ pub(crate) fn insert(&mut self, value: T) -> bool {+ self.0.insert(value, ()).is_none()+ }++ /// Answers whether the set held `value`.+ pub(crate) fn remove<Q>(&mut self, value: &Q) -> bool+ where+ T: Borrow<Q>,+ Q: Eq + Hash + ?Sized,+ {+ self.0.remove(value).is_some()+ }++ /// Every value, in no particular order.+ pub(crate) fn iter(&self) -> impl Iterator<Item = &T> {+ self.0.keys()+ }+}++const _: () = {+ const fn assert_send_and_sync<T: Send + Sync>() {}+ assert_send_and_sync::<CowMap<u64, u64>>();+ assert_send_and_sync::<CowSet<u64>>();+};++#[cfg(test)]+mod tests {+ use super::*;+ use std::collections::HashMap;++ /// A key whose hash is always the same, so that every entry lands in one leaf.+ #[derive(Clone, PartialEq, Eq)]+ struct Colliding(u32);++ impl Hash for Colliding {+ fn hash<H: std::hash::Hasher>(&self, state: &mut H) {+ 0u32.hash(state);+ }+ }++ #[test]+ fn a_map_acts_as_a_hash_map_through_many_writes() {+ let mut map = CowMap::default();+ let mut expected = HashMap::new();+ let mut state = 1u64;+ for _ in 0..50_000 {+ state = state+ .wrapping_mul(6364136223846793005)+ .wrapping_add(1442695040888963407);+ let key = (state >> 40) % 3000;+ match state >> 62 {+ 0 => assert_eq!(map.remove(&key), expected.remove(&key)),+ 1 => assert_eq!(map.get(&key), expected.get(&key)),+ _ => assert_eq!(map.insert(key, state), expected.insert(key, state)),+ }+ assert_eq!(map.len(), expected.len());+ }+ let mut entries: Vec<_> = map.iter().map(|(&key, &value)| (key, value)).collect();+ let mut expected: Vec<_> = expected.into_iter().collect();+ entries.sort_unstable();+ expected.sort_unstable();+ assert_eq!(entries, expected);+ }++ #[test]+ fn a_fork_shares_the_root_and_neither_side_sees_the_others_writes() {+ let mut map = CowMap::default();+ for key in 0..1000u32 {+ map.insert(key, key);+ }+ let mut fork = map.clone();+ assert!(Arc::ptr_eq(map.root.as_ref().unwrap(), fork.root.as_ref().unwrap()));+ *fork.get_mut(&1).unwrap() = 100;+ fork.remove(&2);+ map.insert(1000, 1000);+ map.remove(&3);+ assert_eq!(+ (map.get(&1), map.get(&2), map.get(&3), map.get(&1000)),+ (Some(&1), Some(&2), None, Some(&1000))+ );+ assert_eq!(+ (fork.get(&1), fork.get(&2), fork.get(&3), fork.get(&1000)),+ (Some(&100), None, Some(&3), None)+ );+ assert_eq!((map.len(), fork.len()), (1000, 999));+ }++ #[test]+ fn keys_of_one_hash_share_a_leaf() {+ let mut map = CowMap::default();+ for key in 0..2 * ENTRIES_PER_LEAF as u32 {+ map.insert(Colliding(key), key);+ }+ assert_eq!(map.get(&Colliding(5)), Some(&5));+ assert_eq!(map.remove(&Colliding(5)), Some(5));+ assert_eq!(map.get(&Colliding(5)), None);+ assert_eq!(map.iter().count(), 2 * ENTRIES_PER_LEAF - 1);+ }++ #[test]+ fn removing_every_entry_empties_the_map() {+ let mut map = CowMap::default();+ for key in 0..100u32 {+ map.insert(key, ());+ }+ for key in 0..100u32 {+ map.remove(&key);+ }+ assert!(map.is_empty());+ assert!(map.root.is_none());+ }++ #[test]+ fn a_set_answers_as_a_hash_set_does() {+ let mut set = CowSet::default();+ assert!(set.insert(1));+ assert!(!set.insert(1));+ assert!(set.contains(&1));+ assert!(set.remove(&1));+ assert!(!set.remove(&1));+ assert!(set.is_empty());+ }+}diff --git a/Libraries/LibWeb/Rust/src/css/style/animations.rs b/Libraries/LibWeb/Rust/src/css/style/animations.rsindex 14cdff143c0..f6442bac7f0 100644--- a/Libraries/LibWeb/Rust/src/css/style/animations.rs+++ b/Libraries/LibWeb/Rust/src/css/style/animations.rs@@ -150,14 +150,14 @@ type CssDefinedAnimationList = (AnimationSlot, Box<[CssDefinedAnimation]>);pub(crate) struct CssDefinedAnimations {/// Owning a CSS animation is rare, so only the elements that do have a row, and a row holds/// only the lists that are not empty.- rows: HashMap<StyleNodeID, Vec<CssDefinedAnimationList>>,+ rows: crate::cow_map::CowMap<StyleNodeID, Vec<CssDefinedAnimationList>>,}impl CssDefinedAnimations {/// The bytes the rows hold on the heap, with each name the first time `sizer` reaches it.pub(crate) fn heap_size(&self, sizer: &mut crate::heap_size::HeapSizer) -> usize {- use crate::heap_size::{map_bytes, vec_bytes};- let mut bytes = map_bytes(&self.rows);+ use crate::heap_size::vec_bytes;+ let mut bytes = self.rows.heap_size();for lists in self.rows.values() {bytes += vec_bytes(lists);for (_, animations) in lists {@@ -312,7 +312,7 @@ pub(crate) type KeyframesRow = HashMap<Box<[u16]>, usize>;/// resolves keyframes.#[derive(Clone, Default)]pub(crate) struct AnimationKeyframes {- scopes: HashMap<TreeScopeID, KeyframesRow>,+ scopes: crate::cow_map::CowMap<TreeScopeID, KeyframesRow>,}impl AnimationKeyframes {diff --git a/Libraries/LibWeb/Rust/src/css/style/column.rs b/Libraries/LibWeb/Rust/src/css/style/column.rsindex e75ab305ad5..f26905530fe 100644--- a/Libraries/LibWeb/Rust/src/css/style/column.rs+++ b/Libraries/LibWeb/Rust/src/css/style/column.rs@@ -90,15 +90,19 @@ impl<T> IntoIterator for Column<T> {/// A directly indexed packed boolean column.#[derive(Clone, Default)]pub(super) struct BitColumn {- words: Vec<u64>,+ words: crate::cow_column::CowVec<u64, 64>,}impl PartialEq for BitColumn {fn eq(&self, other: &Self) -> bool {- let common_length = self.words.len().min(other.words.len());- self.words[..common_length] == other.words[..common_length]- && self.words[common_length..].iter().all(|word| *word == 0)- && other.words[common_length..].iter().all(|word| *word == 0)+ let (longer, shorter) = match self.words.len() >= other.words.len() {+ true => (&self.words, &other.words),+ false => (&other.words, &self.words),+ };+ longer+ .iter()+ .enumerate()+ .all(|(index, word)| shorter.get(index).copied().unwrap_or(0) == *word)}}@@ -106,28 +110,30 @@ impl Eq for BitColumn {}impl BitColumn {pub(super) fn heap_size(&self) -> usize {- crate::heap_size::vec_bytes(&self.words)+ self.words.row_bytes()}/// Set one bit and return whether its value changed and newly allocated bytes.pub(super) fn set(&mut self, index: usize, value: bool) -> (bool, u64) {let word_index = index / u64::BITS as usize;- let capacity_before = self.words.capacity();+ let bytes_before = self.words.row_bytes();if self.words.len() <= word_index {if !value {return (false, 0);}- self.words.resize(word_index + 1, 0);+ self.words.resize_with_default(word_index + 1);}- let growth = ((self.words.capacity() - capacity_before) * size_of::<u64>()) as u64;+ let growth = (self.words.row_bytes() - bytes_before) as u64;let mask = 1_u64 << (index % u64::BITS as usize);- let previous = self.words[word_index] & mask != 0;+ if (self.words[word_index] & mask != 0) == value {+ return (false, growth);+ }if value {self.words[word_index] |= mask;} else {self.words[word_index] &= !mask;}- (previous != value, growth)+ (true, growth)}pub(super) fn contains(&self, index: usize) -> bool {diff --git a/Libraries/LibWeb/Rust/src/css/style/computed.rs b/Libraries/LibWeb/Rust/src/css/style/computed.rsindex 9974b4279b1..9d171f3a65b 100644--- a/Libraries/LibWeb/Rust/src/css/style/computed.rs+++ b/Libraries/LibWeb/Rust/src/css/style/computed.rs@@ -12,7 +12,6 @@//! actual pseudo-element kinds use sparse rows. An element's or pseudo-element's animations compose//! an animation overlay record over the record it is assigned, in a recyclable slot of its own.-use super::fast_hash::FastMap as HashMap;use super::index::StyleAtomID;use super::installed_records::{InstalledRecord, InstalledRecordID, InstalledRecords};use super::tree::StyleNodeID;@@ -527,6 +526,7 @@ impl ReleasedAnimationOverlayRecords {self.records.push(record);}+ #[cfg(test)]fn is_empty(&self) -> bool {self.records.is_empty() && !self.overflowed}@@ -677,7 +677,7 @@ type PseudoComputedRows = smallvec::SmallVec<[PseudoComputedRow; 1]>;/// The slot of the animation overlay composed over each element's record, by element.#[derive(Clone, Default)]-struct AnimationOverlayColumn(Vec<u32>);+struct AnimationOverlayColumn(crate::fork_vec::ForkVec<u32>);impl AnimationOverlayColumn {fn get(&self, index: usize) -> Option<u32> {@@ -686,10 +686,8 @@ impl AnimationOverlayColumn {fn set(&mut self, index: usize, slot: Option<u32>) {if self.0.len() <= index {- self.0.resize(- index.checked_add(1).expect("animation overlay column space exhausted"),- 0,- );+ self.0+ .resize_with_default(index.checked_add(1).expect("animation overlay column space exhausted"));}self.0[index] = slot.map_or(0, |slot| {slot.checked_add(1)@@ -882,7 +880,7 @@ pub struct ComputedGroupSets {installed_pseudo_column:crate::cow_column::CowColumn<Option<std::sync::Arc<InstalledPseudoStyles>>, INSTALLED_STYLE_CHUNK>,/// The elements whose pseudo rows moved since the pseudo column was last published.- pseudo_rows_moved: Vec<StyleNodeID>,+ pseudo_rows_moved: crate::fork::ForkShared<Vec<StyleNodeID>>,/// Long-lived immutable readers pin only the records they actually read. Expired readers leave weak entries/// that the next lease removes, so they neither block reclamation nor need to call back into the owner.hover_frame_leases: std::sync::Arc<std::sync::Mutex<Vec<std::sync::Weak<HoverFrameLease>>>>,@@ -894,18 +892,18 @@ pub struct ComputedGroupSets {// Recyclable animation overlays are deliberately separate from the installed records above.// Dense element assignments and sparse pseudo assignments pin at most one slot each.animation_overlay_column: AnimationOverlayColumn,- animation_overlay_slots: animation_overlay_slots::AnimationOverlaySlots,- animation_overlay_slots_by_record: HashMap<FinalStyleRecordID, u32>,+ animation_overlay_slots: crate::fork::ForkShared<animation_overlay_slots::AnimationOverlaySlots>,+ animation_overlay_slots_by_record: crate::cow_map::CowMap<FinalStyleRecordID, u32>,/// The slots of overlay records nothing assigns or pins but something else holds, such as the host for the element/// it last applied the record to, which go once nothing does.- held_animation_overlay_slots: Vec<u32>,+ held_animation_overlay_slots: crate::fork::ForkShared<Vec<u32>>,released_animation_overlay_records: ReleasedAnimationOverlayRecords,/// How many leases are held, shared with every copy of the sets: a copy holds no lease of its own.// NB: Either copy may be the host's, whose published frames hold their leases here.leases: std::sync::Arc<std::sync::atomic::AtomicUsize>,live_animation_overlay_assignments: usize,next_animation_overlay_generation: u64,- pseudo_rows_by_node: crate::fork::ForkShared<HashMap<StyleNodeID, PseudoComputedRows>>,+ pseudo_rows_by_node: crate::cow_map::CowMap<StyleNodeID, PseudoComputedRows>,/// How many installed records were freed since what they named was last reclaimed.records_freed_since_reclamation: usize,next_reclamation_after: usize,@@ -917,14 +915,14 @@ impl Default for ComputedGroupSets {installed: InstalledRecords::default(),installed_column: Default::default(),installed_pseudo_column: Default::default(),- pseudo_rows_moved: Vec::new(),+ pseudo_rows_moved: Default::default(),hover_frame_leases: std::sync::Arc::default(),released_records_reading_leases: MIN_RECORDS_RELEASED_BEFORE_READING_LEASES,released_records_sweeping: MIN_RECORDS_RELEASED_BEFORE_SWEEPING,animation_overlay_column: AnimationOverlayColumn::default(),- animation_overlay_slots: animation_overlay_slots::AnimationOverlaySlots::default(),- animation_overlay_slots_by_record: HashMap::default(),- held_animation_overlay_slots: Vec::new(),+ animation_overlay_slots: Default::default(),+ animation_overlay_slots_by_record: Default::default(),+ held_animation_overlay_slots: Default::default(),released_animation_overlay_records: ReleasedAnimationOverlayRecords::default(),leases: std::sync::Arc::default(),live_animation_overlay_assignments: 0,@@ -940,24 +938,24 @@ impl ComputedGroupSets {/// Counts the installed records and the columns naming them toward the installed records,/// and the records by owner.pub(super) fn report_memory(&self, report: &mut super::memory_report::MemoryReport) {- use crate::heap_size::{map_bytes, small_vec_bytes, vec_bytes};+ use crate::heap_size::{small_vec_bytes, vec_bytes};self.installed.report_memory(report);for record in self.animation_overlay_slots.records() {super::pipeline::Record::report_memory(record, report);}- let pseudo_rows = &*self.pseudo_rows_by_node;+ let pseudo_rows = &self.pseudo_rows_by_node;report.add(super::memory_report::MemoryOwner::Installed,self.installed_column.len() * size_of::<Option<InstalledStyle>>()+ self.installed_pseudo_column.len() * size_of::<Option<std::sync::Arc<InstalledPseudoStyles>>>()+ vec_bytes(&self.pseudo_rows_moved)- + vec_bytes(&self.animation_overlay_column.0)+ + self.animation_overlay_column.0.row_bytes()+ self.animation_overlay_slots.heap_size()- + map_bytes(&self.animation_overlay_slots_by_record)+ + self.animation_overlay_slots_by_record.heap_size()+ vec_bytes(&self.held_animation_overlay_slots)+ vec_bytes(&self.released_animation_overlay_records.records)- + map_bytes(pseudo_rows)- + pseudo_rows.values().map(small_vec_bytes).sum::<usize>(),+ + pseudo_rows.heap_size()+ + pseudo_rows.iter().map(|(_, rows)| small_vec_bytes(rows)).sum::<usize>(),);}@@ -1016,7 +1014,8 @@ impl ComputedGroupSets {self.animation_overlay_slots.retired_records()}- pub(super) fn has_released_animation_overlay_records(&self) -> bool {+ #[cfg(test)]+ fn has_released_animation_overlay_records(&self) -> bool {!self.released_animation_overlay_records.is_empty()}@@ -1063,19 +1062,16 @@ impl ComputedGroupSets {fn remove_empty_pseudo_row(&mut self, node: StyleNodeID, target: super::pipeline::PseudoElementTarget) {self.pseudo_rows_moved.push(node);- let std::collections::hash_map::Entry::Occupied(mut entry) = self.pseudo_rows_by_node.entry(node) else {+ let Some(rows) = self.pseudo_rows_by_node.get(&node) else {return;};- let Some(row_index) = entry- .get()- .iter()- .position(|row| row.target() == target && row.is_empty())- else {+ let Some(row_index) = rows.iter().position(|row| row.target() == target && row.is_empty()) else {return;};- entry.get_mut().remove(row_index);- if entry.get().is_empty() {- entry.remove();+ let rows = self.pseudo_rows_by_node.get_mut(&node).expect("the node has rows");+ rows.remove(row_index);+ if rows.is_empty() {+ self.pseudo_rows_by_node.remove(&node);}}@@ -1193,7 +1189,7 @@ impl ComputedGroupSets {let mut moved = std::mem::take(&mut self.pseudo_rows_moved);moved.sort_unstable();moved.dedup();- for &node in &moved {+ for &node in moved.iter() {let Some(index) = node.element_index().map(|index| index as usize) else {continue;};@@ -1450,9 +1446,10 @@ impl ComputedGroupSets {let mut slots = std::mem::take(&mut self.held_animation_overlay_slots);slots.sort_unstable();slots.dedup();- for slot in slots {- // NB: A slot a pin took again goes back on the list when its last pin goes.- let Some(record) = self.animation_overlay_slots.get(slot) else {+ for slot in slots.iter().copied() {+ // NB: Taken for writing so that a fork sharing the slots has a copy of its own, which counts as holding the+ // record. A slot a pin took again goes back on the list when its last pin goes.+ let Some(record) = self.animation_overlay_slots.get_mut(slot) else {continue;};if record.is_assigned || record.pin_count != 0 {@@ -1531,6 +1528,12 @@ impl ComputedGroupSets {record_updated: false,};}+ // NB: Taken for writing so that a fork sharing the slots has a copy of its own, which counts as holding the+ // record. Both ways on from here write the slots.+ let current = self+ .animation_overlay_slots+ .get_mut(slot)+ .expect("animation-overlay slot is live");if current.pin_count == 0 && !current.is_held_elsewhere() {let record = self.make_animation_overlay_record(base,diff --git a/Libraries/LibWeb/Rust/src/css/style/effect_descriptions.rs b/Libraries/LibWeb/Rust/src/css/style/effect_descriptions.rsindex 3998016f656..f2fc9817056 100644--- a/Libraries/LibWeb/Rust/src/css/style/effect_descriptions.rs+++ b/Libraries/LibWeb/Rust/src/css/style/effect_descriptions.rs@@ -572,7 +572,7 @@ type AnimationEffectList = (AnimationSlot, Box<[PublishedEffect]>);pub(crate) struct AnimationEffectDescriptions {/// Holding an animation is rare, so only the elements that do have a row, and a row holds only/// the lists that are not empty.- rows: HashMap<StyleNodeID, Vec<AnimationEffectList>>,+ rows: crate::cow_map::CowMap<StyleNodeID, Vec<AnimationEffectList>>,/// The keyframes the effects describe, by content, which an effect describing equal ones shares.keyframes: WeakPool<PublishedKeyframes>,}@@ -596,7 +596,7 @@ impl AnimationEffectDescriptions {});keyframes + interval_values};- let mut bytes = map_bytes(&self.rows);+ let mut bytes = self.rows.heap_size();for lists in self.rows.values() {bytes += vec_bytes(lists);for (_, effects) in lists {@@ -614,18 +614,22 @@ impl AnimationEffectDescriptions {previous: &CustomPropertyRegistry,registry: &CustomPropertyRegistry,) {- for (_, effects) in self.rows.values_mut().flatten() {- for effect in effects {- let Some(interval_values) = &effect.custom_property_interval_values else {- continue;- };- let mut retained_values = interval_values.lock().unwrap().clone();- retained_values.retain(|declaration_indices, _| {- let name = &effect.custom_declaration_at(declaration_indices[0]).name;- registry.registration_matches(previous, &name.to_utf16())- });- // Leave values held by older style snapshots intact.- effect.custom_property_interval_values = Some(Arc::new(Mutex::new(retained_values)));+ let nodes: Vec<StyleNodeID> = self.rows.keys().copied().collect();+ for node in nodes {+ let lists = self.rows.get_mut(&node).expect("the node was just listed");+ for (_, effects) in lists.iter_mut() {+ for effect in effects {+ let Some(interval_values) = &effect.custom_property_interval_values else {+ continue;+ };+ let mut retained_values = interval_values.lock().unwrap().clone();+ retained_values.retain(|declaration_indices, _| {+ let name = &effect.custom_declaration_at(declaration_indices[0]).name;+ registry.registration_matches(previous, &name.to_utf16())+ });+ // Leave values held by older style snapshots intact.+ effect.custom_property_interval_values = Some(Arc::new(Mutex::new(retained_values)));+ }}}}diff --git a/Libraries/LibWeb/Rust/src/css/style/inputs.rs b/Libraries/LibWeb/Rust/src/css/style/inputs.rsindex edd4643d61d..a84ba69903e 100644--- a/Libraries/LibWeb/Rust/src/css/style/inputs.rs+++ b/Libraries/LibWeb/Rust/src/css/style/inputs.rs@@ -1563,7 +1563,7 @@ impl StyleEngine {counters: Counters::new(),highlight_observers: Default::default(),- tree: crate::fork::ForkShared::new(tree),+ tree,deepest_element: Arc::default(),rules: crate::fork::ForkShared::new(RuleStore::new()),process_style: Arc::clone(&process_style),diff --git a/Libraries/LibWeb/Rust/src/css/style/installed_records.rs b/Libraries/LibWeb/Rust/src/css/style/installed_records.rsindex f56732b74c8..c782bf64d2f 100644--- a/Libraries/LibWeb/Rust/src/css/style/installed_records.rs+++ b/Libraries/LibWeb/Rust/src/css/style/installed_records.rs@@ -28,7 +28,7 @@ use std::hash::{Hash, Hasher};use std::sync::Arc;/// The slot of an installed record.-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]pub(crate) struct InstalledRecordSlot(u32);impl InstalledRecordSlot {@@ -97,13 +97,13 @@ impl InstalledRecord {/// The slots of the installed records.#[derive(Clone, Default)]pub(super) struct InstalledRecords {- slots: Vec<Option<InstalledRecord>>,- generations: Vec<u32>,- free: Vec<InstalledRecordSlot>,+ slots: crate::fork_vec::ForkVec<Option<InstalledRecord>>,+ generations: crate::fork_vec::ForkVec<u32>,+ free: crate::fork_vec::ForkVec<InstalledRecordSlot>,/// The slots of the records derived for what no element is, by the key of what they hold.- derived_by_content: hashbrown::HashTable<InstalledRecordSlot>,+ derived_by_content: crate::cow_map::CowMap<u64, InstalledRecordSlot>,/// The records whose last holder let go, which the next sweep frees unless one took them again.- released: Vec<InstalledRecordID>,+ released: crate::fork::ForkShared<Vec<InstalledRecordID>>,/// How many leases on the records held as they are taken were taken.lease_epoch: u32,}@@ -118,13 +118,10 @@ impl InstalledRecords {}report.add(super::memory_report::MemoryOwner::Installed,- vec_bytes(&self.slots)- + vec_bytes(&self.generations)- + vec_bytes(&self.free)- + crate::heap_size::hash_table_bytes(- self.derived_by_content.capacity(),- size_of::<InstalledRecordSlot>(),- )+ self.slots.row_bytes()+ + self.generations.row_bytes()+ + self.free.row_bytes()+ + self.derived_by_content.heap_size()+ vec_bytes(&self.released),);}@@ -189,27 +186,23 @@ impl InstalledRecords {if let Some(id) = self.named_by(record) {return id;}- let content_key = Self::content_key(record);- if let Some(&slot) = self.derived_by_content.find(content_key, |&slot| {- self.slots[slot.index()]+ // NB: The key reads a few longhands, so records that differ in others share it: each takes the next key free. A+ // sweep can open a gap in such a run, which costs a record past it no more than a slot of its own.+ let mut content_key = Self::content_key(record);+ while let Some(&slot) = self.derived_by_content.get(&content_key) {+ if self.slots[slot.index()].as_ref().is_some_and(|entry| entry.record().holds_the_same_as(record))- }) {- return InstalledRecordID {- slot,- generation: self.generations[slot.index()],- };+ {+ return InstalledRecordID {+ slot,+ generation: self.generations[slot.index()],+ };+ }+ content_key = content_key.wrapping_add(1);}let id = self.install(record, dependency_flags);- let slots = &self.slots;- self.derived_by_content.insert_unique(content_key, id.slot, |slot| {- Self::content_key(- slots[slot.index()]- .as_ref()- .expect("an indexed slot holds its record")- .record(),- )- });+ self.derived_by_content.insert(content_key, id.slot);id}@@ -305,9 +298,10 @@ impl InstalledRecords {{return false;}- // NB: A record the host or a reader still holds a reference to keeps its slot, so that+ // NB: A record the host, a reader or a fork sharing the slot still holds a reference to keeps its slot, so that// its identity keeps naming it until the last reference beside the slot's goes.if kept.contains(&id)+ || self.slots.shares_row(index)|| self.slots[index].as_ref().is_some_and(|entry| {Arc::strong_count(entry.record()) > 1|| oldest_lease.is_some_and(|epoch| entry.released_in >= epoch)@@ -328,7 +322,7 @@ impl InstalledRecords {self.released = released;if freed != 0 {let slots = &self.slots;- self.derived_by_content.retain(|slot| slots[slot.index()].is_some());+ self.derived_by_content.retain(|_, slot| slots[slot.index()].is_some());}freed}@@ -354,6 +348,17 @@ mod tests {records.get(id).expect("the slot holds a record").record()}+ #[test]+ fn derived_records_whose_content_shares_a_key_each_keep_a_slot() {+ let mut records = InstalledRecords::default();+ let first = records.install_derived(&record(1), || 0);+ let second = records.install_derived(&record(2), || 0);++ assert_ne!(first, second);+ assert_eq!(records.install_derived(&record(1), || 0), first);+ assert_eq!(records.install_derived(&record(2), || 0), second);+ }+#[test]fn a_record_a_fork_named_first_takes_a_copy_in_a_slot_here() {let mut original = InstalledRecords::default();diff --git a/Libraries/LibWeb/Rust/src/css/style/memory_report.rs b/Libraries/LibWeb/Rust/src/css/style/memory_report.rsindex 537f62d9d09..5a1fc3cc77b 100644--- a/Libraries/LibWeb/Rust/src/css/style/memory_report.rs+++ b/Libraries/LibWeb/Rust/src/css/style/memory_report.rs@@ -150,8 +150,8 @@ impl super::StyleEngine {report.add(MemoryOwner::CustomProperties, bytes);report.add(MemoryOwner::CustomProperties,- map_bytes(&state.element_custom_property_data)- + map_bytes(&state.pseudo_element_custom_property_data)+ state.element_custom_property_data.heap_size()+ + state.pseudo_element_custom_property_data.heap_size()+ state.pseudo_element_custom_property_data.values()@@ -167,7 +167,7 @@ impl super::StyleEngine {report.add(MemoryOwner::HeldRecordMaps,held_style_records- + map_bytes(&state.held_pseudo_style_records)+ + state.held_pseudo_style_records.heap_size()+ state.held_pseudo_style_records.values()@@ -184,12 +184,12 @@ impl super::StyleEngine {report.add(MemoryOwner::AnimationEffects, bytes);report.add(MemoryOwner::OtherMaps,- set_bytes(&state.keyframes_reading_parent_reset_values)+ state.keyframes_reading_parent_reset_values.heap_size()+ map_bytes(&state.layout_style_snapshots)- + map_bytes(&state.counter_style_environment_identities)- + map_bytes(&state.backing_elements)- + map_bytes(&state.replaced_content_inputs)- + map_bytes(&state.demand_records)+ + state.counter_style_environment_identities.heap_size()+ + state.backing_elements.heap_size()+ + state.replaced_content_inputs.heap_size()+ + state.demand_records.heap_size()+ state.transition_baselines.heap_size()+ state.scope_roots.heap_size()+ state.scope_by_root.heap_size()diff --git a/Libraries/LibWeb/Rust/src/css/style/mod.rs b/Libraries/LibWeb/Rust/src/css/style/mod.rsindex f864ba05fad..9bdb446930d 100644--- a/Libraries/LibWeb/Rust/src/css/style/mod.rs+++ b/Libraries/LibWeb/Rust/src/css/style/mod.rs@@ -133,7 +133,7 @@ pub(crate) type SelectorAttributeNames = Arc<HashSet<StyleAtomID>>;/// The style record each pseudo-element of an element holds.type HeldPseudoStyleRecords =- crate::fork::ForkShared<HashMap<StyleNodeID, smallvec::SmallVec<[(pipeline::PseudoElementTarget, u64); 1]>>>;+ crate::cow_map::CowMap<StyleNodeID, smallvec::SmallVec<[(pipeline::PseudoElementTarget, u64); 1]>>;/// What an element's arrival has to carry to reach the anchor of a `:has()` argument: a name whose raw identity is/// among `names` as its tag, ID, class or attribute name, or a state among `states`. Where an argument can be reached@@ -210,7 +210,7 @@ pub struct RetainedState {counters: Counters,/// The elements the host shows each kind of highlight in.highlight_observers: pipeline::highlight_observers::HighlightObservers,- tree: crate::fork::ForkShared<HostTree>,+ tree: HostTree,/// The depth of the deepest element the tree ever held, which the document's host reads.deepest_element: Arc<std::sync::atomic::AtomicU32>,/// Where the hover is.@@ -245,22 +245,22 @@ pub struct RetainedState {/// The shared computed-group payload tuple last published for each live element. This is the/// computed half of the eventual base style record; custom properties and metadata remain/// separate inputs until that record is complete.- computed_group_sets: crate::fork::ForkShared<ComputedGroupSets>,+ computed_group_sets: ComputedGroupSets,/// How many epochs of style record views the host has open. No computed record is reclaimed while one is.style_record_view_epoch_depth: u32,/// The stores behind the custom-property environments live records are published with.custom_property_environments: crate::fork::ForkShared<custom_property_environments::CustomPropertyEnvironments>,/// The custom-property environment each element holds, for the elements that hold one. This is/// the only copy: the element reads its environment from here.- element_custom_property_data: crate::fork::ForkShared<HashMap<StyleNodeID, inputs::HeldCustomPropertyEnvironment>>,+ element_custom_property_data: crate::cow_map::CowMap<StyleNodeID, inputs::HeldCustomPropertyEnvironment>,/// The custom-property environments of each element's synthetic pseudo-elements, by/// pseudo-element kind, for the elements with a pseudo-element that holds one.pseudo_element_custom_property_data:- crate::fork::ForkShared<HashMap<StyleNodeID, Vec<(u8, inputs::HeldCustomPropertyEnvironment)>>>,+ crate::cow_map::CowMap<StyleNodeID, Vec<(u8, inputs::HeldCustomPropertyEnvironment)>>,/// The elements whose animations' keyframes say `inherit` for a property that does not/// inherit, as the host last sampled them: they read their parent's values of properties that/// do not inherit, whether or not their records do.- keyframes_reading_parent_reset_values: crate::fork::ForkShared<HashSet<StyleNodeID>>,+ keyframes_reading_parent_reset_values: crate::cow_map::CowSet<StyleNodeID>,/// What the container conditions of the rows the engine answered read of their containers,/// per element, taken when the host installs the element's record.container_effects_for_host: container_queries::ContainerEffectsForHost,@@ -273,7 +273,7 @@ pub struct RetainedState {/// The counter-style registry each tree scope's style scope has, as one identity per scope:/// what a record whose `list-style-type` names a counter style the registry may define names,/// so that an edit to `@counter-style` moves it.- counter_style_environment_identities: crate::fork::ForkShared<HashMap<TreeScopeID, u64>>,+ counter_style_environment_identities: crate::cow_map::CowMap<TreeScopeID, u64>,/// The style record each element holds, for the elements that hold one, as the host reports/// every record it installs or clears./// Copied on write in chunks of its own, which a fork shares.@@ -287,7 +287,7 @@ pub struct RetainedState {/// Per shadow host, the elements of its shadow tree that stood for one of its element-backed/// pseudo-elements when the host published them; [`RetainedState::backing_elements`] reads the/// ones that still do.- backing_elements: crate::fork::ForkShared<HashMap<StyleNodeID, SmallVec<[StyleNodeID; 2]>>>,+ backing_elements: crate::cow_map::CowMap<StyleNodeID, SmallVec<[StyleNodeID; 2]>>,/// The names of the CSS animations the host holds for each element, which the computation of/// its animation definitions matches them against.css_defined_animations: crate::fork::ForkShared<animations::CssDefinedAnimations>,@@ -307,7 +307,7 @@ pub struct RetainedState {random_base_values: random_bases::RandomBaseValues,/// What each element that has replaced content gives its natural size, which layout resolves/// against the style of the element's box.- replaced_content_inputs: crate::fork::ForkShared<HashMap<StyleNodeID, inputs::ReplacedContentInput>>,+ replaced_content_inputs: crate::cow_map::CowMap<StyleNodeID, inputs::ReplacedContentInput>,/// The before-change style each transition target's transitions are decided against for the/// rest of the style stabilization epoch, pinned until the epoch commits.transition_baselines: transition_baselines::TransitionBaselines,@@ -317,7 +317,7 @@ pub struct RetainedState {custom_property_registrations_changed: bool,/// The record a private demand last answered for each target it was asked about, pinned for/// the host to read: no node holds it.- demand_records: crate::fork::ForkShared<HashMap<computed::ComputedStyleTarget, computed::FinalStyleRecordID>>,+ demand_records: crate::cow_map::CowMap<computed::ComputedStyleTarget, computed::FinalStyleRecordID>,/// The places of the children of parents with many of them, which sibling-counting functions/// read, kept while the tree's DOM order stands.@@ -344,7 +344,7 @@ pub struct RetainedState {/// The longhand properties each element declares itself, by the kind of declaration they came/// from. An element-attached declaration beats every rule in its context, so the cascade needs/// to know which properties one covers just as it does for a rule.- element_declarations: crate::fork::ForkShared<element_declarations::ElementDeclarationStore>,+ element_declarations: element_declarations::ElementDeclarationStore,/// The document as the engine reads it: every element fact and link the host publishes.projection: pipeline::projection::Projection,/// The attribute names whose value text a selector reads, which the host holds a copy of between jobs.diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/fork_tests.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/fork_tests.rsindex e7efa5dfc8b..b7b87a9262a 100644--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/fork_tests.rs+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/fork_tests.rs@@ -6,8 +6,7 @@//! What a fork of a styled document's engine allocates. The render clock and the hover lane fork//! the engine whenever the host moves on under them, so a fork is made per frame while the host is-//! busy: it should copy chunk pointers and reference counts, not tables, and so allocate no more-//! for a document twice as large.+//! busy: it copies reference counts, not tables, and so allocates no more for a larger document.use super::super::*;use super::allocation_count::count_live_bytes;@@ -17,7 +16,7 @@ use crate::css::computed_values::{BoxValues, StyleGroups};use crate::css::table_group_builder::group_index;/// How many elements the smaller of the two documents a test forks holds.-const ELEMENTS: usize = 256;+const ELEMENTS: usize = 32;/// Builds a document element with `count - 1` children, owned by the engine, as a document's/// host leaves it after its first frame: one query container late in tree order, every eighth@@ -116,24 +115,16 @@ fn fork_bytes(engine: &StyleEngine) -> i64 {bytes}-/// What a fork of the smaller document allocates, and how much more per element a fork of one-/// twice as large does, at most.-const FORK_BYTES: i64 = 5_150;-const FORK_BYTES_PER_ELEMENT: f64 = 1.5;+/// What a fork of a document allocates, whatever the document holds.+const FORK_BYTES: i64 = 5_480;#[test]-fn forking_a_styled_document_allocates_at_most_as_today() {+fn forking_a_styled_document_allocates_the_same_however_large_it_is() {let small = fork_bytes(&styled_document(ELEMENTS));- let large = fork_bytes(&styled_document(2 * ELEMENTS));- let per_element = (large - small) as f64 / ELEMENTS as f64;- // FIXME: A fork copies chunk pointers and reference counts, not tables: drive both bounds to- // what the chunks written since the fork hold.+ let large = fork_bytes(&styled_document(4 * ELEMENTS));assert!(small <= FORK_BYTES,"a fork of {ELEMENTS} elements allocates {small} bytes");- assert!(- per_element <= FORK_BYTES_PER_ELEMENT,- "a fork allocates {per_element:.1} bytes per element"- );+ assert_eq!(small, large, "a fork allocates more for a larger document");}diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/projection.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/projection.rsindex a3d1db65c03..5c1d3c7d41f 100644--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/projection.rs+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/projection.rs@@ -95,7 +95,7 @@ fn clear_transaction_list<T>(list: &mut Vec<T>) {#[derive(Clone, Default)]struct WrittenRows {nodes: Vec<StyleNodeID>,- bits: Vec<u64>,+ bits: crate::cow_column::CowVec<u64, 64>,}impl WrittenRows {@@ -103,7 +103,7 @@ impl WrittenRows {fn insert(&mut self, node: StyleNodeID, slot: usize) -> bool {let (word, bit) = (slot / 64, 1_u64 << (slot % 64));if word >= self.bits.len() {- self.bits.resize(word + 1, 0);+ self.bits.resize_with_default(word + 1);}if self.bits[word] & bit != 0 {return false;@@ -767,9 +767,9 @@ pub(in crate::css::style) struct Projection {/// The distinct sets of host facts the rows name, as the host last published them.host_fact_sets: Arc<HostFactSets>,/// A slotted text node's slot. Text nodes have no rows, and a slotted one is rare.- text_assigned_slots: Arc<HashMap<StyleNodeID, StyleNodeID>>,+ text_assigned_slots: crate::cow_map::CowMap<StyleNodeID, StyleNodeID>,/// The elements whose facts say they are disabled, as the host last published them.- disabled: Arc<HashSet<StyleNodeID>>,+ disabled: crate::cow_map::CowSet<StyleNodeID>,/// The elements whose rows the host's publications wrote since the last barrier.written: WrittenRows,/// Each write since the last barrier, which whether a written row changes the committed@@ -861,7 +861,7 @@ impl Row {impl WrittenRows {fn heap_size(&self) -> usize {- crate::heap_size::vec_bytes(&self.nodes) + crate::heap_size::vec_bytes(&self.bits)+ crate::heap_size::vec_bytes(&self.nodes) + self.bits.row_bytes()}}@@ -869,7 +869,6 @@ impl Projection {/// Counts the rows of every generation the projection holds, each chunk once, and its/// catalogs and change sets, with the live elements it holds.pub(in crate::css::style) fn report_memory(&self, report: &mut crate::css::style::memory_report::MemoryReport) {- use crate::heap_size::map_bytes;let owner = crate::css::style::memory_report::MemoryOwner::Projection;let sizer = &mut report.sizer;let mut bytes = self.rows.heap_size(sizer, Row::heap_size)@@ -900,8 +899,8 @@ impl Projection {bytes += texts.heap_size(sizer);bytes += texts.values().map(|text| size_of_val::<[u16]>(text)).sum::<usize>();}- bytes += sizer.arc_shallow(&self.text_assigned_slots) + map_bytes(&self.text_assigned_slots);- bytes += sizer.arc_shallow(&self.disabled) + crate::heap_size::set_bytes(&self.disabled);+ bytes += self.text_assigned_slots.heap_size();+ bytes += self.disabled.heap_size();if let Some(watched_keys) = &self.watched_keys {bytes += sizer.arc_shallow(watched_keys) + crate::heap_size::set_bytes(&watched_keys.keys);}@@ -1374,7 +1373,7 @@ impl Projection {/// The elements whose facts as written say they are disabled.#[must_use]- pub(in crate::css::style) fn written_disabled(&self) -> &HashSet<StyleNodeID> {+ pub(in crate::css::style) fn written_disabled(&self) -> &crate::cow_map::CowSet<StyleNodeID> {&self.disabled}diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/projection/writer.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/projection/writer.rsindex 27cbf2cfc3b..6f6016b60af 100644--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/projection/writer.rs+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/projection/writer.rs@@ -13,8 +13,6 @@//! An element that left the tree is retired and forgotten here as its departure is published: the generations//! published before keep its facts, which is where the render owner reads what a departed element carried.-use super::super::super::fast_hash::FastMap as HashMap;-use super::super::super::fast_hash::FastSet as HashSet;use super::super::super::index::AttributeFact;use super::super::super::index::AttributeNameForms;use super::super::super::index::StyleAtomID;@@ -84,9 +82,9 @@ pub(in crate::css::style) struct ProjectionWriter {host_fact_sets: Arc<HostFactSets>,recent_lists: RecentFactLists,/// A slotted text node's slot. Text nodes have no rows, and a slotted one is rare.- text_assigned_slots: Arc<HashMap<StyleNodeID, StyleNodeID>>,+ text_assigned_slots: crate::cow_map::CowMap<StyleNodeID, StyleNodeID>,/// The elements whose facts say they are disabled, which only the writes of their states and their departures move.- disabled: Arc<HashSet<StyleNodeID>>,+ disabled: crate::cow_map::CowSet<StyleNodeID>,/// The elements whose rows were written since the last publication.written: WrittenRows,/// Of those, the elements whose links were written.@@ -113,8 +111,8 @@ pub(in crate::css::style) struct ProjectionPublication {pub(super) slot_count: usize,pub(super) catalogs: Catalogs,pub(super) host_fact_sets: Arc<HostFactSets>,- pub(super) text_assigned_slots: Arc<HashMap<StyleNodeID, StyleNodeID>>,- pub(super) disabled: Arc<HashSet<StyleNodeID>>,+ pub(super) text_assigned_slots: crate::cow_map::CowMap<StyleNodeID, StyleNodeID>,+ pub(super) disabled: crate::cow_map::CowSet<StyleNodeID>,pub(super) written: Vec<StyleNodeID>,pub(super) links_written: Vec<StyleNodeID>,pub(super) relations_written: Vec<StyleNodeID>,@@ -142,7 +140,6 @@ impl ProjectionWriter {/// counted where they are seen first, and the lists of what it wrote. Like the generations a/// transaction in flight holds, how much that is depends on when the report runs.pub(in crate::css::style) fn report_memory(&self, report: &mut crate::css::style::memory_report::MemoryReport) {- use crate::heap_size::map_bytes;let sizer = &mut report.sizer;let mut bytes = self.rows.heap_size(sizer, Row::heap_size)+ self.shadows.heap_size(sizer, |shadow, sizer| {@@ -160,8 +157,8 @@ impl ProjectionWriter {bytes += texts.heap_size(sizer);bytes += texts.values().map(|text| size_of_val::<[u16]>(text)).sum::<usize>();}- bytes += sizer.arc_shallow(&self.text_assigned_slots) + map_bytes(&self.text_assigned_slots);- bytes += sizer.arc_shallow(&self.disabled) + crate::heap_size::set_bytes(&self.disabled);+ bytes += self.text_assigned_slots.heap_size();+ bytes += self.disabled.heap_size();bytes += [&self.written, &self.links_written, &self.relations_written].iter().map(|rows| rows.heap_size())@@ -222,8 +219,8 @@ impl ProjectionWriter {slot_count: self.slot_count,catalogs: self.catalogs.clone(),host_fact_sets: Arc::clone(&self.host_fact_sets),- text_assigned_slots: Arc::clone(&self.text_assigned_slots),- disabled: Arc::clone(&self.disabled),+ text_assigned_slots: self.text_assigned_slots.clone(),+ disabled: self.disabled.clone(),written: self.written.take(),links_written: self.links_written.take(),relations_written: self.relations_written.take(),@@ -257,7 +254,7 @@ impl ProjectionWriter {if self.disabled.contains(&node) == disabled {return;}- let elements = Arc::make_mut(&mut self.disabled);+ let elements = &mut self.disabled;if disabled {elements.insert(node);} else {@@ -460,7 +457,7 @@ impl ProjectionWriter {for &assigned in shadow.assigned_nodes.as_slice() {if assigned.text_index().is_some() {if self.text_assigned_slots.get(&assigned) == Some(&node) {- Arc::make_mut(&mut self.text_assigned_slots).remove(&assigned);+ self.text_assigned_slots.remove(&assigned);}} else if self.row(assigned).and_then(|row| row.facts.lists.assigned_slot()) == Some(node) {self.edit_lists_quietly(assigned, |lists| std::mem::take(&mut lists.assigned_slot).is_some());@@ -477,7 +474,7 @@ impl ProjectionWriter {/// Retire text identities, dropping them from the slot each was assigned to.pub(in crate::css::style) fn retire_texts(&mut self, nodes: impl IntoIterator<Item = StyleNodeID>) {for node in nodes {- let Some(slot) = Arc::make_mut(&mut self.text_assigned_slots).remove(&node) else {+ let Some(slot) = self.text_assigned_slots.remove(&node) else {continue;};self.remove_assigned_node(slot, node);@@ -906,7 +903,7 @@ impl ProjectionWriter {return;}let previous: Vec<_> = self.assigned_nodes_of(slot).to_vec();- let text_slots = Arc::make_mut(&mut self.text_assigned_slots);+ let text_slots = &mut self.text_assigned_slots;// A tree-wide assignment can have moved a departing text node to another slot already,// and this slot must not take that newer assignment away again.for node in &previous {diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/records.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/records.rsindex 6377e4e7bd2..325c7bae0e6 100644--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/records.rs+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/records.rs@@ -1390,12 +1390,12 @@ fn empty_retained_page(length: usize) -> Arc<[RetainedSlot]> {/// for the others.////// A fork of the render state takes the records in pages it shares with the state it forked until-/// either side writes one: forking costs a reference count per page, and the first write to a-/// page after a fork copies the page alone.+/// either side writes one: forking costs one reference count, and the first write to a page after+/// a fork copies the page alone.#[derive(Clone, Default)]pub(super) struct RetainedRecords {/// Each page holds `RETAINED_PAGE_SIZE` slots but for the first, until the page after it exists.- pages: Vec<Arc<[RetainedSlot]>>,+ pages: crate::cow_column::CowVec<Arc<[RetainedSlot]>, 64>,/// The root font inputs the last pass that styled the document element resolved/// root-relative lengths against, with that element. A record reads the metrics of its first/// available font through its cascade, which a load filling one of its faces in moves, so what@@ -1407,8 +1407,8 @@ pub(super) struct RetainedRecords {impl RetainedRecords {/// Counts the pages and what their slots hold, by owner.pub(super) fn report_memory(&self, report: &mut MemoryReport) {- report.add(MemoryOwner::RetainedSlots, crate::heap_size::vec_bytes(&self.pages));- for page in &self.pages {+ report.add(MemoryOwner::RetainedSlots, self.pages.row_bytes());+ for page in self.pages.iter() {if !report.sizer.first_sight(page.as_ptr()) {continue;}@@ -1468,12 +1468,12 @@ impl RetainedRecords {let first_page_length = slot_count.next_power_of_two().clamp(RETAINED_FIRST_PAGE_MIN_SIZE, RETAINED_PAGE_SIZE);- match self.pages.first_mut() {+ match self.pages.get(0) {Some(first) if first.len() < first_page_length => {let mut slots = Vec::with_capacity(first_page_length);slots.extend_from_slice(first);slots.resize_with(first_page_length, RetainedSlot::default);- *first = slots.into();+ self.pages[0] = slots.into();}None if slot_count != 0 => self.pages.push(empty_retained_page(first_page_length)),_ => {}@@ -1611,15 +1611,18 @@ impl RetainedRecords {// are kept until the end, so that no other list takes the place of one of them.let mut renumbered: HashMap<*const u32, Option<MatchList>> = HashMap::default();let mut originals: Vec<MatchList> = Vec::new();- for page in &mut self.pages {+ for page_index in 0..self.pages.len() {// NB: A page holding no matches is left to the fork it may be shared with.- if !page+ if !self.pages[page_index].iter().any(|slot| slot.held.as_ref().is_some_and(|held| held.matches.is_some())){continue;}- for held in Arc::make_mut(page).iter_mut().filter_map(|slot| slot.held.as_mut()) {+ for held in Arc::make_mut(&mut self.pages[page_index])+ .iter_mut()+ .filter_map(|slot| slot.held.as_mut())+ {let Some(matches) = held.matches.take() else {continue;};diff --git a/Libraries/LibWeb/Rust/src/css/style/position_try.rs b/Libraries/LibWeb/Rust/src/css/style/position_try.rsindex 71266eb9951..6833980201b 100644--- a/Libraries/LibWeb/Rust/src/css/style/position_try.rs+++ b/Libraries/LibWeb/Rust/src/css/style/position_try.rs@@ -54,7 +54,7 @@ impl PositionTryRuleID {/// The `@position-try` rules every style scope of the document defines, as each scope's rule cache resolved them.#[derive(Clone, Default)]pub(crate) struct PositionTryRules {- scopes: HashMap<TreeScopeID, PositionTryRow>,+ scopes: crate::cow_map::CowMap<TreeScopeID, PositionTryRow>,last_id: u64,}diff --git a/Libraries/LibWeb/Rust/src/css/style/publication.rs b/Libraries/LibWeb/Rust/src/css/style/publication.rsindex 113625b271b..ebe91d3afea 100644--- a/Libraries/LibWeb/Rust/src/css/style/publication.rs+++ b/Libraries/LibWeb/Rust/src/css/style/publication.rs@@ -605,10 +605,6 @@ impl RetainedState {}pub(crate) fn take_released_animation_overlay_records(&mut self) -> computed::ReleasedAnimationOverlayRecords {- // Even an empty take copies the sets while a fork shares them.- if !self.computed_group_sets.has_released_animation_overlay_records() {- return computed::ReleasedAnimationOverlayRecords::default();- }self.computed_group_sets.take_released_animation_overlay_records()}diff --git a/Libraries/LibWeb/Rust/src/css/style/random_bases.rs b/Libraries/LibWeb/Rust/src/css/style/random_bases.rsindex f75fa1c0cb4..1be9183347b 100644--- a/Libraries/LibWeb/Rust/src/css/style/random_bases.rs+++ b/Libraries/LibWeb/Rust/src/css/style/random_bases.rs@@ -8,7 +8,6 @@//! The random base value each random caching key of the document has been given.use super::RetainedState;-use super::fast_hash::FastMap as HashMap;use super::tree::StyleNodeID;use std::hash::BuildHasher;use std::sync::atomic::{AtomicBool, Ordering};@@ -20,10 +19,10 @@ use std::sync::{Arc, Mutex};#[derive(Clone, Default)]pub(crate) struct RandomBaseValues {/// The keys whose element is null, by name, shared with a fork until either side writes it.- document: crate::fork::ForkShared<HashMap<Box<[u16]>, f64>>,+ document: crate::cow_map::CowMap<Box<[u16]>, f64>,/// The keys that name an element. Few elements draw, and those draw few names, so only they/// have a row and a row is searched in order. Shared with a fork until either side writes it.- elements: crate::fork::ForkShared<HashMap<StyleNodeID, Vec<NamedBaseValue>>>,+ elements: crate::cow_map::CowMap<StyleNodeID, Vec<NamedBaseValue>>,/// Raised once any element has a row, and never lowered. The host watches it so that an element losing its/// identity asks for keys only once some element can have any.element_rows_exist: Arc<AtomicBool>,diff --git a/Libraries/LibWeb/Rust/src/css/style/transition_baselines.rs b/Libraries/LibWeb/Rust/src/css/style/transition_baselines.rsindex ce12a5347fe..4fccd552584 100644--- a/Libraries/LibWeb/Rust/src/css/style/transition_baselines.rs+++ b/Libraries/LibWeb/Rust/src/css/style/transition_baselines.rs@@ -9,7 +9,7 @@use super::boundary::StyleChange;use super::pipeline::Record;use super::tree::StyleNodeID;-use super::{HashMap, RetainedState, ViewLonghands};+use super::{RetainedState, ViewLonghands};use crate::css::animated_overlay::FfiAnimatedOverlayEntry;use crate::css::style_value::StyleValueData;use smallvec::SmallVec;@@ -24,7 +24,7 @@ use std::sync::Arc;#[derive(Clone, Default)]pub(crate) struct TransitionBaselines {/// Shared with a fork until either side writes it.- baselines: crate::fork::ForkShared<HashMap<StyleNodeID, SmallVec<[TargetBaseline; 1]>>>,+ baselines: crate::cow_map::CowMap<StyleNodeID, SmallVec<[TargetBaseline; 1]>>,}/// The baseline of a transition target, by its pseudo-element kind.@@ -33,8 +33,8 @@ type TargetBaseline = (u8, Arc<Record>);impl TransitionBaselines {/// The bytes the baselines hold on the heap.pub(crate) fn heap_size(&self) -> usize {- use crate::heap_size::{map_bytes, small_vec_bytes};- map_bytes(&self.baselines) + self.baselines.values().map(small_vec_bytes).sum::<usize>()+ use crate::heap_size::small_vec_bytes;+ self.baselines.heap_size() + self.baselines.values().map(small_vec_bytes).sum::<usize>()}/// Keeps `record` as the target's baseline where it has none.diff --git a/Libraries/LibWeb/Rust/src/css/style/tree.rs b/Libraries/LibWeb/Rust/src/css/style/tree.rsindex fdffb64eafd..d95363c4f00 100644--- a/Libraries/LibWeb/Rust/src/css/style/tree.rs+++ b/Libraries/LibWeb/Rust/src/css/style/tree.rs@@ -20,7 +20,6 @@//! with the live tree at every epoch boundary, maintained from the same tree delta that reports the//! mutation.-use super::fast_hash::FastMap as HashMap;use super::fast_hash::FastSet as HashSet;use smallvec::SmallVec;use std::num::NonZeroU32;@@ -243,10 +242,10 @@ impl<T: Copy> SegmentedNodeColumn<T> {#[derive(Clone, Default)]struct ElementIdIndex {/// The name each element answers to, which is the key a change or a retirement removes under.- name_of_node: HashMap<StyleNodeID, StyleAtomID>,+ name_of_node: crate::cow_map::CowMap<StyleNodeID, StyleAtomID>,/// The elements answering to a name, in the order they took it rather than in tree order./// Nearly every name is unique, so the list that holds one stays inline.- nodes_by_name: HashMap<StyleAtomID, SmallVec<[StyleNodeID; 1]>>,+ nodes_by_name: crate::cow_map::CowMap<StyleAtomID, SmallVec<[StyleNodeID; 1]>>,/// What the spilled candidate lists hold, carried rather than summed: every element that takes/// an id writes here, and walking one list per name would make a page of ids quadratic.candidate_bytes: usize,@@ -325,7 +324,7 @@ pub struct HostTree {connected_element_count: u32,/// Identities retired in the current epoch. They cannot be reused until the epoch that could/// still observe them has retired.- pending_reuse: Vec<u32>,+ pending_reuse: crate::cow_column::CowVec<u32, 1024>,/// The identities a test mints from, standing in for the host's.#[cfg(test)]test_identities: super::identities::StyleNodeIdAllocator,@@ -339,15 +338,15 @@ pub struct HostTree {/// editable or an editing host, inside a blocking wheel event handler, or a navigable container/// holding a navigable. Nearly every node holds none of them, which is the absence of an entry./// Element, text and document identities publish here, as each gets a row.- dom_paint_facts: HashMap<StyleNodeID, u8>,+ dom_paint_facts: crate::cow_map::CowMap<StyleNodeID, u8>,/// The spans a table cell's or table column's attributes give it: the effective column and row/// span, and the column span attribute's unclamped value, which only the table formatting/// context's column handling reads. Every other element spans one of each, which is what the/// absence of an entry means.- table_spans: HashMap<StyleNodeID, TableSpans>,+ table_spans: crate::cow_map::CowMap<StyleNodeID, TableSpans>,/// The document's top layer, in the order its members were added. The order is the order their/// boxes are built in and belongs to the document, so no per-element fact can carry it.- top_layer: Vec<StyleNodeID>,+ top_layer: crate::fork::ForkShared<Vec<StyleNodeID>>,/// Counts the changes to the DOM child sequences, to the parents and shadow roots that place a/// node among its siblings, and to which nodes are live. See [`Self::dom_order_version`].@@ -420,26 +419,26 @@ impl HostTree {/// The bytes of the tree's columns and indexes.pub(super) fn heap_size(&self, sizer: &mut crate::heap_size::HeapSizer) -> usize {- use crate::heap_size::{map_bytes, vec_bytes};+ use crate::heap_size::vec_bytes;let ids = self.ids.as_ref().map_or(0, |ids| {size_of::<ElementIdIndex>()- + map_bytes(&ids.name_of_node)- + map_bytes(&ids.nodes_by_name)+ + ids.name_of_node.heap_size()+ + ids.nodes_by_name.heap_size()+ ids.candidate_bytes});let text = &self.text;let text_bytes = text.links.heap_size(sizer, |_, _| 0)+ text.flags.heap_size(sizer, |_, _| 0)+ text.data.heap_size(sizer, |_, _| 0)- + vec_bytes(&text.pending_reuse);+ + text.pending_reuse.row_bytes();self.elements.heap_size(sizer, |_, _| 0)+ self.live.heap_size()+ self.relation_only.heap_size()- + vec_bytes(&self.pending_reuse)+ + self.pending_reuse.row_bytes()+ ids+ text_bytes- + map_bytes(&self.dom_paint_facts)- + map_bytes(&self.table_spans)+ + self.dom_paint_facts.heap_size()+ + self.table_spans.heap_size()+ vec_bytes(&self.top_layer)}@@ -462,14 +461,14 @@ impl HostTree {live: BitColumn::default(),relation_only: BitColumn::default(),connected_element_count: 0,- pending_reuse: Vec::new(),+ pending_reuse: Default::default(),#[cfg(test)]test_identities: Default::default(),ids: None,text: TextRows::default(),- dom_paint_facts: HashMap::default(),- table_spans: HashMap::default(),- top_layer: Vec::new(),+ dom_paint_facts: Default::default(),+ table_spans: Default::default(),+ top_layer: Default::default(),dom_order_version: 0,dom_paint_facts_version: 0,#[cfg(test)]@@ -617,12 +616,14 @@ impl HostTree {pub fn release_retired_identities(&mut self) -> Vec<u32> {let released: Vec<u32> = self.pending_reuse- .drain(..)+ .take_rows()+ .into_iter().map(|index| StyleNodeID::element(index).raw()).chain(self.text.pending_reuse- .drain(..)+ .take_rows()+ .into_iter().map(|index| StyleNodeID::text(index).raw()),).collect();@@ -824,7 +825,7 @@ impl HostTree {/// Replace the document's top layer.pub fn set_top_layer(&mut self, members: &[StyleNodeID]) {- members.clone_into(&mut self.top_layer);+ self.top_layer.assign(members.to_vec());}/// The characters the text node holds, or none for any other identity.@@ -1144,7 +1145,7 @@ struct TextRows {/// layout tree build reads them to render a text box, so they are published where the node/// arrives and wherever its data is replaced. Copied on write in chunks, as the flags are.data: CowColumn<ak::Utf16String, TEXT_DATA_PER_CHUNK>,- pending_reuse: Vec<u32>,+ pending_reuse: crate::cow_column::CowVec<u32, 1024>,}/// How many text nodes a chunk of [`TextRows`]'s links holds.diff --git a/Libraries/LibWeb/Rust/src/fork.rs b/Libraries/LibWeb/Rust/src/fork.rsindex 523c7cc41fd..d8863509fba 100644--- a/Libraries/LibWeb/Rust/src/fork.rs+++ b/Libraries/LibWeb/Rust/src/fork.rs@@ -67,6 +67,11 @@ impl<T: Clone> ForkShared<T> {Self(std::sync::Arc::new(value))}+ /// The part, for writing, where no fork shares it.+ pub(crate) fn unshared_mut(&mut self) -> Option<&mut T> {+ std::sync::Arc::get_mut(&mut self.0)+ }+/// Replaces the part, in place where no fork shares it.pub(crate) fn assign(&mut self, value: T) {match std::sync::Arc::get_mut(&mut self.0) {diff --git a/Libraries/LibWeb/Rust/src/fork_vec.rs b/Libraries/LibWeb/Rust/src/fork_vec.rsnew file mode 100644index 00000000000..b2c61d08a99--- /dev/null+++ b/Libraries/LibWeb/Rust/src/fork_vec.rs@@ -0,0 +1,466 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! A vector whose fork costs a few reference counts, and which costs what a [`Vec`] does while no fork is alive.+//!+//! The vector keeps its rows flat. A fork shares them, and the vector it was made from goes on writing them in place,+//! saving a row's old value in a log the first time it writes the row. So a fork reads a row from what it wrote itself,+//! then from the logs from its own on, and then from the rows themselves, and sees the vector as it was when forked.+//! A log goes with the last fork that reads it, and the rows it saved with it, and writes then only pay to find that no+//! log is there.+//!+//! The render state and its forks live in the render owner's slot, which one thread holds at a time, and the threads of a+//! pass only read. That is what lets a fork read the rows without a lock. See [`crate::render_state`]. A fork may be+//! dropped once its thread no longer holds the slot, so the vector takes a reference to a log for as long as it writes it.++use crate::css::style::fast_hash::FastMap;+use std::cell::UnsafeCell;+use std::sync::{Arc, OnceLock, Weak};++/// What a vector saved of its rows while a fork made from it, or the log after it, was alive.+struct Log<T> {+ rows_at_fork: usize,+ /// In a box of its own, so that a reference a fork holds stays good as the log grows.+ saved: UnsafeCell<FastMap<usize, Box<T>>>,+ /// The log of the next fork, which saved what this log leaves out from when that fork was made.+ next: UnsafeCell<Option<Arc<Log<T>>>>,+}++struct ForkSide<T> {+ log: Arc<Log<T>>,+ own: FastMap<usize, T>,+ len: usize,+ /// What a row past those the fork was made with reads as until the fork writes it: growing a fork takes no rows.+ default_row: OnceLock<T>,+}++pub(crate) struct ForkVec<T> {+ /// The rows of the vector, which a fork reads none of here: its `len` is 0, so it leaves the fast path.+ rows: *mut T,+ len: usize,+ storage: Arc<UnsafeCell<Vec<T>>>,+ /// The log of the newest fork, which only the forks keep alive.+ log: UnsafeCell<Option<Weak<Log<T>>>>,+ fork: Option<Box<ForkSide<T>>>,+}++// SAFETY: A vector and its forks are reached only by the thread that holds the render owner's slot, and by the threads of+// a pass, which only read them, while it waits, but for a fork dropped past the hold, which only lets go of its `Arc`s.+// See the module documentation.+unsafe impl<T: Send + Sync> Send for ForkVec<T> {}+// SAFETY: As above.+unsafe impl<T: Send + Sync> Sync for ForkVec<T> {}++impl<T> Default for ForkVec<T> {+ fn default() -> Self {+ Self {+ rows: std::ptr::null_mut(),+ len: 0,+ storage: Arc::default(),+ log: UnsafeCell::new(None),+ fork: None,+ }+ }+}++impl<T: Clone + Default> ForkVec<T> {+ fn storage_mut(&mut self) -> &mut Vec<T> {+ // SAFETY: `&mut self` and holding the slot rule out any other reference into the rows.+ unsafe { &mut *self.storage.get() }+ }++ fn note_storage_moved(&mut self) {+ let rows = self.storage_mut();+ let (pointer, len) = (rows.as_mut_ptr(), rows.len());+ self.rows = pointer;+ self.len = len;+ }++ #[inline]+ pub(crate) fn len(&self) -> usize {+ match &self.fork {+ None => self.len,+ Some(fork) => fork.len,+ }+ }++ #[inline]+ pub(crate) fn get(&self, index: usize) -> Option<&T> {+ if index < self.len {+ // SAFETY: `rows` and `len` follow the storage, which `&self` keeps from moving.+ return Some(unsafe { &*self.rows.add(index) });+ }+ self.get_on_fork(index)+ }++ #[cold]+ fn get_on_fork(&self, index: usize) -> Option<&T> {+ let fork = self.fork.as_deref()?;+ if index >= fork.len {+ return None;+ }+ if let Some(row) = fork.own.get(&index) {+ return Some(row);+ }+ if index >= fork.log.rows_at_fork {+ return Some(fork.default_row.get_or_init(T::default));+ }+ let mut log = &fork.log;+ loop {+ // SAFETY: Only the vector writes the log, and not while this reference lives: see the module documentation.+ if let Some(row) = unsafe { &*log.saved.get() }.get(&index) {+ return Some(row);+ }+ // SAFETY: As above.+ match unsafe { &*log.next.get() } {+ Some(next) => log = next,+ // SAFETY: A row no log holds is as it was when the fork was made, and as above.+ None => return unsafe { &*self.storage.get() }.get(index),+ }+ }+ }++ #[inline]+ pub(crate) fn get_mut(&mut self, index: usize) -> Option<&mut T> {+ if index < self.len {+ self.save_row(index);+ // SAFETY: `rows` and `len` follow the storage, and `&mut self` rules out any other reference into it.+ return Some(unsafe { &mut *self.rows.add(index) });+ }+ self.get_mut_on_fork(index)+ }++ /// Whether another side reads the row at `index` as this one does: a fork of the vector, or the vector this is a+ /// fork of, where neither wrote the row since the fork.+ pub(crate) fn shares_row(&mut self, index: usize) -> bool {+ if let Some(fork) = &self.fork {+ return index < fork.log.rows_at_fork+ && !fork.own.contains_key(&index)+ && Arc::strong_count(&self.storage) > 1;+ }+ let Some(log) = self.live_log() else {+ return false;+ };+ if index >= log.rows_at_fork {+ return false;+ }+ // SAFETY: Only the vector writes the log, and `&mut self` rules out any other reference into it.+ !unsafe { &*log.saved.get() }.contains_key(&index)+ }++ /// The log of the newest fork, forgetting it once no fork reads it.+ fn live_log(&mut self) -> Option<Arc<Log<T>>> {+ let log = self.log.get_mut().as_ref().and_then(Weak::upgrade);+ if log.is_none() {+ *self.log.get_mut() = None;+ }+ log+ }++ #[inline]+ fn save_row(&mut self, index: usize) {+ if self.log.get_mut().is_some() {+ self.save_row_in_log(index);+ }+ }++ #[cold]+ fn save_row_in_log(&mut self, index: usize) {+ // NB: The last fork reading the log may go on another thread at any moment, so this holds it.+ let Some(log) = self.live_log() else {+ return;+ };+ if index >= log.rows_at_fork {+ return;+ }+ // SAFETY: Only the vector writes the log, and `&mut self` rules out any other reference into it.+ let saved = unsafe { &mut *log.saved.get() };+ // SAFETY: `index` is a row of the storage, which the caller checked.+ saved+ .entry(index)+ .or_insert_with(|| Box::new(unsafe { (*self.rows.add(index)).clone() }));+ }++ #[cold]+ fn get_mut_on_fork(&mut self, index: usize) -> Option<&mut T> {+ let fork = self.fork.as_deref()?;+ if index >= fork.len {+ return None;+ }+ if !fork.own.contains_key(&index) {+ let row = self.get_on_fork(index).cloned().unwrap_or_default();+ self.fork.as_deref_mut()?.own.insert(index, row);+ }+ self.fork.as_deref_mut()?.own.get_mut(&index)+ }++ pub(crate) fn push(&mut self, value: T) {+ if let Some(fork) = self.fork.as_deref_mut() {+ fork.own.insert(fork.len, value);+ fork.len += 1;+ return;+ }+ self.storage_mut().push(value);+ self.note_storage_moved();+ }++ pub(crate) fn pop(&mut self) -> Option<T> {+ if let Some(fork) = self.fork.as_deref() {+ let index = fork.len.checked_sub(1)?;+ let row = self.get_on_fork(index).cloned();+ let fork = self.fork.as_deref_mut()?;+ fork.own.remove(&index);+ fork.len = index;+ return row;+ }+ let index = self.len.checked_sub(1)?;+ self.save_row(index);+ let row = self.storage_mut().pop();+ self.note_storage_moved();+ row+ }++ /// Grows the vector to `len` rows, the new ones default, or truncates it to them.+ pub(crate) fn resize_with_default(&mut self, len: usize) {+ while self.len() > len {+ self.pop();+ }+ if let Some(fork) = self.fork.as_deref_mut() {+ // NB: A row the fork was made with reads as what it holds there, so it takes a default of its own.+ while fork.len < len.min(fork.log.rows_at_fork) {+ fork.own.insert(fork.len, T::default());+ fork.len += 1;+ }+ fork.len = fork.len.max(len);+ return;+ }+ self.storage_mut().resize_with(len, T::default);+ self.note_storage_moved();+ }++ /// Empties the vector, answering its rows in order.+ pub(crate) fn take_rows(&mut self) -> Vec<T> {+ if self.fork.is_some() || self.live_log().is_some() {+ let rows = self.iter().cloned().collect();+ // NB: What a fork reads stays as it was, in the rows this vector leaves behind.+ *self = Self::default();+ return rows;+ }+ let rows = std::mem::take(self.storage_mut());+ self.note_storage_moved();+ rows+ }++ /// The bytes of the rows themselves, without what they hold on the heap.+ pub(crate) fn row_bytes(&self) -> usize {+ // SAFETY: Holding the slot rules out a write to the storage.+ unsafe { &*self.storage.get() }.capacity() * size_of::<T>()+ }++ /// Every row, in order.+ pub(crate) fn iter(&self) -> impl Iterator<Item = &T> {+ (0..self.len()).filter_map(|index| self.get(index))+ }+}++/// A fork of the vector, which shares its rows. A fork of a fork takes rows of its own.+impl<T: Clone + Default> Clone for ForkVec<T> {+ fn clone(&self) -> Self {+ if self.fork.is_some() {+ return self.iter().cloned().collect();+ }+ let log = Arc::new(Log {+ rows_at_fork: self.len,+ saved: UnsafeCell::default(),+ next: UnsafeCell::new(None),+ });+ // SAFETY: The thread that holds the slot makes the fork, so nothing else reaches the log. See the module+ // documentation.+ let current = unsafe { &mut *self.log.get() };+ let previous = current.replace(Arc::downgrade(&log));+ if let Some(previous) = previous.as_ref().and_then(Weak::upgrade) {+ // SAFETY: As above.+ unsafe { *previous.next.get() = Some(Arc::clone(&log)) };+ }+ Self {+ rows: std::ptr::null_mut(),+ len: 0,+ storage: Arc::clone(&self.storage),+ log: UnsafeCell::new(None),+ fork: Some(Box::new(ForkSide {+ log,+ own: FastMap::default(),+ len: self.len,+ default_row: OnceLock::new(),+ })),+ }+ }+}++impl<T: Clone + Default> FromIterator<T> for ForkVec<T> {+ fn from_iter<I: IntoIterator<Item = T>>(rows: I) -> Self {+ let mut vector = Self::default();+ *vector.storage_mut() = rows.into_iter().collect();+ vector.note_storage_moved();+ vector+ }+}++impl<T: Clone + Default> std::ops::Index<usize> for ForkVec<T> {+ type Output = T;++ #[inline]+ fn index(&self, index: usize) -> &T {+ self.get(index).expect("index within the vector")+ }+}++impl<T: Clone + Default> std::ops::IndexMut<usize> for ForkVec<T> {+ #[inline]+ fn index_mut(&mut self, index: usize) -> &mut T {+ self.get_mut(index).expect("index within the vector")+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn rows(vector: &ForkVec<u32>) -> Vec<u32> {+ vector.iter().copied().collect()+ }++ #[test]+ fn a_fork_sees_the_vector_as_it_was_when_forked() {+ let mut vector: ForkVec<u32> = [1, 2, 3].into_iter().collect();+ let fork = vector.clone();+ vector[0] = 10;+ vector.push(4);+ vector.pop();+ vector.pop();+ vector.push(30);+ assert_eq!(rows(&vector), [10, 2, 30]);+ assert_eq!(rows(&fork), [1, 2, 3]);+ }++ #[test]+ fn a_fork_writes_its_own_rows() {+ let mut vector: ForkVec<u32> = [1, 2, 3].into_iter().collect();+ let mut fork = vector.clone();+ fork[1] = 20;+ fork.push(4);+ vector[2] = 30;+ assert_eq!(rows(&fork), [1, 20, 3, 4]);+ assert_eq!(rows(&vector), [1, 2, 30]);+ assert_eq!(fork.pop(), Some(4));+ fork.resize_with_default(5);+ assert_eq!(rows(&fork), [1, 20, 3, 0, 0]);+ }++ #[test]+ fn a_fork_grows_past_its_rows_without_taking_any() {+ let mut vector: ForkVec<u32> = [1, 2, 3].into_iter().collect();+ let mut fork = vector.clone();+ vector.push(4);+ fork.resize_with_default(1_000_000);+ assert!(fork.fork.as_ref().unwrap().own.is_empty());+ assert_eq!(fork.len(), 1_000_000);+ assert_eq!((fork[2], fork[3], fork[999_999]), (3, 0, 0));+ assert!(!fork.shares_row(3));+ fork[500] = 5;+ assert_eq!(fork[500], 5);+ fork.resize_with_default(2);+ assert_eq!(rows(&fork), [1, 2]);+ fork.resize_with_default(600);+ assert_eq!((fork[2], fork[500]), (0, 0));+ }++ #[test]+ fn a_fork_copies_a_row_the_first_time_it_writes_it() {+ use std::sync::atomic::{AtomicUsize, Ordering};++ #[derive(Default)]+ struct Counted(Arc<AtomicUsize>);++ impl Clone for Counted {+ fn clone(&self) -> Self {+ self.0.fetch_add(1, Ordering::Relaxed);+ Self(Arc::clone(&self.0))+ }+ }++ let copies = Arc::new(AtomicUsize::new(0));+ let vector: ForkVec<Counted> = [Counted(Arc::clone(&copies))].into_iter().collect();+ let mut fork = vector.clone();+ fork.get_mut(0);+ fork.get_mut(0);+ assert_eq!(copies.load(Ordering::Relaxed), 1);+ }++ #[test]+ fn an_earlier_fork_reads_through_the_logs_of_later_ones() {+ let mut vector: ForkVec<u32> = [1, 2].into_iter().collect();+ let first = vector.clone();+ vector[0] = 10;+ let second = vector.clone();+ vector[0] = 100;+ vector[1] = 200;+ assert_eq!(rows(&first), [1, 2]);+ assert_eq!(rows(&second), [10, 2]);+ drop(second);+ vector[1] = 2000;+ assert_eq!(rows(&first), [1, 2]);+ }++ #[test]+ fn the_vector_stops_logging_once_its_forks_are_gone() {+ let mut vector: ForkVec<u32> = [1].into_iter().collect();+ drop(vector.clone());+ vector[0] = 2;+ assert!(vector.log.get_mut().is_none());+ }++ #[test]+ fn the_rows_a_log_saved_go_with_its_last_fork() {+ let row = Arc::new(1);+ let mut vector: ForkVec<Arc<u32>> = [Arc::clone(&row)].into_iter().collect();+ let fork = vector.clone();+ vector[0] = Arc::default();+ assert_eq!(Arc::strong_count(&row), 2);+ drop(fork);+ assert_eq!(Arc::strong_count(&row), 1);+ }++ #[test]+ fn a_fork_shares_a_row_until_the_vector_writes_it() {+ let mut vector: ForkVec<u32> = (0..4).collect();+ assert!(!vector.shares_row(1));+ let fork = vector.clone();+ assert!(vector.shares_row(1));+ let mut other = vector.clone();+ assert!(other.shares_row(1));+ other[1] = 8;+ assert!(!other.shares_row(1));+ drop(other);+ vector[1] = 9;+ assert!(!vector.shares_row(1));+ assert!(vector.shares_row(2));+ vector.push(4);+ assert!(!vector.shares_row(4));+ drop(fork);+ assert!(!vector.shares_row(2));+ }++ #[test]+ fn taking_the_rows_leaves_a_fork_its_rows() {+ let mut vector: ForkVec<u32> = [1, 2].into_iter().collect();+ let fork = vector.clone();+ assert_eq!(vector.take_rows(), [1, 2]);+ vector.push(3);+ assert_eq!(rows(&fork), [1, 2]);+ assert_eq!(rows(&vector), [3]);+ }+}diff --git a/Libraries/LibWeb/Rust/src/layout/counters.rs b/Libraries/LibWeb/Rust/src/layout/counters.rsindex e51d6ac56eb..941d3ecb039 100644--- a/Libraries/LibWeb/Rust/src/layout/counters.rs+++ b/Libraries/LibWeb/Rust/src/layout/counters.rs@@ -14,7 +14,6 @@ use super::node_data::{use crate::css::computed_value_views::ComputedValuesView;use crate::css::css_string::CssString;use crate::css::style::RetainedState;-use crate::css::style::fast_hash::FastMap as HashMap;use crate::css::style::tree::StyleNodeID;use crate::painting::paint_read::PaintRead;use std::sync::Arc;@@ -111,7 +110,7 @@ type CountersSet = Arc<Vec<Counter>>;/// Every non-empty counters set, keyed by its owner. An empty set is simply absent.#[derive(Clone, Default)]pub(crate) struct CountersSets {- sets: HashMap<CounterOwner, CountersSet>,+ sets: crate::cow_map::CowMap<CounterOwner, CountersSet>,list_item_counter_name: Option<CssString>,}diff --git a/Libraries/LibWeb/Rust/src/layout/fc_run_cache.rs b/Libraries/LibWeb/Rust/src/layout/fc_run_cache.rsindex 7e4331ea117..93fa1df95a4 100644--- a/Libraries/LibWeb/Rust/src/layout/fc_run_cache.rs+++ b/Libraries/LibWeb/Rust/src/layout/fc_run_cache.rs@@ -540,7 +540,7 @@ pub(crate) struct FcRunCacheStore {/// Written in place, while a fork of the arena reads them as they were when it was made.slots: super::pass_column::ForkSharedRows<FcRunCacheSlot>,/// Noted between passes, and only read during one.- inline_layout_damage: Vec<InlineLayoutDamage>,+ inline_layout_damage: crate::fork_vec::ForkVec<InlineLayoutDamage>,queued_for_sweep: super::pass_column::PassFlags,}@@ -634,7 +634,7 @@ impl FcRunCacheStore {}let damage = &mut self.inline_layout_damage;if damage.len() <= box_.slot_index() as usize {- damage.resize(box_.slot_index() as usize + 1, InlineLayoutDamage::default());+ damage.resize_with_default(box_.slot_index() as usize + 1);}let entry = &mut damage[box_.slot_index() as usize];if entry.generation != box_.generation() {diff --git a/Libraries/LibWeb/Rust/src/layout/generated_content.rs b/Libraries/LibWeb/Rust/src/layout/generated_content.rsindex dc4d5a54f9e..59f56ff2541 100644--- a/Libraries/LibWeb/Rust/src/layout/generated_content.rs+++ b/Libraries/LibWeb/Rust/src/layout/generated_content.rs@@ -17,7 +17,6 @@ use crate::css::counter_representation::{};use crate::css::css_enums::keyword;use crate::css::css_string::CssString;-use crate::css::style::fast_hash::FastMap as HashMap;use crate::css::style::tree::StyleNodeID;use crate::css::style_value::{COUNTER_FUNCTION_COUNTER, StyleValueData};use crate::css::style_value::{ContentPayload, CounterPayload};@@ -36,12 +35,12 @@ enum MarkerContent<'a> {#[derive(Clone, Default)]pub(crate) struct GeneratedContent {/// The text each pseudo-element's content resolved to, the way accessibility reads it.- accessible_texts: HashMap<CounterOwner, Vec<u16>>,+ accessible_texts: crate::cow_map::CowMap<CounterOwner, Vec<u16>>,/// The counter styles the box built for a pseudo-element was rendered from, one per/// `counter()` or `counters()` the content names and one for the counter style a normal/// marker shows. A later style change compares what the pseudo-element's record names now/// against this to decide whether the box has to be rebuilt.- content_counter_styles_in_use: HashMap<CounterOwner, Vec<Option<Arc<CounterStyle>>>>,+ content_counter_styles_in_use: crate::cow_map::CowMap<CounterOwner, Vec<Option<Arc<CounterStyle>>>>,}impl GeneratedContent {diff --git a/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rs b/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rsindex a54886721cc..9275be672eb 100644--- a/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rs+++ b/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rs@@ -12,6 +12,7 @@ use super::tree_builder::FfiLayoutTreeBuildOutcome;use super::tree_shape::{Chunk, PUBLISHED_ROWS_PER_CHUNK, ShapeWriter, ShapeWrites, TreeShape};use super::update_layout::FfiLayoutTreeBuildStats;use crate::cow_column::{ColumnSnapshot, CowColumn, CowVec};+use crate::cow_map::{CowMap, CowSet};use crate::css::css_pixels::{CssPixelPoint, FfiCssPixelPoint};use crate::css::style::bridge::ElementBoxKind;use crate::css::style::bridge::{REBUILD_LEVEL, RELAYOUT_LEVEL};@@ -22,6 +23,7 @@ use crate::css::style::{engine_sample::NeedsHost,layout_style::{AnonymousStyleKind, AnonymousStyleOverrides, DerivedStyleRecord, LayoutStyle},};+use crate::fork_vec::ForkVec;use crate::layout::ComputedValuesView;use crate::layout::CssPixels;use crate::layout::node_data::{@@ -361,11 +363,11 @@ impl Default for TextNodeSlot {/// one, so forking the arena does not copy every text row's state.#[derive(Clone, Default)]struct TextSlots {- slots: Vec<TextNodeSlot>,+ slots: ForkVec<TextNodeSlot>,states: CowVec<TextNodeState, TEXT_STATES_PER_CHUNK>,/// The places in `states` no slot uses.- vacant_states: Vec<u32>,- released_states: Vec<u32>,+ vacant_states: ForkVec<u32>,+ released_states: ForkVec<u32>,published: CowColumn<PublishedTextSlot, SLOTS_PER_CHUNK>,}@@ -385,7 +387,7 @@ impl TextSlots {fn state_mut(&mut self, id: NodeSlotId) -> TextStateMut<'_> {let index = id.slot_index() as usize;if self.slots.len() <= index {- self.slots.resize_with(index + 1, TextNodeSlot::default);+ self.slots.resize_with_default(index + 1);}if self.slots[index].generation != id.generation() {self.release_state(index);@@ -773,7 +775,7 @@ const BOUND_ROWS_PER_CHUNK: usize = 64;pub(crate) struct BoundRows {elements: CowColumn<NodeSlotId, BOUND_ROWS_PER_CHUNK>,texts: CowColumn<NodeSlotId, BOUND_ROWS_PER_CHUNK>,- pseudo_elements: Arc<HashMap<StyleNodeID, PseudoElementRows>>,+ pseudo_elements: CowMap<StyleNodeID, PseudoElementRows>,viewport: NodeSlotId,/// Advanced by every write to the pseudo-element or viewport rows.writes: u64,@@ -783,7 +785,7 @@ pub(crate) struct BoundRows {pub(crate) struct PublishedBoundRows {elements: ColumnSnapshot<NodeSlotId, BOUND_ROWS_PER_CHUNK>,texts: ColumnSnapshot<NodeSlotId, BOUND_ROWS_PER_CHUNK>,- pseudo_elements: Arc<HashMap<StyleNodeID, PseudoElementRows>>,+ pseudo_elements: CowMap<StyleNodeID, PseudoElementRows>,viewport: NodeSlotId,}@@ -840,17 +842,17 @@ impl BoundRows {let previous = self.pseudo_element_row(generator, generated_for);if previous != row {self.writes += 1;- let rows = Arc::make_mut(&mut self.pseudo_elements);- let element_rows = rows+ let element_rows = self+ .pseudo_elements.entry(generator)- .or_insert(PseudoElementRows([NodeSlotId::INVALID; _]));+ .or_insert_with(|| PseudoElementRows([NodeSlotId::INVALID; _]));let slot = element_rows.0.get_mut(usize::from(generated_for)).expect("only an element's synthetic pseudo-elements are bound to rows");*slot = row;if element_rows.0.iter().all(|row| row.is_invalid()) {- rows.remove(&generator);+ self.pseudo_elements.remove(&generator);}}previous@@ -900,8 +902,8 @@ impl PublishedBoundRows {/// and text identities each cost one entry per node of their own kind.#[derive(Clone, Default)]struct RowsByStyleNode {- elements: Vec<NodeSlotId>,- texts: Vec<NodeSlotId>,+ elements: ForkVec<NodeSlotId>,+ texts: ForkVec<NodeSlotId>,}impl RowsByStyleNode {@@ -919,7 +921,7 @@ impl RowsByStyleNode {None => (&mut self.elements, style_node.element_slot()),};if rows.len() <= index {- rows.resize(index + 1, NodeSlotId::INVALID);+ rows.resize_with_default(index + 1);}&mut rows[index]}@@ -961,26 +963,26 @@ struct StyleNodeTables {/// The maps are borrowed for writing only by the publication entry points, which can run while a/// tree build is under way: an element styled on the build's behalf replaces its style record,/// which republishes the resources its style names. No reader holds a borrow across a host call.- svg_attribute_facts: HashMap<StyleNodeID, super::svg_formatting_context::FfiSvgAttributeFacts>,+ svg_attribute_facts: CowMap<StyleNodeID, super::svg_formatting_context::FfiSvgAttributeFacts>,/// The parsed MathML attributes each MathML element published, keyed by its style node.- math_attribute_facts: HashMap<StyleNodeID, super::math_formatting_context::FfiMathAttributeFacts>,+ math_attribute_facts: CowMap<StyleNodeID, super::math_formatting_context::FfiMathAttributeFacts>,/// The `points` list each <polyline> and <polygon> published beside its facts.- svg_points: HashMap<StyleNodeID, std::sync::Arc<[super::svg_formatting_context::FfiFloatPoint]>>,+ svg_points: CowMap<StyleNodeID, std::sync::Arc<[super::svg_formatting_context::FfiFloatPoint]>>,/// The elements carrying each anchor name, in tree order. The DOM's registry republishes a/// name's list whenever it changes.- anchor_name_elements: HashMap<ScopedAnchorName, Vec<StyleNodeID>>,+ anchor_name_elements: CowMap<ScopedAnchorName, Vec<StyleNodeID>>,/// The nodes sitting in the user agent shadow tree of the focused text control, which is what/// a caret is painted inside. At most one control is focused, so this holds one control's/// shadow tree and is empty the rest of the time.- identities_in_focused_text_control: HashSet<StyleNodeID>,+ identities_in_focused_text_control: CowSet<StyleNodeID>,/// What each element has scrolled to, held against its identity because the element's box is/// replaced whenever its subtree is rebuilt. The element still stores the offset it answers/// `scrollTop` with, and publishes it here as it changes, arrives and changes identity. Zero is/// the absence of an entry, which is nearly every element.- element_scroll_offsets: HashMap<StyleNodeID, CssPixelPoint>,+ element_scroll_offsets: CowMap<StyleNodeID, CssPixelPoint>,/// What each element's pseudo-elements have scrolled to, held against the element's identity,/// since a pseudo-element has none of its own, and published the way the element's offset is.- pseudo_element_scroll_offsets: HashMap<StyleNodeID, PseudoElementScrollOffsets>,+ pseudo_element_scroll_offsets: CowMap<StyleNodeID, PseudoElementScrollOffsets>,/// The writing suggestion showing after the caret, if any: at most one per document, held/// against the identity of the text node the caret is in.writing_suggestion: Option<PublishedWritingSuggestion>,@@ -1017,8 +1019,9 @@ struct ScopedAnchorName {}/// Why the arena holds a pin on the style record a row names.-#[derive(Clone, Copy, PartialEq, Eq)]+#[derive(Clone, Copy, Default, PartialEq, Eq)]enum ArenaStylePin {+ #[default]None,/// The arena derived the record for the row: an anonymous box's, or a style layout adjusted.Derived,@@ -1073,31 +1076,31 @@ struct CommittedLinkHolder {#[derive(Clone)]pub(crate) struct LayoutNodeArena {- chunks: Vec<Box<Chunk>>,+ chunks: ForkVec<Box<Chunk>>,tree_shape: TreeShape,/// Advanced by every write to a node's shape, or to the style record or node kept beside it, which/// publication takes into the published rows.shape_writes: ShapeWrites,- slot_metadata: Vec<SlotMetadata>,- style_records: Vec<u64>,+ slot_metadata: ForkVec<SlotMetadata>,+ style_records: ForkVec<u64>,/// How many of `style_records` name a record other than one the engine installed.rows_naming_uninstalled_records: u32,/// The style record whose image resources the host was last owed for each row, or zero. A row whose record has not/// changed since holds those resources still, so a build that visits it again owes it nothing.- image_resources_owed_records: Vec<u64>,- style_record_pins: Vec<ArenaStylePin>,+ image_resources_owed_records: ForkVec<u64>,+ style_record_pins: ForkVec<ArenaStylePin>,/// The style record the host pinned for its readers of a row that outlive the row's place in/// the tree (a detached box is read until its row is freed), or zero. A pin is counted, so this/// is a pin of its own beside the arena's, and it names the record it took rather than whichever/// record the row holds when it goes.- style_records_pinned_by_host: Vec<u64>,- derived_styles_shown_before_host_installs: HashMap<NodeSlotId, DerivedStyleRecord>,+ style_records_pinned_by_host: ForkVec<u64>,+ derived_styles_shown_before_host_installs: CowMap<NodeSlotId, DerivedStyleRecord>,/// The StyleNodeID of the element or text node each row is bound to, or of the element it is/// generated for. Rows carrying one identity are chained through `next_rows_with_same_style_node`/// from `first_rows_by_style_node`, so retiring an identity reaches every row that carries it,/// bound or not, before the identity can be reused.- style_nodes: Vec<Option<StyleNodeID>>,- next_rows_with_same_style_node: Vec<NodeSlotId>,+ style_nodes: ForkVec<Option<StyleNodeID>>,+ next_rows_with_same_style_node: ForkVec<NodeSlotId>,first_rows_by_style_node: RowsByStyleNode,/// The row each element or text node is bound to: the row its layout node is. Carrying the/// identity does not make a row bound, since first-letter slices and rows awaiting a rebuild@@ -1136,21 +1139,21 @@ pub(crate) struct LayoutNodeArena {/// How many layouts were committed, full and partial.layout_commit_count: u64,/// Per slot, which fragment held the box's committed link when a commit last met it.- committed_link_holders: Vec<CommittedLinkHolder>,+ committed_link_holders: ForkVec<CommittedLinkHolder>,/// The boxes whose committed links a full commit met at the top of its pass, which no fragment holds.pass_level_committed_links: Vec<NodeSlotId>,- pub(crate) links_held_apart_from_their_containing_blocks: crate::fast_hash::FastSet<NodeSlotId>,+ pub(crate) links_held_apart_from_their_containing_blocks: CowSet<NodeSlotId>,layout_tree_build_stats: FfiLayoutTreeBuildStats,- pre_order_labels: Vec<u64>,+ pre_order_labels: ForkVec<u64>,pre_order_relabel_count: u64,- free_list: Vec<u32>,+ free_list: ForkVec<u32>,live_count: u32,default_scroll_shift_anchors: Vec<DefaultScrollShiftAnchorSlot>,text_slots: TextSlots,- pub(super) searchable_text: Option<Vec<super::text_queries::MappedText>>,+ pub(super) searchable_text: crate::fork::ForkReset<Option<Vec<super::text_queries::MappedText>>>,replaced_content_facts: CowVec<ReplacedContentFactsSlot, REPLACED_CONTENT_FACTS_PER_CHUNK>,/// The layout kind of each row built for a MathML element, from its tag name.- math_layout_kinds: HashMap<NodeSlotId, super::math_formatting_context::MathLayoutKind>,+ math_layout_kinds: CowMap<NodeSlotId, super::math_formatting_context::MathLayoutKind>,replaced_paint_facts: Arc<crate::painting::replaced_paint_facts::ReplacedPaintFactsTable>,layer_image_paint_facts: Arc<crate::painting::layer_image_paint_facts::LayerImagePaintFactsTable>,svg_paint_resources: crate::painting::svg_paint_resources::SvgPaintResources,@@ -1159,7 +1162,7 @@ pub(crate) struct LayoutNodeArena {/// The rows built for one DOM node, chained into a ring through the rows themselves; a row that/// is the only one built for its node links to nothing. The chain lives on the rows rather than/// under a key so that it survives the node's identity being retired and re-issued.- next_rows_built_for_same_node: Vec<NodeSlotId>,+ next_rows_built_for_same_node: ForkVec<NodeSlotId>,/// What writes since the layout stage last looked did to the boxes its run memos hold entries of.memo_invalidations: super::memo_invalidations::MemoInvalidations,pub(super) layout_trace: super::trace::TraceRecord,@@ -1170,32 +1173,32 @@ pub(crate) struct LayoutNodeArena {pub(crate) scrollable_overflow: crate::painting::scrollable_overflow::ScrollableOverflowState,pub(crate) partial_relayout_boundary_roots: super::partial_relayout::PartialRelayoutBoundaryRoots,nodes_with_layout_update_flags: Vec<NodeSlotId>,- layout_update_flag_node_indices: HashMap<NodeSlotId, usize>,+ layout_update_flag_node_indices: CowMap<NodeSlotId, usize>,/// Boxes whose child lists gained children since the last layout tree build, held back from/// layout invalidation until the build shows what the new children are.pub(crate) deferred_child_list_insertion_parents: Vec<(NodeSlotId, NodeSlotId)>,- pub(super) deferred_child_list_insertion_parent_slots: HashSet<NodeSlotId>,+ pub(super) deferred_child_list_insertion_parent_slots: CowSet<NodeSlotId>,pub(super) children_inserted_under_deferred_parents: Vec<(NodeSlotId, NodeSlotId)>,/// Layout inputs for new absolutely positioned boxes that the build confined to themselves./// They stand in for the committed inputs such a box does not have yet.- pub(crate) confined_abspos_layout_inputs: HashMap<NodeSlotId, AbsposLayoutInputs>,+ pub(crate) confined_abspos_layout_inputs: CowMap<NodeSlotId, AbsposLayoutInputs>,/// The position option each box with position options was last laid out with./// https://drafts.csswg.org/css-anchor-position-1/#fallback-apply- position_options_in_use: HashMap<NodeSlotId, super::abspos_inputs::PositionOptionChoice>,+ position_options_in_use: CowMap<NodeSlotId, super::abspos_inputs::PositionOptionChoice>,/// https://drafts.csswg.org/css-anchor-position-1/#last-successful-position-option- last_successful_position_options: HashMap<NodeSlotId, super::abspos_inputs::PositionOptionChoice>,+ last_successful_position_options: CowMap<NodeSlotId, super::abspos_inputs::PositionOptionChoice>,/// The style record and custom property environment of the element containing the letter, as each/// `::first-letter` box's style was last derived from them.- first_letter_parent_styles: HashMap<NodeSlotId, (u64, u64)>,+ first_letter_parent_styles: CowMap<NodeSlotId, (u64, u64)>,first_letter_styles_derived: std::sync::Arc<std::sync::atomic::AtomicBool>,- pub(crate) inline_boxes_lifted_out_of: HashMap<NodeSlotId, NodeSlotId>,- pub(crate) out_of_flow_positioning_contained: HashMap<NodeSlotId, u32>,+ pub(crate) inline_boxes_lifted_out_of: CowMap<NodeSlotId, NodeSlotId>,+ pub(crate) out_of_flow_positioning_contained: CowMap<NodeSlotId, u32>,/// Attribution of pending updates for partial relayout. Invariant: every update recorded/// since the last layout pass is either attributed to a boundary in the root set above, or/// this escape bit is set. Partial relayout may only run while the bit is clear; a full/// layout pass re-derives every fact boundary qualification depends on, so it clears the bit.pub(crate) pending_updates_escape_partial_relayout: bool,- text_nodes_enrolled_for_content_sync: HashSet<NodeSlotId>,+ text_nodes_enrolled_for_content_sync: CowSet<NodeSlotId>,/// The scroll containers a running tree build gave a style, which may be where scroll/// snapping happens once the build is over.built_scroll_containers: Vec<NodeSlotId>,@@ -1203,9 +1206,9 @@ pub(crate) struct LayoutNodeArena {/// the builds came to owe them, until the layout update the builds ran in is over.image_resources_owed_to_host: Vec<(NodeSlotId, OwedImageResources)>,/// The image boxes among the rows that own the provider of the image they show.- owned_image_providers: HashMap<NodeSlotId, OwnedImageProvider>,+ owned_image_providers: CowMap<NodeSlotId, OwnedImageProvider>,/// The text node that each `display: contents` text wrapper box wraps.- display_contents_text_wrappers: HashMap<NodeSlotId, StyleNodeID>,+ display_contents_text_wrappers: CowMap<NodeSlotId, StyleNodeID>,/// Whether a row has ever been given a style with `content-visibility: auto`.may_have_auto_content_visibility: bool,/// Whether a row has ever been given a style with a scroll snap type.@@ -1214,12 +1217,12 @@ pub(crate) struct LayoutNodeArena {/// The natural size of the image each image box that owns its image's provider shows/// (`content: url(...)`), as the provider publishes it: zero while the image is not available./// Such a box shows an image of its own rather than its element's.- owned_image_natural_sizes: HashMap<NodeSlotId, crate::css::style::NaturalSize>,+ owned_image_natural_sizes: CowMap<NodeSlotId, crate::css::style::NaturalSize>,/// The natural size layout last negotiated for the box of an `<svg>` document element, and that/// box. An `<object>` showing the document is sized from it.document_svg_root_natural_size: Option<(NodeSlotId, crate::css::style::NaturalSize)>,container_bases_read_by_committed_layout:- HashMap<NodeSlotId, Vec<(StyleNodeID, crate::css::style::ContainerUnitBases)>>,+ CowMap<NodeSlotId, Vec<(StyleNodeID, crate::css::style::ContainerUnitBases)>>,/// The document element's natural size as it was last handed to the `<object>` showing the/// document, if it has been.handed_over_document_svg_root_natural_size: Option<crate::css::style::NaturalSize>,@@ -1238,27 +1241,26 @@ pub(crate) struct LayoutNodeArena {impl LayoutNodeArena {/// The bytes of the columns that name the style record each row is built from.pub(crate) fn style_column_heap_size(&self) -> usize {- use crate::heap_size::vec_bytes;- vec_bytes(&self.style_records)- + vec_bytes(&self.image_resources_owed_records)- + vec_bytes(&self.style_record_pins)- + vec_bytes(&self.style_records_pinned_by_host)+ self.style_records.row_bytes()+ + self.image_resources_owed_records.row_bytes()+ + self.style_record_pins.row_bytes()+ + self.style_records_pinned_by_host.row_bytes()}pub(crate) fn new() -> Self {Self {- chunks: Vec::new(),+ chunks: ForkVec::default(),tree_shape: TreeShape::default(),shape_writes: ShapeWrites::default(),- slot_metadata: Vec::new(),- style_records: Vec::new(),+ slot_metadata: ForkVec::default(),+ style_records: ForkVec::default(),rows_naming_uninstalled_records: 0,- image_resources_owed_records: Vec::new(),- style_record_pins: Vec::new(),- style_records_pinned_by_host: Vec::new(),- derived_styles_shown_before_host_installs: HashMap::default(),- style_nodes: Vec::new(),- next_rows_with_same_style_node: Vec::new(),+ image_resources_owed_records: ForkVec::default(),+ style_record_pins: ForkVec::default(),+ style_records_pinned_by_host: ForkVec::default(),+ derived_styles_shown_before_host_installs: Default::default(),+ style_nodes: ForkVec::default(),+ next_rows_with_same_style_node: ForkVec::default(),first_rows_by_style_node: RowsByStyleNode::default(),bound_rows: Default::default(),viewport_scroll_offset: CssPixelPoint::default(),@@ -1275,24 +1277,24 @@ impl LayoutNodeArena {partial_layout_count: (0),full_layout_count: (0),layout_commit_count: 0,- committed_link_holders: Vec::new(),+ committed_link_holders: ForkVec::default(),pass_level_committed_links: Vec::new(),links_held_apart_from_their_containing_blocks: Default::default(),layout_tree_build_stats: (FfiLayoutTreeBuildStats::default()),- pre_order_labels: Vec::new(),+ pre_order_labels: ForkVec::default(),pre_order_relabel_count: 0,- free_list: Vec::new(),+ free_list: ForkVec::default(),live_count: 0,default_scroll_shift_anchors: Vec::new(),text_slots: TextSlots::default(),- searchable_text: None,+ searchable_text: Default::default(),replaced_content_facts: CowVec::default(),math_layout_kinds: Default::default(),replaced_paint_facts: Default::default(),layer_image_paint_facts: Default::default(),svg_paint_resources: crate::painting::svg_paint_resources::SvgPaintResources::default(),paint_fact_writes: 0,- next_rows_built_for_same_node: Vec::new(),+ next_rows_built_for_same_node: ForkVec::default(),memo_invalidations: Default::default(),layout_trace: super::trace::TraceRecord::default(),paintable_rows: crate::painting::paintable_rows::PaintableRowStore::default(),@@ -1300,19 +1302,19 @@ impl LayoutNodeArena {scrollable_overflow: Default::default(),partial_relayout_boundary_roots: Default::default(),nodes_with_layout_update_flags: Vec::new(),- layout_update_flag_node_indices: HashMap::default(),+ layout_update_flag_node_indices: Default::default(),deferred_child_list_insertion_parents: Vec::new(),- deferred_child_list_insertion_parent_slots: HashSet::default(),+ deferred_child_list_insertion_parent_slots: Default::default(),children_inserted_under_deferred_parents: Vec::new(),- confined_abspos_layout_inputs: HashMap::default(),- position_options_in_use: (HashMap::default()),- last_successful_position_options: (HashMap::default()),- first_letter_parent_styles: HashMap::default(),+ confined_abspos_layout_inputs: Default::default(),+ position_options_in_use: (Default::default()),+ last_successful_position_options: (Default::default()),+ first_letter_parent_styles: Default::default(),first_letter_styles_derived: std::sync::Arc::default(),- inline_boxes_lifted_out_of: HashMap::default(),- out_of_flow_positioning_contained: HashMap::default(),+ inline_boxes_lifted_out_of: Default::default(),+ out_of_flow_positioning_contained: Default::default(),pending_updates_escape_partial_relayout: false,- text_nodes_enrolled_for_content_sync: HashSet::default(),+ text_nodes_enrolled_for_content_sync: Default::default(),built_scroll_containers: Default::default(),image_resources_owed_to_host: Default::default(),owned_image_providers: Default::default(),@@ -1320,9 +1322,9 @@ impl LayoutNodeArena {may_have_auto_content_visibility: false,may_have_scroll_snap_areas: false,nodes_enrolled_for_replaced_content_facts_sync: Vec::new(),- owned_image_natural_sizes: HashMap::default(),+ owned_image_natural_sizes: Default::default(),document_svg_root_natural_size: None,- container_bases_read_by_committed_layout: HashMap::default(),+ container_bases_read_by_committed_layout: Default::default(),handed_over_document_svg_root_natural_size: (None),layout_style_snapshot_commit: Vec::new(),layout_tree_update_marks: Default::default(),@@ -1336,8 +1338,7 @@ impl LayoutNodeArena {pub(crate) fn note_committed_link_holder(&mut self, id: NodeSlotId, holder: NodeSlotId, commit: u32) {let index = id.slot_index() as usize;if self.committed_link_holders.len() <= index {- self.committed_link_holders- .resize(index + 1, CommittedLinkHolder::default());+ self.committed_link_holders.resize_with_default(index + 1);}self.committed_link_holders[index] = CommittedLinkHolder {generation: id.generation(),@@ -1380,7 +1381,7 @@ impl LayoutNodeArena {/// What writes did to the boxes the layout stage's run memos hold entries of since the stage last took it.pub(crate) fn take_memo_invalidations(&mut self) -> super::memo_invalidations::MemoInvalidations {- for state in self.text_slots.released_states.drain(..) {+ for state in self.text_slots.released_states.take_rows() {self.memo_invalidations.note_text_state_dropped(state);}std::mem::take(&mut self.memo_invalidations)@@ -1507,7 +1508,7 @@ impl LayoutNodeArena {);if (index as usize).is_multiple_of(SLOTS_PER_CHUNK) {let chunk_index = self.chunks.len();- self.chunks.push(Chunk::new());+ self.chunks.resize_with_default(chunk_index + 1);self.shape_writes.add_chunk(chunk_index);}self.slot_metadata.push(SlotMetadata::default());@@ -1604,7 +1605,7 @@ impl LayoutNodeArena {}fn free_unlinked_slot(&mut self, id: NodeSlotId) -> Option<crate::painting::paintable_rows::PaintableRowReset> {- self.searchable_text = None;+ *self.searchable_text = None;let index = id.slot_index();let id_generation = id.generation();let should_reuse = {@@ -2390,15 +2391,10 @@ impl LayoutNodeArena {.expect("a derived style row holds its style"),};self.style_record_pins[index] = ArenaStylePin::None;- let holds_an_older_shown_style = match self.derived_styles_shown_before_host_installs.entry(slot) {- std::collections::hash_map::Entry::Occupied(_) => true,- std::collections::hash_map::Entry::Vacant(entry) => {- entry.insert(shown);- false- }- };- if holds_an_older_shown_style {+ if self.derived_styles_shown_before_host_installs.contains_key(&slot) {self.with_style_engine(|engine| engine.unpin_layout_style_record(shown.record));+ } else {+ self.derived_styles_shown_before_host_installs.insert(slot, shown);}self.install_style_record(slot, style_record, payloads, None);}@@ -2892,8 +2888,8 @@ impl LayoutNodeArena {&mut self.svg_paint_resources}- /// A fork of the arena, linked to `engine`, the fork of its style engine: its chunks have addresses of their own,- /// and the flags the arena shares with the host are its own. See [`crate::fork`].+ /// A fork of the arena, linked to `engine`, the fork of its style engine: the flags the arena shares with the host+ /// are its own. See [`crate::fork`].pub(crate) fn fork(&self, engine: crate::css::style::StyleEngineHandle) -> Self {let mut fork = self.clone();fork.style_engine = ArenaStyleEngine(engine);@@ -3082,7 +3078,7 @@ impl LayoutNodeArena {return;}let mut readers_whose_bases_moved = Vec::new();- for (&reader, bases_read) in &self.container_bases_read_by_committed_layout {+ for (&reader, bases_read) in self.container_bases_read_by_committed_layout.iter() {if !self.slot_is_live(reader) {readers_whose_bases_moved.push(reader);continue;@@ -4097,7 +4093,7 @@ impl LayoutNodeArena {}/// The style records the rows name.- pub(crate) fn style_records(&self) -> &[u64] {+ pub(crate) fn style_records(&self) -> &ForkVec<u64> {&self.style_records}@@ -5451,7 +5447,7 @@ impl LayoutNodeArena {.state_index(id).expect("the row has the text it was just given");self.memo_invalidations.note_text_state_dropped(text_state);- self.searchable_text = None;+ *self.searchable_text = None;// Publication can happen through a C++ text read before the enrolled// sync runs. Invalidate here so every publication invalidates layout,// including mapping-only changes with identical rendered code units.@@ -5524,7 +5520,7 @@ impl LayoutNodeArena {}pub(crate) fn invalidate_searchable_text(&mut self) {- self.searchable_text = None;+ *self.searchable_text = None;}/// Gives the row the spans its element published again, after one of the element's spandiff --git a/Libraries/LibWeb/Rust/src/layout/memo_invalidations.rs b/Libraries/LibWeb/Rust/src/layout/memo_invalidations.rsindex 1d0457abc56..259d361fb1f 100644--- a/Libraries/LibWeb/Rust/src/layout/memo_invalidations.rs+++ b/Libraries/LibWeb/Rust/src/layout/memo_invalidations.rs@@ -31,21 +31,25 @@ struct SlotNotes {generation: u8,}+const NOTES_PER_PAGE: usize = 256;+/// The notes of each box the arena wrote since the stage last applied them, in the order the boxes were first noted.#[derive(Clone, Default)]pub(crate) struct MemoInvalidations {- slots: Vec<SlotNotes>,+ /// Each page holds the notes of `NOTES_PER_PAGE` slots, and comes to be with the first of them noted, so that a copy+ /// of the notes costs what was noted.+ pages: Vec<Option<Box<[SlotNotes; NOTES_PER_PAGE]>>>,noted_slots: Vec<u32>,dropped_text_states: Vec<u32>,}impl MemoInvalidations {fn notes_of(&mut self, slot: u32) -> &mut SlotNotes {- let index = slot as usize;- if self.slots.len() <= index {- self.slots.resize_with(index + 1, SlotNotes::default);+ let (page, row) = (slot as usize / NOTES_PER_PAGE, slot as usize % NOTES_PER_PAGE);+ if self.pages.len() <= page {+ self.pages.resize_with(page + 1, || None);}- let notes = &mut self.slots[index];+ let notes = &mut self.pages[page].get_or_insert_with(|| Box::new([SlotNotes::default(); NOTES_PER_PAGE]))[row];if !notes.noted {notes.noted = true;self.noted_slots.push(slot);@@ -115,7 +119,9 @@ impl MemoInvalidations {text_memos.forget(text_state);}for slot in self.noted_slots {- let notes = self.slots[slot as usize];+ let notes = self.pages[slot as usize / NOTES_PER_PAGE]+ .as_ref()+ .expect("a noted slot has its page")[slot as usize % NOTES_PER_PAGE];if notes.run_cache_entries_dropped {run_cache.remove_entry(slot);} else if notes.structural_inline_changes > 0 || notes.fragment_cache_epoch_bumped {diff --git a/Libraries/LibWeb/Rust/src/layout/text_queries.rs b/Libraries/LibWeb/Rust/src/layout/text_queries.rsindex ec6a64597d1..ed571dae34b 100644--- a/Libraries/LibWeb/Rust/src/layout/text_queries.rs+++ b/Libraries/LibWeb/Rust/src/layout/text_queries.rs@@ -391,7 +391,7 @@ fn ensure_searchable_text(}}builder.flush();- arena.searchable_text = Some(builder.blocks);+ *arena.searchable_text = Some(builder.blocks);}/// A range in the DOM text the layout rows render, between the DOM text nodes the identities@@ -585,10 +585,10 @@ mod tests {let mut builder = SearchTextBuilder::default();builder.append(text, &arena.text_content(text).unwrap().text, false);builder.flush();- arena.searchable_text = Some(builder.blocks);+ *arena.searchable_text = Some(builder.blocks);arena.set_text_content(text, TextContent::for_test("world", 0, 5, Vec::new()));assert!(arena.searchable_text.is_none());- arena.searchable_text = Some(Vec::new());+ *arena.searchable_text = Some(Vec::new());arena.free_subtree(text).destroy_shells_and_invoke_callbacks(&crate::stage::MainThread::for_test());@@ -602,7 +602,7 @@ mod tests {let mut builder = SearchTextBuilder::default();builder.append(text, &arena.text_content(text).unwrap().text, false);builder.flush();- arena.searchable_text = Some(builder.blocks);+ *arena.searchable_text = Some(builder.blocks);let query: Vec<u16> = "foo".encode_utf16().collect();let offsets: Vec<_> = find_matching_text(&mut arena, text, &query, true, &[]).iter()diff --git a/Libraries/LibWeb/Rust/src/layout/tree_shape.rs b/Libraries/LibWeb/Rust/src/layout/tree_shape.rsindex 59886cf4127..f8f2070c5e5 100644--- a/Libraries/LibWeb/Rust/src/layout/tree_shape.rs+++ b/Libraries/LibWeb/Rust/src/layout/tree_shape.rs@@ -20,6 +20,7 @@ use super::layout_node_arena::SLOTS_PER_CHUNK;use super::node_data::{LayoutStyleRef, NodeData, NodeFlag, NodeKind, NodeSlotId, PaintNode};use crate::cow_column::{ColumnSnapshot, CowColumn};use crate::css::style::tree::StyleNodeID;+use crate::fork_vec::ForkVec;use std::ops::Deref;/// A field of a node the paint side reads. It reads like a plain field, and is written through a@@ -56,7 +57,7 @@ pub(crate) struct ShapeWrites {identity: u64,style: u64,/// One bit per chunk holding a node marked since the last publication, so that publishing visits those alone.- written_chunks: Vec<u64>,+ written_chunks: ForkVec<u64>,}impl ShapeWrites {@@ -94,7 +95,7 @@ impl ShapeWrites {/// Makes room for the chunk at `chunk_index`, whose nodes are all marked as it is made.pub(crate) fn add_chunk(&mut self, chunk_index: usize) {- self.written_chunks.resize(chunk_index / 64 + 1, 0);+ self.written_chunks.resize_with_default(chunk_index / 64 + 1);self.note_chunk_written(chunk_index);}@@ -103,20 +104,18 @@ impl ShapeWrites {}/// The chunks holding a node marked since the last publication, which it forgets.- fn take_written_chunks(&mut self) -> impl Iterator<Item = usize> + '_ {- self.written_chunks- .iter_mut()- .enumerate()- .flat_map(|(word_index, word)| {- let mut chunks = std::mem::take(word);- std::iter::from_fn(move || {- (chunks != 0).then(|| {- let chunk = chunks.trailing_zeros() as usize;- chunks &= chunks - 1;- word_index * 64 + chunk- })+ fn take_written_chunks(&mut self) -> impl Iterator<Item = usize> + use<> {+ let words = self.written_chunks.take_rows();+ self.written_chunks.resize_with_default(words.len());+ words.into_iter().enumerate().flat_map(|(word_index, mut chunks)| {+ std::iter::from_fn(move || {+ (chunks != 0).then(|| {+ let chunk = chunks.trailing_zeros() as usize;+ chunks &= chunks - 1;+ word_index * 64 + chunk})})+ })}}@@ -237,22 +236,16 @@ pub(crate) struct Chunk {written_rows: [u64; SLOTS_PER_CHUNK / 64],}-impl Chunk {- pub(crate) fn new() -> Box<Self> {- // SAFETY: Every slot is written with NodeData::default() and every mark word with all bits- // set before the chunk is exposed. The chunk is built in place on the heap because it is- // far too large for the stack.- unsafe {- let mut chunk = Box::<Self>::new_uninit();- let slots = &raw mut (*chunk.as_mut_ptr()).slots;- for offset in 0..SLOTS_PER_CHUNK {- (&raw mut (*slots)[offset]).write(NodeData::default());- }- (&raw mut (*chunk.as_mut_ptr()).written_rows).write([u64::MAX; SLOTS_PER_CHUNK / 64]);- chunk.assume_init()+impl Default for Chunk {+ fn default() -> Self {+ Self {+ slots: std::array::from_fn(|_| NodeData::default()),+ written_rows: [u64::MAX; SLOTS_PER_CHUNK / 64],}}+}+impl Chunk {#[inline]pub(crate) fn slot(&self, offset: usize) -> &NodeData {&self.slots[offset]@@ -318,9 +311,9 @@ impl TreeShape {/// publication shares is copied only for a change.pub(crate) fn publish(&mut self,- chunks: &mut [Box<Chunk>],- style_records: &[u64],- style_nodes: &[Option<StyleNodeID>],+ chunks: &mut ForkVec<Box<Chunk>>,+ style_records: &ForkVec<u64>,+ style_nodes: &ForkVec<Option<StyleNodeID>>,style_is_derived: impl Fn(usize) -> bool,writes: &mut ShapeWrites,) -> ColumnSnapshot<PaintNode, PUBLISHED_ROWS_PER_CHUNK> {@@ -359,9 +352,27 @@ const _: () = {mod tests {use super::*;+ fn clone_bytes_of_arena_with_rows(rows: usize) -> i64 {+ let mut arena = crate::layout::LayoutNodeArena::new();+ for _ in 0..rows {+ arena.allocate_unbound();+ }+ let (clone, bytes) = crate::css::style::pipeline::allocation_count::count_live_bytes(|| arena.clone());+ drop(clone);+ bytes+ }++ #[test]+ fn forking_the_arena_allocates_the_same_however_many_rows_it_holds() {+ assert_eq!(+ clone_bytes_of_arena_with_rows(1_000),+ clone_bytes_of_arena_with_rows(200_000)+ );+ }+#[test]fn a_write_that_changes_a_node_marks_it_and_one_that_does_not_leaves_it_unmarked() {- let mut chunk = Chunk::new();+ let mut chunk = Box::<Chunk>::default();let mut writes = ShapeWrites::default();writes.add_chunk(0);assert!(chunk.is_marked(0), "a new chunk's nodes are all marked");@@ -390,7 +401,7 @@ mod tests {#[test]fn only_a_write_of_what_a_row_is_counts_as_an_identity_write() {- let mut chunk = Chunk::new();+ let mut chunk = Box::<Chunk>::default();let mut writes = ShapeWrites::default();writes.add_chunk(0);let mut shape = chunk.write_shape(0, 3, &mut writes);@@ -410,7 +421,7 @@ mod tests {#[test]fn a_publication_visits_only_the_chunks_holding_a_marked_node() {- let mut chunk = Chunk::new();+ let mut chunk = Box::<Chunk>::default();let mut writes = ShapeWrites::default();for chunk_index in [0, 1, 70] {writes.add_chunk(chunk_index);diff --git a/Libraries/LibWeb/Rust/src/lib.rs b/Libraries/LibWeb/Rust/src/lib.rsindex 10f533a34df..f0006afa05c 100644--- a/Libraries/LibWeb/Rust/src/lib.rs+++ b/Libraries/LibWeb/Rust/src/lib.rs@@ -15,8 +15,10 @@ mod rust_demangle;mod rust_panic;pub(crate) mod cow_column;+pub(crate) mod cow_map;mod encoding_detection;pub(crate) mod fork;+pub(crate) mod fork_vec;#[cfg(test)]mod gfx_test_stubs;pub(crate) mod heap_size;diff --git a/Libraries/LibWeb/Rust/src/painting/image_map_areas.rs b/Libraries/LibWeb/Rust/src/painting/image_map_areas.rsindex 1b459e99b54..7b1da1087a8 100644--- a/Libraries/LibWeb/Rust/src/painting/image_map_areas.rs+++ b/Libraries/LibWeb/Rust/src/painting/image_map_areas.rs@@ -4,7 +4,6 @@* SPDX-License-Identifier: BSD-2-Clause*/-use crate::css::style::fast_hash::FastMap;use crate::layout::node_data::NodeSlotId;use libgfx_rust::path::Path;use libgfx_rust::{FloatPoint, WindingRule};@@ -189,7 +188,7 @@ pub struct ImageMapAreaColumn {}/// The `<area>` elements of the image map of every image that has one, by the image's paintable row.-pub type ImageMaps = FastMap<NodeSlotId, Arc<[PublishedImageMapArea]>>;+pub type ImageMaps = crate::cow_map::CowMap<NodeSlotId, Arc<[PublishedImageMapArea]>>;impl ImageMapAreaColumn {/// Publishes the `<area>` elements of the image map an image is associated with, in tree order.diff --git a/Libraries/LibWeb/Rust/src/painting/layer_image_paint_facts.rs b/Libraries/LibWeb/Rust/src/painting/layer_image_paint_facts.rsindex fc48fa7754b..7e1b3a87e11 100644--- a/Libraries/LibWeb/Rust/src/painting/layer_image_paint_facts.rs+++ b/Libraries/LibWeb/Rust/src/painting/layer_image_paint_facts.rs@@ -41,7 +41,7 @@ impl LayerImagePaintFacts {/// Each row's layer image paint facts. A publication shares the table, so a write copies it only/// while a publication still holds it.pub(crate) type LayerImagePaintFactsTable =- crate::css::style::fast_hash::FastMap<crate::layout::node_data::NodeSlotId, Vec<LayerImagePaintFactsEntry>>;+ crate::cow_map::CowMap<crate::layout::node_data::NodeSlotId, Vec<LayerImagePaintFactsEntry>>;/// The layer image paint facts of one image layer of a row of `table`.pub(crate) fn layer_image_paint_facts_in(diff --git a/Libraries/LibWeb/Rust/src/painting/paintable_rows.rs b/Libraries/LibWeb/Rust/src/painting/paintable_rows.rsindex 47a7dd046b1..702621e22bc 100644--- a/Libraries/LibWeb/Rust/src/painting/paintable_rows.rs+++ b/Libraries/LibWeb/Rust/src/painting/paintable_rows.rs@@ -4,7 +4,7 @@* SPDX-License-Identifier: BSD-2-Clause*/-use crate::cow_column::{CowColumn, RowMut};+use crate::cow_column::{CowColumn, CowVec, RowMut};use crate::layout::LayoutNodeArena;use crate::layout::fragment_tree;use crate::layout::node_data::{NodeFlag, NodeSlotId};@@ -198,7 +198,7 @@ impl PartialEq for CommittedFragmentLinkSlot {// for, so a slot that has been recycled since answers for the new row and not the old one.#[derive(Clone, Default)]pub(crate) struct UniqueNodeIdColumn {- ids: Vec<(NodeSlotId, i64)>,+ ids: crate::fork_vec::ForkVec<(NodeSlotId, i64)>,}impl UniqueNodeIdColumn {@@ -215,7 +215,7 @@ impl UniqueNodeIdColumn {}let index = slot.slot_index() as usize;if self.ids.len() <= index {- self.ids.resize(index + 1, (NodeSlotId::INVALID, 0));+ self.ids.resize_with_default(index + 1);}self.ids[index] = (slot, id);}@@ -225,9 +225,9 @@ impl UniqueNodeIdColumn {pub(crate) struct PaintableRowStore {rows: CowColumn<PaintableData, PAINTABLE_SLOTS_PER_CHUNK>,/// In chunks a fork of the arena shares until either side writes one, so forking does not copy every row's.- side_data: crate::cow_column::CowVec<PaintableSideData, PAINTABLE_SLOTS_PER_CHUNK>,+ side_data: CowVec<PaintableSideData, PAINTABLE_SLOTS_PER_CHUNK>,committed_side_data: CowColumn<CommittedSideData, PAINTABLE_SLOTS_PER_CHUNK>,- pub(crate) row_paint_states: Vec<RowPaintState>,+ pub(crate) row_paint_states: crate::fork_vec::ForkVec<RowPaintState>,pub(crate) damage: DamageSet,// NB: Boxed, as most rows have no record, and a row holds no more than a pointer for one.visual_context_records: CowColumn<Option<Box<PaintableVisualContextRecord>>, PAINTABLE_SLOTS_PER_CHUNK>,diff --git a/Libraries/LibWeb/Rust/src/painting/record/damage.rs b/Libraries/LibWeb/Rust/src/painting/record/damage.rsindex 82ad1be259e..08beb689534 100644--- a/Libraries/LibWeb/Rust/src/painting/record/damage.rs+++ b/Libraries/LibWeb/Rust/src/painting/record/damage.rs@@ -148,7 +148,7 @@ impl RowPaintState {pub(crate) struct DamageSet {// Every row whose damage is non-empty, listed once when its first bit is pushed. Entries of// rows reset since are skipped by their slot generation.- rows: Vec<NodeSlotId>,+ rows: crate::fork_vec::ForkVec<NodeSlotId>,// Zero, or the stamp the whole-document damage was pushed at.all: u32,scroll_metadata_everywhere: u32,@@ -401,11 +401,11 @@ impl LayoutNodeArena {/// A recording that publishes nothing consumes no damage, so damage goes on accumulating: only the rows gone since,/// and those listed again, leave the list.pub(crate) fn forget_paint_damage_rows_gone(&mut self) {- let mut rows = std::mem::take(&mut self.paintable_rows.damage.rows);+ let mut rows = self.paintable_rows.damage.rows.take_rows();rows.retain(|row| self.paintable_row_is_populated(*row));rows.sort_unstable_by_key(|row| (row.slot_index(), row.generation()));rows.dedup();- self.paintable_rows.damage.rows = rows;+ self.paintable_rows.damage.rows = rows.into_iter().collect();}/// The published recording consumed everything pushed before it started. Rows pushed since@@ -419,7 +419,7 @@ impl LayoutNodeArena {if set.scroll_metadata_everywhere != 0 && set.scroll_metadata_everywhere <= consumed_through {set.scroll_metadata_everywhere = 0;}- let listed = std::mem::take(&mut set.rows);+ let listed = set.rows.take_rows();let mut kept = Vec::new();for row in listed {if !self.paintable_row_is_populated(row) {@@ -435,7 +435,7 @@ impl LayoutNodeArena {// A row populated again after its push is listed again by its next push.kept.sort_unstable_by_key(|row| (row.slot_index(), row.generation()));kept.dedup();- self.paintable_rows.damage.rows.clone_from(&kept);+ self.paintable_rows.damage.rows = kept.iter().copied().collect();for row in kept {let stamp = self.paintable_rows.row_paint_states[row.slot_index() as usize].damage_stamp;self.hint_descendant_readers_above(row, stamp);@@ -647,7 +647,10 @@ mod tests {let mut expected = vec![root, rows[0], rows[1], rows[2]];expected.sort_unstable_by_key(|row| (row.slot_index(), row.generation()));- assert_eq!(arena.paintable_rows.damage.rows, expected);+ assert_eq!(+ arena.paintable_rows.damage.rows.iter().copied().collect::<Vec<_>>(),+ expected+ );}#[test]diff --git a/Libraries/LibWeb/Rust/src/painting/replaced_paint_facts.rs b/Libraries/LibWeb/Rust/src/painting/replaced_paint_facts.rsindex b4694bab76a..6ebd4fad490 100644--- a/Libraries/LibWeb/Rust/src/painting/replaced_paint_facts.rs+++ b/Libraries/LibWeb/Rust/src/painting/replaced_paint_facts.rs@@ -75,7 +75,7 @@ impl ImagePaintFacts {/// Each replaced row's paint facts. A publication shares the table, so a write copies it only while/// a publication still holds it.pub(crate) type ReplacedPaintFactsTable =- crate::css::style::fast_hash::FastMap<crate::layout::node_data::NodeSlotId, ReplacedPaintFacts>;+ crate::cow_map::CowMap<crate::layout::node_data::NodeSlotId, ReplacedPaintFacts>;#[derive(Clone, Debug, PartialEq)]pub(crate) enum ReplacedPaintFacts {diff --git a/Libraries/LibWeb/Rust/src/painting/svg_paint_resources.rs b/Libraries/LibWeb/Rust/src/painting/svg_paint_resources.rsindex 70066ecd099..16d8f42fc4f 100644--- a/Libraries/LibWeb/Rust/src/painting/svg_paint_resources.rs+++ b/Libraries/LibWeb/Rust/src/painting/svg_paint_resources.rs@@ -4,7 +4,6 @@* SPDX-License-Identifier: BSD-2-Clause*/-use std::collections::HashMap;use std::sync::Arc;use std::sync::atomic::{AtomicBool, Ordering};@@ -119,7 +118,7 @@ impl SvgPaintResourceRow {/// Each enrolled row's published SVG paint resources. A publication shares the table, so a write/// copies it only while a publication still holds it.-pub(crate) type SvgPaintResourceRows = HashMap<NodeSlotId, SvgPaintResourceRow>;+pub(crate) type SvgPaintResourceRows = crate::cow_map::CowMap<NodeSlotId, SvgPaintResourceRow>;#[derive(Clone, Default)]pub(crate) struct SvgPaintResources {diff --git a/Libraries/LibWeb/Rust/src/painting/visual_context/dirty.rs b/Libraries/LibWeb/Rust/src/painting/visual_context/dirty.rsindex eca93b0b3f1..46672911739 100644--- a/Libraries/LibWeb/Rust/src/painting/visual_context/dirty.rs+++ b/Libraries/LibWeb/Rust/src/painting/visual_context/dirty.rs@@ -5,7 +5,6 @@*/use super::BoxVisualContextNodeHandles;-use crate::fast_hash::FastMap as HashMap;use crate::layout::node_data::NodeSlotId;pub use crate::painting::host::VisualContextUpdateScope;@@ -71,7 +70,7 @@ pub struct RemovedBoxBlocks {#[derive(Clone, Default)]pub struct VisualContextDirtySet {- pub boxes: HashMap<NodeSlotId, BoxDirtyBits>,+ pub boxes: crate::fork::ForkShared<crate::fast_hash::FastMap<NodeSlotId, BoxDirtyBits>>,pub removed: Vec<RemovedBoxBlocks>,pub scope: VisualContextUpdateScope,}@@ -101,7 +100,15 @@ impl VisualContextDirtySet {pub fn request_full_rebuild(&mut self, scope: VisualContextUpdateScope) {self.scope = self.scope.max(scope);- self.boxes.clear();+ self.forget_boxes();+ }++ /// Forgets the boxes, keeping the map's room where no fork shares it.+ fn forget_boxes(&mut self) {+ match self.boxes.unshared_mut() {+ Some(boxes) => boxes.clear(),+ None => self.boxes.assign(Default::default()),+ }}pub fn is_empty(&self) -> bool {@@ -116,7 +123,7 @@ impl VisualContextDirtySet {}pub fn clear(&mut self) {- self.boxes.clear();+ self.forget_boxes();self.removed.clear();self.scope = VisualContextUpdateScope::DirtyPath;}diff --git a/Libraries/LibWeb/Rust/src/painting/visual_context/incremental.rs b/Libraries/LibWeb/Rust/src/painting/visual_context/incremental.rsindex 90d79afdfff..f772792e8ac 100644--- a/Libraries/LibWeb/Rust/src/painting/visual_context/incremental.rs+++ b/Libraries/LibWeb/Rust/src/painting/visual_context/incremental.rs@@ -69,10 +69,10 @@ struct WorkPlan {fn expand_dirty_entries(layout_arena: &impl PaintableRowsRead,dirty: &VisualContextDirtySet,- offset_path_boxes: &HashSet<NodeSlotId>,+ offset_path_boxes: &crate::cow_map::CowSet<NodeSlotId>,) -> Result<WorkPlan, VisualContextUpdateScope> {let mut work: HashMap<NodeSlotId, BoxDirtyBits> = HashMap::default();- for (slot, bits) in &dirty.boxes {+ for (slot, bits) in dirty.boxes.iter() {if !layout_arena.paintable_row_is_populated(*slot) {continue;}diff --git a/Libraries/LibWeb/Rust/src/painting/visual_context/records.rs b/Libraries/LibWeb/Rust/src/painting/visual_context/records.rsindex a562535c819..e2273a4cd80 100644--- a/Libraries/LibWeb/Rust/src/painting/visual_context/records.rs+++ b/Libraries/LibWeb/Rust/src/painting/visual_context/records.rs@@ -25,7 +25,7 @@ pub struct VisualContextState {// The list the tree was last given, which the next pass compares its own against.pub published_compositor_animations: Vec<VisualAnimation>,// The boxes whose transform node has an offset path, which depends on the geometry of their containing block.- pub offset_path_boxes: crate::fast_hash::FastSet<NodeSlotId>,+ pub offset_path_boxes: crate::cow_map::CowSet<NodeSlotId>,}impl VisualContextState {diff --git a/Libraries/LibWeb/Rust/src/render_state/clock/lane.rs b/Libraries/LibWeb/Rust/src/render_state/clock/lane.rsindex c35c31f7b4b..70f7e88e677 100644--- a/Libraries/LibWeb/Rust/src/render_state/clock/lane.rs+++ b/Libraries/LibWeb/Rust/src/render_state/clock/lane.rs@@ -134,8 +134,8 @@ enum FramePlan {Sealed(ClockPlan),}-/// Lets go of `lanes`, whose forks copy the document's whole render state: they are dropped once the owner no longer-/// holds the render states, which the host may be waiting for.+/// Lets go of `lanes`, whose forks may take long to drop: they are dropped once the owner no longer holds the render+/// states, which the host may be waiting for.fn retire(lanes: Lanes) {owner::drop_after_hold(lanes);}@@ -258,6 +258,16 @@ pub(in crate::render_state) fn note_host_write(document: DocumentId) {lane.state.move_on();return;}+ // NB: Nor does a coming lane tick while the update holds it, and with no animations to sample, what it would show+ // is what the update replaces or leaves showing, as above.+ if slot.taken_in.is_some()+ && let Lanes::Coming { pieces, .. } = &slot.lanes+ && matches!(&pieces.plan, FramePlan::Sealed(plan) if !plan.animates())+ && let Some(state) = slot.lanes.newest_state()+ {+ state.move_on();+ return;+ }// A lane that follows the pointer hovers beside the next task, which may begin as soon as this job is done,// whether or not its animations run beside the idle event loop.let needs_state = match &slot.lanes {diff --git a/Tests/LibWeb/Text/expected/css/style-memory/bytes-per-animated-element.txt b/Tests/LibWeb/Text/expected/css/style-memory/bytes-per-animated-element.txtindex edc899f3497..1d81cbc76f3 100644--- a/Tests/LibWeb/Text/expected/css/style-memory/bytes-per-animated-element.txt+++ b/Tests/LibWeb/Text/expected/css/style-memory/bytes-per-animated-element.txt@@ -12,7 +12,7 @@ animation: 500 elementscustomProperties: within 0retainedSlots: within 36recordCells: within 4- installed: within 100+ installed: within 124projection: within 52hostTree: within 24elementDeclarations: within 0@@ -20,9 +20,9 @@ animation: 500 elementslayoutStyleColumns: within 28otherMaps: within 0styleValues: within 24- animationEffects: within 388+ animationEffects: within 432fontResolutions: within 0- cssAnimations: within 320+ cssAnimations: within 360hostMemo: within 180cppInstalledStyles: within 8cppHintProperties: within 0@@ -40,12 +40,12 @@ transition: 500 elementscustomProperties: within 0retainedSlots: within 36recordCells: within 4- installed: within 88+ installed: within 92projection: within 52hostTree: within 24elementDeclarations: within 0heldRecordMaps: within 12- layoutStyleColumns: within 0+ layoutStyleColumns: within 28otherMaps: within 0styleValues: within 0animationEffects: within 456diff --git a/Tests/LibWeb/Text/expected/css/style-memory/bytes-per-element-by-owner.txt b/Tests/LibWeb/Text/expected/css/style-memory/bytes-per-element-by-owner.txtindex 7af848430b5..871377c8349 100644--- a/Tests/LibWeb/Text/expected/css/style-memory/bytes-per-element-by-owner.txt+++ b/Tests/LibWeb/Text/expected/css/style-memory/bytes-per-element-by-owner.txt@@ -45,7 +45,7 @@ custom: 500 elements, 500 styledhostTree: within 24elementDeclarations: within 88heldRecordMaps: within 12- layoutStyleColumns: within 0+ layoutStyleColumns: within 28otherMaps: within 0styleValues: within 144animationEffects: within 0@@ -73,7 +73,7 @@ unique: 500 elements, 500 styledhostTree: within 24elementDeclarations: within 40heldRecordMaps: within 12- layoutStyleColumns: within 0+ layoutStyleColumns: within 28otherMaps: within 0styleValues: within 0animationEffects: within 0@@ -96,7 +96,7 @@ uniqueFont: 500 elements, 500 styledcustomProperties: within 0retainedSlots: within 36recordCells: within 0- installed: within 20+ installed: within 38projection: within 52hostTree: within 24elementDeclarations: within 40@@ -129,7 +129,7 @@ uniqueVisual: 500 elements, 500 styledhostTree: within 24elementDeclarations: within 40heldRecordMaps: within 12- layoutStyleColumns: within 0+ layoutStyleColumns: within 28otherMaps: within 0styleValues: within 180animationEffects: within 0@@ -152,12 +152,12 @@ substituted: 500 elements, 500 styledcustomProperties: within 448retainedSlots: within 36recordCells: within 0- installed: within 16+ installed: within 36projection: within 44hostTree: within 24elementDeclarations: within 84heldRecordMaps: within 12- layoutStyleColumns: within 0+ layoutStyleColumns: within 28otherMaps: within 0styleValues: within 160animationEffects: within 0diff --git a/Tests/LibWeb/Text/input/css/style-memory/bytes-per-animated-element.html b/Tests/LibWeb/Text/input/css/style-memory/bytes-per-animated-element.htmlindex 626c5858578..5ef5141a90c 100644--- a/Tests/LibWeb/Text/input/css/style-memory/bytes-per-animated-element.html+++ b/Tests/LibWeb/Text/input/css/style-memory/bytes-per-animated-element.html@@ -53,14 +53,14 @@payloads: 656,retainedSlots: 36,recordCells: 4,- installed: 100,+ installed: 124,projection: 52,hostTree: 24,heldRecordMaps: 12,layoutStyleColumns: 28,styleValues: 24,- animationEffects: 388,- cssAnimations: 320,+ animationEffects: 432,+ cssAnimations: 360,hostMemo: 180,cppInstalledStyles: 8,};@@ -69,10 +69,11 @@payloads: 352,retainedSlots: 36,recordCells: 4,- installed: 88,+ installed: 92,projection: 52,hostTree: 24,heldRecordMaps: 12,+ layoutStyleColumns: 28,animationEffects: 456,hostMemo: 248,cppInstalledStyles: 8,diff --git a/Tests/LibWeb/Text/input/css/style-memory/bytes-per-element-by-owner.html b/Tests/LibWeb/Text/input/css/style-memory/bytes-per-element-by-owner.htmlindex 4fb6229a91d..5ad3f74335d 100644--- a/Tests/LibWeb/Text/input/css/style-memory/bytes-per-element-by-owner.html+++ b/Tests/LibWeb/Text/input/css/style-memory/bytes-per-element-by-owner.html@@ -72,6 +72,7 @@projection: 52,hostTree: 24,elementDeclarations: 88,+ layoutStyleColumns: 28,heldRecordMaps: 12,styleValues: 144,hostMemo: 36,@@ -83,10 +84,11 @@groupValueFacts: 4,customProperties: 448,retainedSlots: 36,- installed: 16,+ installed: 36,projection: 44,hostTree: 24,elementDeclarations: 84,+ layoutStyleColumns: 28,heldRecordMaps: 12,styleValues: 160,hostMemo: 72,@@ -101,6 +103,7 @@projection: 52,hostTree: 24,elementDeclarations: 40,+ layoutStyleColumns: 28,heldRecordMaps: 12,cppInstalledStyles: 8,};@@ -110,7 +113,7 @@payloads: 340,groupValueFacts: 4,retainedSlots: 36,- installed: 20,+ installed: 38,projection: 52,hostTree: 24,elementDeclarations: 40,@@ -133,6 +136,7 @@projection: 52,hostTree: 24,elementDeclarations: 40,+ layoutStyleColumns: 28,heldRecordMaps: 12,styleValues: 180,cppInstalledStyles: 8,