Skip to content

std::hint::unreachable_unchecked: docs note about compiler optimizations being sufficient? #95865

Closed
@sharnoff

Description

@sharnoff
Contributor

I don't know whether this is something that the docs team already has a particular policy on, so perhaps this is out of scope, but:

The docs for std::hint::unreachable_unchecked give an example that -- with optimizations -- compiles to the same assembly using plain unwrap instead of unwrap_or_else(|| unsafe { unreachable_unchecked }). (See: https://godbolt.org/z/4ha9K1rGK)

Given that this is likely often the case for simple inputs (particularly for arithemtic operations like the example), I was wondering if it would be good to have some kind of note in the documentation to advising that this function should only be used if it's actually necessary. In particular, this could note that rustc with -C opt-level=1 will produce the same assembly for the example as a version that uses unwrap instead.

Of course several caveats apply (it's not ideal to rely on compiler optimizations in docs, etc) - but IMO it could be worthwhile for the purpose of discouraging unecessary unsafe.

Activity

leonardo-m

leonardo-m commented on Apr 10, 2022

@leonardo-m

Also the example could be replaced with a better one where unreachable_unchecked gives an advantage.

added 2 commits that reference this issue on May 13, 2022
3615cb4

Rollup merge of rust-lang#96154 - lukaslueg:unreachablehint, r=scottmcm

feb18d1
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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      Participants

      @leonardo-m@sharnoff

      Issue actions

        `std::hint::unreachable_unchecked`: docs note about compiler optimizations being sufficient? · Issue #95865 · rust-lang/rust