Truly independent web browser
LibWeb: Pass the encoding detector and font matcher spans
Andreas Klingcdf3cc28b3f1
diff --git a/Libraries/LibWeb/CSS/FontResolution.cpp b/Libraries/LibWeb/CSS/FontResolution.cppindex c45e165a377..ee46b3b3616 100644--- a/Libraries/LibWeb/CSS/FontResolution.cpp+++ b/Libraries/LibWeb/CSS/FontResolution.cpp@@ -188,7 +188,7 @@ static RefPtr<Gfx::FontCascadeList const> font_matching_algorithm(FontFaceSnapshweighed_candidates.unchecked_append({ candidate.key.weight.min, candidate.key.weight.max, candidate.key.slope, candidate.width });Vector<size_t> order;order.resize(matching_family_fonts.size());- auto order_length = Parser::ValueParserFFI::rust_font_matching_order(weighed_candidates.data(), weighed_candidates.size(), weight, font_width_bucket_from_percentage(font_width.value()), slope, order.data());+ auto order_length = Parser::ValueParserFFI::rust_font_matching_order(weighed_candidates.span(), weight, font_width_bucket_from_percentage(font_width.value()), slope, order.span());for (auto index : order.span().trim(order_length)) {if (auto found_font = matching_family_fonts[index].font_with_point_size(snapshot, font_size_in_pt, variations, shape_features))return found_font;diff --git a/Libraries/LibWeb/HTML/Parser/HTMLEncodingDetection.cpp b/Libraries/LibWeb/HTML/Parser/HTMLEncodingDetection.cppindex 36b39997b25..beac061dd54 100644--- a/Libraries/LibWeb/HTML/Parser/HTMLEncodingDetection.cpp+++ b/Libraries/LibWeb/HTML/Parser/HTMLEncodingDetection.cpp@@ -641,24 +641,17 @@ EncodingSniffingResult run_encoding_sniffing_algorithm(DOM::Document& document,// then return that encoding, with the confidence tentative. [UNIVCHARDET]auto tld_hint = extract_tld_hint(document.url());- u8 const* tld_data = tld_hint.is_empty() ? nullptr : reinterpret_cast<u8 const*>(tld_hint.characters());- size_t tld_size = tld_hint.length();u8 const* encoding_name_ptr = nullptr;size_t encoding_name_len = 0;bool allow_utf8_detection = document.url().scheme() == "file"sv;- if (Parser::rust_detect_encoding(- input.data(), input.size(),- tld_data, tld_size,- allow_utf8_detection,- &encoding_name_ptr, &encoding_name_len)) {- auto detected = StringView { reinterpret_cast<char const*>(encoding_name_ptr), encoding_name_len };- auto standardized = TextCodec::get_standardized_encoding(detected);- if (standardized.has_value())- return { ByteString { standardized.value() }, EncodingConfidence::Tentative };- }+ Parser::rust_detect_encoding(input, tld_hint.bytes(), allow_utf8_detection, &encoding_name_ptr, &encoding_name_len);+ auto detected = StringView { reinterpret_cast<char const*>(encoding_name_ptr), encoding_name_len };+ auto standardized = TextCodec::get_standardized_encoding(detected);+ if (standardized.has_value())+ return { ByteString { standardized.value() }, EncodingConfidence::Tentative };// 9. Otherwise, return an implementation-defined or user-specified default character encoding, with the confidence tentative.// In controlled environments or in environments where the encoding of documents can be prescribed (for example, for user agents intended for dedicated use in newdiff --git a/Libraries/LibWeb/Rust/cbindgen.toml b/Libraries/LibWeb/Rust/cbindgen.tomlindex 5543488de86..ea41b8458b1 100644--- a/Libraries/LibWeb/Rust/cbindgen.toml+++ b/Libraries/LibWeb/Rust/cbindgen.toml@@ -29,6 +29,7 @@ rename_types = "PascalCase"[export.rename]# An ak::Span is laid out as an AK ReadonlySpan, which C++ passes it as."Span" = "AK::ReadonlySpan"+"SpanMut" = "AK::Span"# A style engine handle is opaque to C++."StyleEngineHandle" = "const void*"# So is a parsed syntax, which C++ holds by pointer.diff --git a/Libraries/LibWeb/Rust/src/css/font_matching.rs b/Libraries/LibWeb/Rust/src/css/font_matching.rsindex 8e8163696ef..6f6a5afa993 100644--- a/Libraries/LibWeb/Rust/src/css/font_matching.rs+++ b/Libraries/LibWeb/Rust/src/css/font_matching.rs@@ -97,27 +97,18 @@ fn font_matching_order(length}-/// # Safety-///-/// `candidates` and `order` must point to `count` readable and writable elements respectively, and-/// `count` must not be zero.+/// Writes the order to try `candidates` in to `order`, which holds as many entries, and answers how many it wrote.#[unsafe(no_mangle)]-pub unsafe extern "C" fn rust_font_matching_order(- candidates: *const FfiFontMatchingCandidate,- count: usize,+pub extern "C" fn rust_font_matching_order(+ candidates: ak::Span<'_, FfiFontMatchingCandidate>,weight: i32,width: u32,slope: i32,- order: *mut usize,+ order: ak::SpanMut<'_, usize>,) -> usize {- // SAFETY: Guaranteed by the caller.- let (candidates, order) = unsafe {- (- ak::slice_from_raw_parts(candidates, count),- ak::slice_from_raw_parts_mut(order, count),- )- };- font_matching_order(candidates, weight, width, slope, order)+ let order = order.into_slice();+ assert_eq!(candidates.as_slice().len(), order.len());+ font_matching_order(candidates.as_slice(), weight, width, slope, order)}#[cfg(test)]diff --git a/Libraries/LibWeb/Rust/src/encoding_detection.rs b/Libraries/LibWeb/Rust/src/encoding_detection.rsindex 3cbd6deadad..6c0711105d5 100644--- a/Libraries/LibWeb/Rust/src/encoding_detection.rs+++ b/Libraries/LibWeb/Rust/src/encoding_detection.rs@@ -13,64 +13,44 @@ use chardetng::Utf8Detection;/// This implements step 8 of the WHATWG encoding sniffing algorithm:/// https://html.spec.whatwg.org/multipage/parsing.html#determining-the-character-encoding///-/// # Safety-/// - `input` and `input_len` must describe a valid byte slice (or `input` may be null if-/// `input_len` is 0)-/// - `tld` if non-null, must describe a valid byte slice of `tld_len` bytes containing the-/// rightmost DNS label of the resource's host, with no dots, no uppercase, and only ASCII-/// characters — these constraints are required by chardetng and must be validated by the caller-/// - `out_encoding_name` and `out_encoding_name_len` must be non-null writable pointers+/// `tld` is empty, or the rightmost DNS label of the resource's host, with no dots, no uppercase, and only ASCII+/// characters, as chardetng requires and the caller must check.///-/// Returns `true` if an encoding was detected (always, unless the input pointer is invalid).-/// When `true` is returned, `*out_encoding_name` is set to a pointer into a static ASCII-/// string naming the detected encoding (e.g. `"windows-1252"`, `"Shift_JIS"`), and-/// `*out_encoding_name_len` is set to its byte length. The pointer is valid for the lifetime-/// of the process. When `false` is returned (only on null-pointer error), the output pointers-/// are left unmodified.+/// Sets `*out_encoding_name` to a pointer into a static ASCII string naming the detected encoding (e.g.+/// `"windows-1252"`, `"Shift_JIS"`), valid for the lifetime of the process, and `*out_encoding_name_len` to its byte+/// length.#[unsafe(no_mangle)]-pub unsafe extern "C" fn rust_detect_encoding(- input: *const u8,- input_len: usize,- tld: *const u8,- tld_len: usize,+pub extern "C" fn rust_detect_encoding(+ input: ak::Span<'_, u8>,+ tld: ak::Span<'_, u8>,allow_utf8: bool,- out_encoding_name: *mut *const u8,- out_encoding_name_len: *mut usize,-) -> bool {- unsafe {- let Some(input_slice) = crate::bytes_from_raw(input, input_len) else {- return false;- };+ out_encoding_name: &mut *const u8,+ out_encoding_name_len: &mut usize,+) {+ let input_slice = input.as_slice();+ let tld_slice = Some(tld.as_slice()).filter(|tld| !tld.is_empty());- let tld_slice = if tld.is_null() || tld_len == 0 {- None- } else {- Some(ak::slice_from_raw_parts(tld, tld_len))- };+ // Web browsers must use `Iso2022JpDetection::Deny` and `Utf8Detection::Deny` to+ // prevent charset confusion attacks. See the chardetng documentation for details.+ // Japanese pages using ISO-2022-JP will have declared it in a <meta> tag, which+ // is detected in step 5 (prescan) before this step is reached.+ // We always call `guess()` even for pure-ASCII input because chardetng still+ // tracks ESC sequences (ISO-2022-JP uses 7-bit escapes) and returns the+ // correct locale-based fallback (windows-1252 for generic TLD) with+ // `Utf8Detection::Deny` when no distinctive non-ASCII encoding evidence is found.+ let mut detector = EncodingDetector::new(Iso2022JpDetection::Deny);+ // Pass last=false because the caller may only be providing a sniff-bytes prefix+ // of a longer stream. chardetng docs: "If you want to perform detection on just+ // the prefix of a longer stream, do not pass last=true."+ detector.feed(input_slice, false);- // Web browsers must use `Iso2022JpDetection::Deny` and `Utf8Detection::Deny` to- // prevent charset confusion attacks. See the chardetng documentation for details.- // Japanese pages using ISO-2022-JP will have declared it in a <meta> tag, which- // is detected in step 5 (prescan) before this step is reached.- // We always call `guess()` even for pure-ASCII input because chardetng still- // tracks ESC sequences (ISO-2022-JP uses 7-bit escapes) and returns the- // correct locale-based fallback (windows-1252 for generic TLD) with- // `Utf8Detection::Deny` when no distinctive non-ASCII encoding evidence is found.- let mut detector = EncodingDetector::new(Iso2022JpDetection::Deny);- // Pass last=false because the caller may only be providing a sniff-bytes prefix- // of a longer stream. chardetng docs: "If you want to perform detection on just- // the prefix of a longer stream, do not pass last=true."- detector.feed(input_slice, false);-- let utf8_detection = if allow_utf8 {- Utf8Detection::Allow- } else {- Utf8Detection::Deny- };- let encoding = detector.guess(tld_slice, utf8_detection);- let name = encoding.name().as_bytes();- *out_encoding_name = name.as_ptr();- *out_encoding_name_len = name.len();- true- }+ let utf8_detection = if allow_utf8 {+ Utf8Detection::Allow+ } else {+ Utf8Detection::Deny+ };+ let encoding = detector.guess(tld_slice, utf8_detection);+ let name = encoding.name().as_bytes();+ *out_encoding_name = name.as_ptr();+ *out_encoding_name_len = name.len();}