Skip to content

shared: Compact Utf8CodeUnits and friends - #47742

Merged
SimonSapin merged 10 commits into
mainfrom
compact-code-units2
Sep 14, 2026
Merged

SimonSapin merged 10 commits into
mainfrom
compact-code-units2

Conversation

@SimonSapin

@SimonSapin SimonSapin commented Sep 2, 2026 •

Copy link
Copy Markdown
Member

Fixes #47696, attempt number 2
Closes #47714, the previous attempt
Testing: existing WPT and unit tests

In that previous attempt I used NonMaxU32 in order to optimize the size of Option<Utf8CodeUnits>. This made u32::MAX memory-unsafe to use, so as a precaution I made every operation checked, returning Results. Unsurprisingly, this was a huge pain to deal with. I gave up before getting the script crate to compile.

Smaller RangeAny

Instead of the Option size optimization, per #47696 (comment) I’ve changed RangeAny from storing two options (each with a 64-bit or 32-bit tag because of alignment) to a single 4-variant enum (with a single tag). So RangeAny<u32> occupies 12 bytes instead of 16. This change is internal, the public API is still based on two options (though no longer bare public fields)

u32 overflow

In this PR I’ve still reduced the width of Utf*CodeUnits from usize to u32 but left the full u32 range available. impl Add for Utf8CodeUnits is still there (not replaced with checked_add) and still defers to plain integer addition: checked with panic on overflow when compiled in debug mode, or wrapping in release mode.

In either compilation mode, trying to deal with offsets greater than u32::MAX would be a bug (though not memory-unsafe). To help surface this issue to callers, I’ve changed some APIs from taking &str arguments to taking a new struct Str32(&str) marker type that says: “this string is expected to not be bigger than 4 GiB (u32::MAX bytes)”

In practice the strings come from a few places:

  • DOMString in many places in the script crate: multi-representation, UTF-8 or Latin-1
  • Rope for the text value of <input> or <textarea> elements: UTF-8 Vec<String> (currently does not cache its total length)
  • Text value of CharacterData DOM nodes: UTF-8 String
  • Rendered text in layout: mostly from DOM text (CharacterData) nodes, but for InlineFormattingContext also computes offsets spanning multiple DOM nodes

Maybe we could systematically enforce limits on their sizes (with e.g. JS exceptions instead of Rust panics or silently incorrect behavior), but I haven’t done so in this PR. The script crate was already using u32 is some places, so I suspect there were already bugs and/or limitations with very large strings including a limitation from SpiderMonkey.

Splitting surrogate pairs

As a drive-by improvement, Utf*CodeUnits is used in more places instead of usize, and their methods instead of ad-hoc offset or length computations. The latter points out a subtle aspect of converting a UTF-16 offset to UTF-8 or UTF-32: if the UTF-16 offset would split a surrogate pair (for a non-BMP code point), Utf16CodeUnits methods used to arbitrarily snap to the code point boundary after the whole pair. When using this method to implement the maxlength HTML attribute of <input> or <textarea> however, the snap must be to before the surrogate pair. So I’ve changed the behavior of the Utf16CodeUnits methods, which also affects the result of changing the selection range through DOM APIs.

@SimonSapin SimonSapin added the T-linux-wpt Do a try run of the WPT label Sep 2, 2026
@github-actions github-actions Bot removed the T-linux-wpt Do a try run of the WPT label Sep 2, 2026
@github-actions

github-actions Bot commented Sep 2, 2026

Copy link
Copy Markdown

🔨 Triggering try run (#33628165698) for Linux (WPT)

@github-actions

github-actions Bot commented Sep 2, 2026

Copy link
Copy Markdown

✨ Try run (#33628165698) succeeded.

@SimonSapin
SimonSapin force-pushed the compact-code-units2 branch 2 times, most recently from 0f1b65c to dc56a27 Compare September 3, 2026 11:39
@SimonSapin

Copy link
Copy Markdown
Member Author

Testing in #47696 (comment) suggests that it’s quite hard to reach anywhere near u32::MAX, so maybe this PR as-is is fine

Signed-off-by: Simon Sapin <[email protected]>
Signed-off-by: Simon Sapin <[email protected]>
Drive-by: use `Utf*CodeUnits` in more places

Signed-off-by: Simon Sapin <[email protected]>
Signed-off-by: Simon Sapin <[email protected]>
…-8 or UTF-32 offset before instead of after the whole pair

This is needed for the `maxlength` HTML attribute

Signed-off-by: Simon Sapin <[email protected]>
@SimonSapin
SimonSapin marked this pull request as ready for review September 3, 2026 13:47
@servo-highfive servo-highfive added S-awaiting-review There is new code that needs to be reviewed. S-needs-rebase There are merge conflict errors. labels Sep 3, 2026
Comment thread components/shared/base/text.rs Outdated
Comment on lines +220 to +225
/// A wrapper for `&str` whose length is not greater than 4 GiB, `u32::MAX` bytes
///
/// Using `Str32` with a string too long is not memory unsafe, but other APIs
/// like `Utf8CodeUnits::length_of` may silently return an incorrect (wrapped) value.
#[derive(Clone, Copy)]
pub struct Str32<'a>(pub &'a str);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is probably the most controversial part of this change for me. In order to move this one along, can we just drop the Str32 changes from this change. I don't this does any assertion about size, so it's purely documentation.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think having some kind of "speed bump" to make callers pay attention is still important, so I’ve replace this with a zero-size marker type that is not passed as an additional parameter. The string parameters are back to plain &str

Comment thread components/shared/base/text.rs Resolved
Comment thread components/shared/base/text.rs Resolved
Comment thread components/shared/base/text.rs Outdated
Comment on lines +68 to +71
// Nudges rustc towards placing `end` at the same offset as in the `Range` variant,
// for slightly better codegen in the `fn end()` getter
#[ignore_malloc_size_of = "always uninitialized"]
_layout_hint: MaybeUninit<T>,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Have you measured if this has any impact?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I checked that Gobolt shows fewer branches and instructions: https://rust.godbolt.org/z/TWTd5e66Y but not measured the timing. It’s probably tiny, if not below noise level

Comment thread components/shared/base/text.rs Resolved
) -> Option<DOMString> {
if command_value.ends_with_str("px") {
command_value.str()[0..command_value.len() - 2]
command_value.str()[..usize::from(command_value.len_utf8()) - 2]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

str() already produces a UTF-8 string so it makes sense to just call len() on that string, I think.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh i didn’t realize it’s the same command_value used in two places. Better yet, I’ll use str::strip_suffix

Comment thread components/shared/base/text.rs Resolved
Comment thread components/layout/flow/inline/mod.rs Resolved
Comment thread components/shared/base/text.rs Resolved

// Sub-step 2: Let delta be new length minus old length.
let delta = (new_length.0 as isize) - (old_length.0 as isize);
let delta = (new_length.0 as i32) - (old_length.0 as i32);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could this narrowing produce negative numbers?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR also changed new_length.0 and old_length.0 from usize to u32, so there is no more integer truncation here than before.

Still, I realize now we can avoid signed integers entirely by "inlining" delta so I’ll do that

Signed-off-by: Simon Sapin <[email protected]>
@servo-highfive servo-highfive removed the S-needs-rebase There are merge conflict errors. label Sep 9, 2026
@codecov-commenter

Copy link
Copy Markdown

⚠️ JUnit XML file not found

The CLI was unable to find any JUnit XML files to upload.
For more help, visit our troubleshooting guide.

 - Removed a now-unused `cfg-if` inclusion in `Cargo.toml`
 - Remove _layout_hint from `RangeInner`. Perhaps this kind of
   micro-optimization should be profile-driven? It adds quite a bit of
   code.
 - Added `RangeAny::from_start_to` constructor
   to make a simpler to create single-ended ranges
 - Added a `to_usize_range` helper to the code unit types
 - Simplified `DOMString::len_utf16`
 - Remove `EncodedBytes::len` as it is unused now and incorrect
 - Fixed a couple typos

Signed-off-by: Martin Robinson <[email protected]>
Comment thread components/script_bindings/domstring.rs Resolved
Comment thread components/shared/base/text.rs Resolved
Comment thread components/shared/base/text.rs Resolved
Comment thread components/shared/base/text.rs Resolved
Comment thread components/shared/base/text.rs Outdated
/// Convert this UTF-32 (`char`) offset in `string` to an UTF-16 offset
///
/// Note: this silently wraps and returns an incorrect value for offsets larger than
/// `u32::MAX` (~4 billion) code units

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe I'm misreading this, but the offset is a u32 here so it can never be over u32::MAX right?

@SimonSapin SimonSapin Sep 11, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In a string with non-BMP code points that would get encoded as surrogate pairs, a UTF-16 offset can be larger than the corresponding UTF-32 code offset so it’s theoretically possible for Utf32CodeUnits::to_utf16_code_units_in to overflow even with a u32 input

@servo-highfive servo-highfive removed the S-awaiting-review There is new code that needs to be reviewed. label Sep 11, 2026
The AssumeUnder4GB parameter serves that purpose now

Signed-off-by: Simon Sapin <[email protected]>
@servo-highfive servo-highfive added the S-awaiting-review There is new code that needs to be reviewed. label Sep 11, 2026
@SimonSapin
SimonSapin added this pull request to the merge queue Sep 11, 2026
@servo-highfive servo-highfive added the S-awaiting-merge The PR is in the process of compiling and running tests on the automated CI. label Sep 11, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to a conflict with the base branch Sep 11, 2026
@servo-highfive servo-highfive added S-needs-rebase There are merge conflict errors. and removed S-awaiting-merge The PR is in the process of compiling and running tests on the automated CI. labels Sep 11, 2026
@servo-highfive servo-highfive removed the S-needs-rebase There are merge conflict errors. label Sep 14, 2026
@SimonSapin
SimonSapin added this pull request to the merge queue Sep 14, 2026
@servo-highfive servo-highfive added the S-awaiting-merge The PR is in the process of compiling and running tests on the automated CI. label Sep 14, 2026
Merged via the queue into main with commit a47d365 Sep 14, 2026
33 of 34 checks passed
@SimonSapin
SimonSapin deleted the compact-code-units2 branch September 14, 2026 08:19
@servo-highfive servo-highfive removed the S-awaiting-merge The PR is in the process of compiling and running tests on the automated CI. label Sep 14, 2026
RichardTjokroutomo pushed a commit to RichardTjokroutomo/servo that referenced this pull request Oct 6, 2026
Fixes servo#47696, attempt number 2
Closes servo#47714, the previous attempt
Testing: existing WPT and unit tests

In that previous attempt I used `NonMaxU32` in order to optimize the
size of `Option<Utf8CodeUnits>`. This made `u32::MAX` memory-unsafe to
use, so as a precaution I made every operation checked, returning
`Result`s. Unsurprisingly, this was a huge pain to deal with. I gave up
before getting the `script` crate to compile.

## Smaller `RangeAny`

Instead of the `Option` size optimization, per
servo#47696 (comment) I’ve
changed `RangeAny` from storing two options (each with a 64-bit or
32-bit tag because of alignment) to a single 4-variant enum (with a
single tag). So `RangeAny<u32>` occupies 12 bytes instead of 16. This
change is internal, the public API is still based on two options (though
no longer bare public fields)

## `u32` overflow

In this PR I’ve still reduced the width of `Utf*CodeUnits` from
`usize` to `u32` but left the full `u32` range available. `impl Add for
Utf8CodeUnits` is still there (not replaced with `checked_add`) and
still defers to plain integer addition: checked with panic on overflow
when compiled in debug mode, or wrapping in release mode.

In either compilation mode, trying to deal with offsets greater than
`u32::MAX` would be a bug (though not memory-unsafe). To help surface
this issue to callers, I’ve changed some APIs from taking `&str`
arguments to taking a new `struct Str32(&str)` marker type that says:
“this string is expected to not be bigger than 4 GiB (`u32::MAX` bytes)”

In practice the strings come from a few places:

* `DOMString` in many places in the script crate: multi-representation,
UTF-8 or Latin-1
* `Rope` for the text value of `<input>` or `<textarea>` elements: UTF-8
`Vec<String>` (currently does not cache its total length)
* Text value of `CharacterData` DOM nodes: UTF-8  `String`
* Rendered text in layout: mostly from DOM text (`CharacterData`) nodes,
but for `InlineFormattingContext` also computes offsets spanning
multiple DOM nodes

Maybe we could systematically enforce limits on their sizes (with e.g.
JS exceptions instead of Rust panics or silently incorrect behavior),
but I haven’t done so in this PR. The script crate was already using
`u32` is some places, so I suspect there were already bugs and/or
limitations with very large strings including [a limitation from
SpiderMonkey](https://stackoverflow.com/a/65570725).

## Splitting surrogate pairs

As a drive-by improvement, `Utf*CodeUnits` is used in more places
instead of `usize`, and their methods instead of ad-hoc offset or length
computations. The latter points out a subtle aspect of converting a
UTF-16 offset to UTF-8 or UTF-32: if the UTF-16 offset would split a
surrogate pair (for a non-BMP code point), `Utf16CodeUnits` methods used
to arbitrarily snap to the code point boundary *after* the whole pair.
When using this method to implement the `maxlength` HTML attribute of
`<input>` or `<textarea>` however, the snap must be to *before* the
surrogate pair. So I’ve changed the behavior of the `Utf16CodeUnits`
methods, which also affects the result of changing the selection range
through DOM APIs.

---------

Signed-off-by: Simon Sapin <[email protected]>
Signed-off-by: Martin Robinson <[email protected]>
Co-authored-by: Martin Robinson <[email protected]>
hhhwsqhhh pushed a commit to hhhwsqhhh/servo that referenced this pull request Oct 12, 2026
Fixes servo#47696, attempt number 2
Closes servo#47714, the previous attempt
Testing: existing WPT and unit tests

In that previous attempt I used `NonMaxU32` in order to optimize the
size of `Option<Utf8CodeUnits>`. This made `u32::MAX` memory-unsafe to
use, so as a precaution I made every operation checked, returning
`Result`s. Unsurprisingly, this was a huge pain to deal with. I gave up
before getting the `script` crate to compile.

## Smaller `RangeAny`

Instead of the `Option` size optimization, per
servo#47696 (comment) I’ve
changed `RangeAny` from storing two options (each with a 64-bit or
32-bit tag because of alignment) to a single 4-variant enum (with a
single tag). So `RangeAny<u32>` occupies 12 bytes instead of 16. This
change is internal, the public API is still based on two options (though
no longer bare public fields)

## `u32` overflow

In this PR I’ve still reduced the width of `Utf*CodeUnits` from
`usize` to `u32` but left the full `u32` range available. `impl Add for
Utf8CodeUnits` is still there (not replaced with `checked_add`) and
still defers to plain integer addition: checked with panic on overflow
when compiled in debug mode, or wrapping in release mode.

In either compilation mode, trying to deal with offsets greater than
`u32::MAX` would be a bug (though not memory-unsafe). To help surface
this issue to callers, I’ve changed some APIs from taking `&str`
arguments to taking a new `struct Str32(&str)` marker type that says:
“this string is expected to not be bigger than 4 GiB (`u32::MAX` bytes)”

In practice the strings come from a few places:

* `DOMString` in many places in the script crate: multi-representation,
UTF-8 or Latin-1
* `Rope` for the text value of `<input>` or `<textarea>` elements: UTF-8
`Vec<String>` (currently does not cache its total length)
* Text value of `CharacterData` DOM nodes: UTF-8  `String`
* Rendered text in layout: mostly from DOM text (`CharacterData`) nodes,
but for `InlineFormattingContext` also computes offsets spanning
multiple DOM nodes

Maybe we could systematically enforce limits on their sizes (with e.g.
JS exceptions instead of Rust panics or silently incorrect behavior),
but I haven’t done so in this PR. The script crate was already using
`u32` is some places, so I suspect there were already bugs and/or
limitations with very large strings including [a limitation from
SpiderMonkey](https://stackoverflow.com/a/65570725).

## Splitting surrogate pairs

As a drive-by improvement, `Utf*CodeUnits` is used in more places
instead of `usize`, and their methods instead of ad-hoc offset or length
computations. The latter points out a subtle aspect of converting a
UTF-16 offset to UTF-8 or UTF-32: if the UTF-16 offset would split a
surrogate pair (for a non-BMP code point), `Utf16CodeUnits` methods used
to arbitrarily snap to the code point boundary *after* the whole pair.
When using this method to implement the `maxlength` HTML attribute of
`<input>` or `<textarea>` however, the snap must be to *before* the
surrogate pair. So I’ve changed the behavior of the `Utf16CodeUnits`
methods, which also affects the result of changing the selection range
through DOM APIs.

---------

Signed-off-by: Simon Sapin <[email protected]>
Signed-off-by: Martin Robinson <[email protected]>
Co-authored-by: Martin Robinson <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

S-awaiting-review There is new code that needs to be reviewed.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

u32/NonMaxU32 instead of usize in Utf8CodeUnits and friends

4 participants