BurntSushi/memchr

Consider hinting to the compiler that indices returned from `memchr()` are within bounds of the haystack

Open

#195 geöffnet am 1. Dez. 2025

Auf GitHub ansehen
 (1 Kommentar) (0 Reaktionen) (0 zugewiesene Personen)Rust (146 Forks)github user discovery
enhancementhelp wanted

Repository-Metriken

Stars
 (1.457 Stars)
PR-Merge-Metriken
 (Durchschn. Merge 18m) (2 gemergte PRs in 30 T)

Beschreibung

Currently, indexing into the haystack with the index returned by memchr usually generates a bounds check, because the compiler doesn't know that it's valid. However, if an assert_unchecked(i < haystack.len()) is inserted, the compiler has enough information to elide the check (godbolt).

Pros:

  • Reduces bounds-checking in downstream code; this doesn't remove a ton of overhead but could possibly allow for further optimizations that had been inhibited by the branch.

Cons:

  • assert_unchecked() is only available since Rust 1.81, so would either have to feature-gate this, do rust version detection, or (most likely) use if !cond { unreachable_unchecked(); } to polyfill it. The last option should be equivalent to assert_unchecked(), but I'm not sure if it's treated exactly the same by the compiler.
  • Returning an out-of-bound index becomes UB rather than just a logic error. I assume there was already downstream code relying on this, though, and also it'd probably already be UB internally.

Contributor Guide