Skip to content

unsafe-deep-dive: replace may_overflow with a real safety precondition - #3244

Open
rmyndharis wants to merge 1 commit into
google:mainfrom
rmyndharis:fix/may-overflow-not-ub
Open

unsafe-deep-dive: replace may_overflow with a real safety precondition#3244
rmyndharis wants to merge 1 commit into
google:mainfrom
rmyndharis:fix/may-overflow-not-ub

Conversation

@rmyndharis

Copy link
Copy Markdown

The "Example: may_overflow" slide taught that signed integer overflow is
undefined behavior in release mode and that the function therefore needs
the unsafe keyword. Both claims are false: integer overflow is well
defined in Rust (debug builds panic, release builds wrap), and
a + i32::MAX does not require unsafe at all.

Replace the example with an unsafe fn element_at built on
slice::get_unchecked, which has a genuine safety precondition: the
caller must keep the index in bounds. This preserves the slide's purpose
(a concrete example of responsibility shifting to the programmer) and
leads directly into the "Safety Preconditions" segment. The speaker notes
state plainly that integer overflow is defined behavior and never requires
unsafe.

Closes #3122.

The "Example: may_overflow" slide taught that signed integer overflow is
undefined behavior in release mode and that the function therefore needs
the `unsafe` keyword. Both claims are false: integer overflow is well
defined in Rust (debug builds panic, release builds wrap), and
`a + i32::MAX` does not require `unsafe` at all.

Replace the example with an `unsafe fn element_at` built on
`slice::get_unchecked`, which has a genuine safety precondition: the
caller must keep the index in bounds. This preserves the slide's purpose
(a concrete example of responsibility shifting to the programmer) and
leads directly into the "Safety Preconditions" segment. The speaker notes
state plainly that integer overflow is defined behavior and never requires
`unsafe`.

Closes google#3122.
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.

Unsafe Rust: Integer overflow is not UB

1 participant