Skip to content

[WIP] shared: Compact Utf8CodeUnits and friends - #47714

Closed
SimonSapin wants to merge 4 commits into
servo:mainfrom
SimonSapin:compact-code-units
Closed

SimonSapin wants to merge 4 commits into
servo:mainfrom
SimonSapin:compact-code-units

Conversation

@SimonSapin

Copy link
Copy Markdown
Member

Fixes #47696

@SimonSapin

Copy link
Copy Markdown
Member Author

This is an attempt at changing the memory representation of Utf8CodeUnits, Utf16CodeUnits, and Utf32CodeUnits from usize to NonMaxU32 as suggested in #47696

This saves memory use in the box and fragment tree, but reduces the range of values that can be represented. Not only conversion from usize but also conversion from u32 can fail. For this draft, I’ve opted to make fallibility apparent in the API of these types: many methods return a Result, impl Add has been replaced by checked_add, etc.

Unfortunately this is a nightmare to deal with in the script crate. I’ve gave up for now on making it compile, even though I had started by sprinkling some result.expect("overflow") that would need to be replaced by something else (such as raising a JS exception) before merge.

Maybe the all-fallible API approach needs revision, but having invisible potential Rust panic or value truncation doesn’t seem good either.

@Narfinger

Copy link
Copy Markdown
Contributor

I feel like the question is: What is the supposed caller do with the error information? If we get an overflow on real websites, don't we have to just increase the value?
So I feel like a clean panic might just be better.

jdm pushed a commit to jdm/servo that referenced this pull request Sep 14, 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]>
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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

u32/NonMaxU32 instead of usize in Utf8CodeUnits and friends

2 participants