Skip to content

u32/NonMaxU32 instead of usize in Utf8CodeUnits and friends #47696

Closed

Description

@SimonSapin

In servo_base::text we define wrapper structs like Utf8CodeUnits, Utf16CodeUnits, and Utf32CodeUnits to represent an offset in a string or its length, to help avoid bugs where one is accidentally used instead of the other. (Rust &str uses UTF-8, many DOM APIs use UTF-16 offsets, and much of our font/glyph code uses UTF-32 offsets; even if strings are not necessarily materialized in memory as UTF-16 / UTF-32)

Currently they wrap a usize but (on 64-bit platform) they could be made smaller by wrapping u32 instead. This would reduce memory usage of the box tree and fragment tree. The main question in my opinion is: how to deal with overflow when converting from usize? It’s possible that trying to have 4+ GiB in a single text node already runs into other limitations, but it’d be nice not to add a new panic. (JS engines have a practical limit on the length of JS strings but the HTML parser can be fed more at least from the network. At least some parts of DOM code already use u32 offsets though.)

Going further, we could use NonMaxU32 to make Option<Utf*CodeUnits> smaller, and therefore RangeAny<Utf*CodeUnits>. Generic pattern types are not stable in the language yet, so this crate relies on NonZeroU32 instead. It has a small CPU cost (unconditional/branchless XOR with u32::MAX) when wrapping or unwrapping the u32 value. (Alternatively, if overflow remains a problem, use NonMaxUsize. The Option optimization is independent from the bit width.)

Activity

  1. added
    I-perf-bloat
    A-layout/2020
    C-untriaged
    on Aug 31, 2026
  2. jschwe commented on Sep 1, 2026

    @jschwe
    Member

    how to deal with overflow when converting from usize

    Where does the overflow come from? If we cap max string size, shouldn't that be solved?

  3. SimonSapin commented on Sep 1, 2026

    @SimonSapin
    MemberAuthor

    Sure but what to do if the cap is exceeded? Are we confident all code paths handle it properly without Rust panics? For DOM APIs this may be raising a JS exception, but what about parsing HTML from the network? This is all solvable but affects more than just servo_base::text

  4. SimonSapin commented on Sep 1, 2026

    @SimonSapin
    MemberAuthor

    Unfinished attempt: PR #47714

  5. SimonSapin commented on Sep 1, 2026

    @SimonSapin
    MemberAuthor

    Alternative idea: if Utf*CodeUnits doesn’t have a niche for enum optimization (maybe that’s too much of a pain to deal with), RangeAny { start: Option<T>, end: Option<T> } needs to store two separate enum tags, each padded to the align_of::<T>() bytes. Instead, we could have a single enum to store a single tag:

    enum RangeAnyInner<T> {
        Range { start: T, end: T },
        RangeFrom { start: T },
        RangeTo { end: T },
        RangeFull
    }

    There would be convenience methods fn start(self) -> Option<T> and fn end(self) -> Option<T>. But I’m unsure if those should be the only access to data, with the 4-variant enum being private, or if that enum should be the public type.

  6. removed
    C-untriaged
    on Sep 3, 2026
  7. SimonSapin commented on Sep 3, 2026

    @SimonSapin
    MemberAuthor

    Trying to generate a giant DOM text node with a Python HTTP server:

    from wsgiref.simple_server import make_server
    
    def app(environ, start_fn):
        start_fn('200 OK', [('Content-Type', 'text/html')])
        yield b"<pre>\n"
        kilo = b"01234567890" * 100
        for i in range(4_300_000):
            yield f"{i}: {kilo}\n".encode("ascii")
    
    with make_server('', 8000, app) as server:
        print("http://localhost:8000")
        server.handle_request()

    This emits more than 4 300 000 000 bytes, which is slightly more than 2³² a.k.a u32::MAX. In the Network tab of Firefox devtools, the Size columns grows for a couple seconds until something like 2.66 GB or 3.57 GB (it varies every time). The Transferred column shows NS_ERROR_OUT_OF_MEMORY. The number of lines actually rendered also varies, could be ~20k or ~300k but nowhere near the total 4 million.

    Chromium seemingly kept loading for several minutes, with one process settling at around 6 GB memory usage. I got bored and stopped it after 6 minutes. Scrolling down then showed like ~179k.

    Servo in compiled in release mode with this PR showed the initial screenful of lines while not responsive to scrolling, kept using 100% of one CPU core while consuming ~10 GB memory. After several minutes it jumped to 32 GB and I killed it.

  8. SimonSapin commented on Sep 3, 2026

    @SimonSapin
    MemberAuthor

    I don’t know if other engines have a very different memory representation for the text value of <textarea> elements v.s. that of DOM text nodes the way Servo does, but the observable behavior is about the same:

    from wsgiref.simple_server import make_server
    
    def app(environ, start_fn):
        start_fn('200 OK', [('Content-Type', 'text/html')])
        yield b"<textarea cols=150 rows=50>\n"
        kilo = b"01234567890" * 100
        for i in range(4_300_000):
            yield f"{i}: {kilo}\n".encode("ascii")
        yield b"</textarea>\n"
    
    with make_server('', 8000, app) as server:
        print("http://localhost:8000")
        #server.handle_request()
        server.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-layout/2020I-perf-bloat

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions