Skip to content

Commit

Permalink
Rollup merge of #124701 - scottmcm:unchecked_sub_docs, r=Nilstrieb
Browse files Browse the repository at this point in the history
Docs: suggest `uN::checked_sub` instead of check-then-unchecked

As of #124114 it's exactly the same in codegen, so might as well not use `unsafe`.

Note that this is only for *unsigned*, since the overflow conditions for `iN::checked_sub` are more complicated.
  • Loading branch information
matthiaskrgr authored May 4, 2024
2 parents 7705671 + e1c833e commit 5f4f4fb
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions library/core/src/num/uint_macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -636,6 +636,31 @@ macro_rules! uint_impl {
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_sub`].
///
/// If you find yourself writing code like this:
///
/// ```
/// # let foo = 30_u32;
/// # let bar = 20;
/// if foo >= bar {
/// // SAFETY: just checked it will not overflow
/// let diff = unsafe { foo.unchecked_sub(bar) };
/// // ... use diff ...
/// }
/// ```
///
/// Consider changing it to
///
/// ```
/// # let foo = 30_u32;
/// # let bar = 20;
/// if let Some(diff) = foo.checked_sub(bar) {
/// // ... use diff ...
/// }
/// ```
///
/// As that does exactly the same thing -- including telling the optimizer
/// that the subtraction cannot overflow -- but avoids needing `unsafe`.
///
/// # Safety
///
/// This results in undefined behavior when
Expand Down

0 comments on commit 5f4f4fb

Please sign in to comment.