Repository navigation
shared: Compact Utf8CodeUnits and friends - #47742
Conversation
|
🔨 Triggering try run (#33628165698) for Linux (WPT) |
|
✨ Try run (#33628165698) succeeded. |
0f1b65c to
dc56a27
Compare
|
Testing in #47696 (comment) suggests that it’s quite hard to reach anywhere near |
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]>
dc56a27 to
1177f85
Compare
| /// 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); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
| // 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>, |
There was a problem hiding this comment.
Have you measured if this has any impact?
There was a problem hiding this comment.
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
| ) -> 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] |
There was a problem hiding this comment.
str() already produces a UTF-8 string so it makes sense to just call len() on that string, I think.
There was a problem hiding this comment.
Oh i didn’t realize it’s the same command_value used in two places. Better yet, I’ll use str::strip_suffix
|
|
||
| // 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); |
There was a problem hiding this comment.
Could this narrowing produce negative numbers?
There was a problem hiding this comment.
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]>
726e2db to
c4b5236
Compare
|
…rameter Signed-off-by: Simon Sapin <[email protected]>
c4b5236 to
90bdfbc
Compare
- 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]>
| /// 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 |
There was a problem hiding this comment.
Maybe I'm misreading this, but the offset is a u32 here so it can never be over u32::MAX right?
There was a problem hiding this comment.
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
The AssumeUnder4GB parameter serves that purpose now Signed-off-by: Simon Sapin <[email protected]>
Signed-off-by: Simon Sapin <[email protected]>
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]>
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]>
Fixes #47696, attempt number 2
Closes #47714, the previous attempt
Testing: existing WPT and unit tests
In that previous attempt I used
NonMaxU32in order to optimize the size ofOption<Utf8CodeUnits>. This madeu32::MAXmemory-unsafe to use, so as a precaution I made every operation checked, returningResults. Unsurprisingly, this was a huge pain to deal with. I gave up before getting thescriptcrate to compile.Smaller
RangeAnyInstead of the
Optionsize optimization, per #47696 (comment) I’ve changedRangeAnyfrom 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). SoRangeAny<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)u32overflowIn this PR I’ve still reduced the width of
Utf*CodeUnitsfromusizetou32but left the fullu32range available.impl Add for Utf8CodeUnitsis still there (not replaced withchecked_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::MAXwould be a bug (though not memory-unsafe). To help surface this issue to callers, I’ve changed some APIs from taking&strarguments to taking a newstruct Str32(&str)marker type that says: “this string is expected to not be bigger than 4 GiB (u32::MAXbytes)”In practice the strings come from a few places:
DOMStringin many places in the script crate: multi-representation, UTF-8 or Latin-1Ropefor the text value of<input>or<textarea>elements: UTF-8Vec<String>(currently does not cache its total length)CharacterDataDOM nodes: UTF-8StringCharacterData) nodes, but forInlineFormattingContextalso computes offsets spanning multiple DOM nodesMaybe 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
u32is 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*CodeUnitsis used in more places instead ofusize, 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),Utf16CodeUnitsmethods used to arbitrarily snap to the code point boundary after the whole pair. When using this method to implement themaxlengthHTML attribute of<input>or<textarea>however, the snap must be to before the surrogate pair. So I’ve changed the behavior of theUtf16CodeUnitsmethods, which also affects the result of changing the selection range through DOM APIs.