Truly independent web browser
LibWeb: Keep the source text of style sheets compressed
Andreas Kling8947a3ade26a
diff --git a/Cargo.lock b/Cargo.lockindex 555402973fb..7d9c2ddf26c 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2034,6 +2034,7 @@ dependencies = ["hashbrown 0.17.1","ladybird_allocator","libcompositing_rust",+ "libcompress_rust","libgfx_rust","libipc_rust","liburl_rust",diff --git a/Libraries/LibWeb/Rust/Cargo.toml b/Libraries/LibWeb/Rust/Cargo.tomlindex ec7805ff64f..238e6210f4a 100644--- a/Libraries/LibWeb/Rust/Cargo.toml+++ b/Libraries/LibWeb/Rust/Cargo.toml@@ -19,6 +19,7 @@ foldhash = "0.2"hashbrown = "0.17.1"ladybird_allocator = { path = "../../RustAllocator", optional = true }libcompositing_rust = { path = "../../LibCompositing/Rust" }+libcompress_rust = { path = "../../LibCompress/Rust" }libgfx_rust = { path = "../../LibGfx/Rust", default-features = false }libipc_rust = { path = "../../LibIPC/Rust" }liburl_rust = { path = "../../LibURL/Rust", default-features = false }diff --git a/Libraries/LibWeb/Rust/src/css/parser/memory_tests.rs b/Libraries/LibWeb/Rust/src/css/parser/memory_tests.rsindex b343d057a12..5f57344e5f4 100644--- a/Libraries/LibWeb/Rust/src/css/parser/memory_tests.rs+++ b/Libraries/LibWeb/Rust/src/css/parser/memory_tests.rs@@ -180,7 +180,7 @@ fn parsed_sheet_bytes_per_unit() {name: "sheet, fixed",bytes: sheets,// NB: The arena holds the sheet's `@namespace` declarations and the rank of its compounds.- ceiling: 920.0,+ ceiling: 928.0,typical: "about 600-1000 B",},Unit {diff --git a/Libraries/LibWeb/Rust/src/css/parser/mod.rs b/Libraries/LibWeb/Rust/src/css/parser/mod.rsindex 938a2290f4e..cf4fd332071 100644--- a/Libraries/LibWeb/Rust/src/css/parser/mod.rs+++ b/Libraries/LibWeb/Rust/src/css/parser/mod.rs@@ -16,6 +16,7 @@ pub(crate) mod images_gradients_parser;mod memory_tests;pub(crate) mod positions_shapes_parser;pub(crate) mod query_parser;+pub(crate) mod sheet_source_text;mod stylesheet_cache;pub(crate) mod syntax;pub(crate) mod syntax_parser;diff --git a/Libraries/LibWeb/Rust/src/css/parser/sheet_source_text.rs b/Libraries/LibWeb/Rust/src/css/parser/sheet_source_text.rsnew file mode 100644index 00000000000..4ae308cace2--- /dev/null+++ b/Libraries/LibWeb/Rust/src/css/parser/sheet_source_text.rs@@ -0,0 +1,221 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The text a style sheet was parsed from. Only DevTools reads it, so a text of some size is kept+//! compressed: a thread of its own compresses each text soon after the parse, and a reader gets a+//! decompressed copy.++use crate::css::css_tokenizer::TokenizerInput;+use crate::css::style_value::RetainedString;+use libcompress_rust::{Compressor, Decompressor, Format};+use std::sync::{Arc, Mutex};++/// The smallest text that is worth compressing, in bytes.+const SMALLEST_COMPRESSED_TEXT_SIZE: usize = 10 * 1024;++enum State {+ Plain(RetainedString),+ Compressed { deflated: Box<[u8]>, is_latin1: bool },+}++/// The text of a sheet. A text that is too small to compress costs the sheet no more than the text itself.+pub(crate) enum SheetSourceText {+ Plain(RetainedString),+ Compressible(Arc<CompressibleText>),+}++impl SheetSourceText {+ /// The text of a parse that is not of a whole sheet, which has none.+ pub(crate) fn empty() -> Self {+ Self::Plain(RetainedString::from_ascii(String::new()))+ }++ /// The text of a sheet, which is compressed soon if that is worth it.+ pub(crate) fn new(source: TokenizerInput<'_>) -> Self {+ let plain = RetainedString::from_text(source);+ let size = match plain.units() {+ TokenizerInput::Latin1(bytes) => bytes.len(),+ TokenizerInput::Utf16(units) => size_of_val(units),+ };+ if size < SMALLEST_COMPRESSED_TEXT_SIZE {+ return Self::Plain(plain);+ }+ let text = Arc::new(CompressibleText::plain(plain));+ // NB: The tests that count what a parse allocates must not count what the queue allocates now and then.+ #[cfg(not(test))]+ compress_soon(&text);+ Self::Compressible(text)+ }++ pub(crate) fn to_utf16_string(&self) -> ak::Utf16String {+ match self {+ Self::Plain(text) => utf16_string_of(text),+ Self::Compressible(text) => text.to_utf16_string(),+ }+ }+}++fn utf16_string_of(text: &RetainedString) -> ak::Utf16String {+ match text.units() {+ TokenizerInput::Latin1(bytes) => ak::Utf16String::from_latin1(bytes),+ TokenizerInput::Utf16(units) => ak::Utf16String::from_utf16(units),+ }+}++pub(crate) struct CompressibleText {+ state: Mutex<State>,+}++impl CompressibleText {+ fn plain(text: RetainedString) -> Self {+ Self {+ state: Mutex::new(State::Plain(text)),+ }+ }++ fn to_utf16_string(&self) -> ak::Utf16String {+ match &*self.state.lock().expect("no reader of a sheet's text panics") {+ State::Plain(text) => utf16_string_of(text),+ State::Compressed { deflated, is_latin1 } => {+ let bytes = Decompressor::new(Format::Deflate)+ .decompress(deflated)+ .expect("a compressed text is what the compressor made of it")+ .output;+ if *is_latin1 {+ return ak::Utf16String::from_latin1(&bytes);+ }+ let units: Vec<u16> = bytes+ .as_chunks::<2>()+ .0+ .iter()+ .map(|bytes| u16::from_ne_bytes(*bytes))+ .collect();+ ak::Utf16String::from_utf16(&units)+ }+ }+ }++ fn compress(&self) {+ // NB: The lock is not held while the text is compressed, so a reader does not wait for that.+ let text = match &*self.state.lock().expect("no reader of a sheet's text panics") {+ State::Plain(text) => text.clone(),+ State::Compressed { .. } => return,+ };+ let mut compressor = Compressor::new(Format::Deflate);+ let mut deflated = Vec::new();+ let (is_latin1, size) = match text.units() {+ TokenizerInput::Latin1(bytes) => {+ let Ok(more) = compressor.compress(bytes) else {+ return;+ };+ deflated = more;+ (true, bytes.len())+ }+ TokenizerInput::Utf16(units) => {+ let mut bytes = Vec::new();+ for chunk in units.chunks(1 << 16) {+ bytes.clear();+ bytes.extend(chunk.iter().flat_map(|unit| unit.to_ne_bytes()));+ let Ok(more) = compressor.compress(&bytes) else {+ return;+ };+ deflated.extend(more);+ }+ (false, size_of_val(units))+ }+ };+ let Ok(end) = compressor.finish() else {+ return;+ };+ deflated.extend(end);+ if deflated.len() >= size {+ return;+ }+ *self.state.lock().expect("no reader of a sheet's text panics") = State::Compressed {+ deflated: deflated.into_boxed_slice(),+ is_latin1,+ };+ }+}++/// Hands the text to the thread that compresses the texts, which starts when the first text comes.+#[cfg(not(test))]+fn compress_soon(text: &Arc<CompressibleText>) {+ use std::sync::mpsc::{Sender, channel};+ use std::sync::{OnceLock, Weak};++ static QUEUE: OnceLock<Option<Mutex<Sender<Weak<CompressibleText>>>>> = OnceLock::new();+ let queue = QUEUE.get_or_init(|| {+ let (sender, receiver) = channel::<Weak<CompressibleText>>();+ std::thread::Builder::new()+ .name("CSS source text".into())+ .spawn(move || {+ let mut next = receiver.recv();+ while let Ok(text) = next {+ if let Some(text) = text.upgrade() {+ text.compress();+ }+ next = receiver.try_recv().or_else(|_| {+ // NB: The allocator keeps what a thread freed until the thread allocates again, which this+ // thread does not do until the next text comes, and it frees each text it compresses.+ // Standalone Rust tests do not link the C++ allocator.+ #[cfg(feature = "allocator")]+ ak::release_unused_allocator_memory();+ receiver.recv()+ });+ }+ })+ .ok()+ .map(|_| Mutex::new(sender))+ });+ if let Some(queue) = queue {+ let _ = queue+ .lock()+ .expect("sending a text does not panic")+ .send(Arc::downgrade(text));+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn units_of(text: &CompressibleText) -> Vec<u16> {+ text.to_utf16_string().to_utf16().into_owned()+ }++ #[test]+ fn a_compressed_text_reads_as_the_text_it_was() {+ let ascii = "a { color: red; } /* a comment */\n".repeat(1000);+ let wide: Vec<u16> = "b::before { content: \"\u{2192} \u{1f600}\"; }\n"+ .repeat(1000)+ .encode_utf16()+ .collect();++ let text = CompressibleText::plain(RetainedString::from_text(TokenizerInput::Latin1(ascii.as_bytes())));+ text.compress();+ assert!(+ matches!(&*text.state.lock().unwrap(), State::Compressed { deflated, .. } if deflated.len() < ascii.len() / 4)+ );+ assert_eq!(units_of(&text), ascii.encode_utf16().collect::<Vec<_>>());++ let text = CompressibleText::plain(RetainedString::from_text(TokenizerInput::Utf16(&wide)));+ text.compress();+ assert!(matches!(+ &*text.state.lock().unwrap(),+ State::Compressed { is_latin1: false, .. }+ ));+ assert_eq!(units_of(&text), wide);+ }++ #[test]+ fn a_text_that_does_not_get_smaller_stays_as_it_is() {+ let text = CompressibleText::plain(RetainedString::from_text(TokenizerInput::Latin1(b"a{}")));+ text.compress();+ assert!(matches!(&*text.state.lock().unwrap(), State::Plain(_)));+ assert_eq!(units_of(&text), "a{}".encode_utf16().collect::<Vec<_>>());+ }+}diff --git a/Libraries/LibWeb/Rust/src/css/parser/syntax_parser.rs b/Libraries/LibWeb/Rust/src/css/parser/syntax_parser.rsindex e912f2a00a8..0d5cd665304 100644--- a/Libraries/LibWeb/Rust/src/css/parser/syntax_parser.rs+++ b/Libraries/LibWeb/Rust/src/css/parser/syntax_parser.rs@@ -40,6 +40,7 @@ use crate::css::parser::query_parser::{parse_media_query_list_from_component_values, parse_supports_condition_from_component_values,parse_supports_declaration_from_component_values, resolve_query_feature, supports_feature_matches,};+use crate::css::parser::sheet_source_text::SheetSourceText;use crate::css::parser::stylesheet_cache::{CachedParseMetadata, parse_with_cache};use crate::css::parser::syntax::{SyntaxNode, parse_syntax, parse_with_syntax};use crate::css::parser::value_parser::{@@ -2561,7 +2562,7 @@ pub struct ParsedStyleSheet {identity_count: u64,/// The text the sheet was parsed from, which DevTools shows: one copy for every document the/// parse cache gives this parse.- source_text: RetainedString,+ source_text: SheetSourceText,pub(super) cache_metadata: Option<CachedParseMetadata>,declarations_kind: NestedDeclarationsKind,values: Box<[u16]>,@@ -2603,7 +2604,7 @@ impl ParsedStyleSheet {self.identity_count}- pub(crate) fn source_text(&self) -> &RetainedString {+ pub(crate) fn source_text(&self) -> &SheetSourceText {&self.source_text}@@ -3197,7 +3198,7 @@ impl<'a> SyntaxParseBuilder<'a> {};let mut parsed = ParsedStyleSheet {identity_count: self.identity_count,- source_text: RetainedString::from_ascii(String::new()),+ source_text: SheetSourceText::empty(),cache_metadata: None,declarations_kind: self.declarations_kind,values: values.into_boxed_slice(),@@ -4250,7 +4251,7 @@ pub(crate) fn parse_stylesheet_uncached(// As in every other parse, the tokens' own diagnostics come ahead of the rules'.parse.diagnostics.splice(0..0, parser.tokens.diagnostics);let mut parsed = parse.finish();- parsed.source_text = RetainedString::from_text(source);+ parsed.source_text = SheetSourceText::new(source);parsed}diff --git a/Libraries/LibWeb/Rust/src/css/rule.rs b/Libraries/LibWeb/Rust/src/css/rule.rsindex 0bcaa60a7bf..01cdde6cf19 100644--- a/Libraries/LibWeb/Rust/src/css/rule.rs+++ b/Libraries/LibWeb/Rust/src/css/rule.rs@@ -1136,10 +1136,7 @@ pub extern "C" fn rust_rule_list_source_text(list: &NativeRuleList, has_text: &mreturn ak::Utf16String::from_utf16(&[]).into_raw();};*has_text = true;- match sheet.source_text().units() {- crate::css::css_tokenizer::TokenizerInput::Latin1(bytes) => ak::Utf16String::from_latin1(bytes).into_raw(),- crate::css::css_tokenizer::TokenizerInput::Utf16(units) => ak::Utf16String::from_utf16(units).into_raw(),- }+ sheet.source_text().to_utf16_string().into_raw()}#[unsafe(no_mangle)]diff --git a/Meta/Linters/check_rust_process_wide_state.py b/Meta/Linters/check_rust_process_wide_state.pyindex ee178f25675..f5cf9ee65e7 100755--- a/Meta/Linters/check_rust_process_wide_state.py+++ b/Meta/Linters/check_rust_process_wide_state.py@@ -157,6 +157,7 @@ RENDER_STATE_ALLOWED = {**render_state_entries(LOCKED,[+ "css/parser/sheet_source_text.rs:QUEUE","css/parser/stylesheet_cache.rs:CACHE",],),