diff options
| author | Matthias Krüger <matthias.krueger@famsik.de> | 2024-05-04 12:37:24 +0200 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2024-05-04 12:37:24 +0200 |
| commit | 5f4f4fbb989b3f966b4fc1fd7bd3d5089c458cd2 (patch) | |
| tree | 680548d5172900e069bd0e4eb807a76f2cb4b9c6 | |
| parent | 770567101cf2f67416b09818b89afb22aa5eaa8f (diff) | |
| parent | e1c833eb076efc5aef95d5c8ec9a410d8738def4 (diff) | |
| download | rust-5f4f4fbb989b3f966b4fc1fd7bd3d5089c458cd2.tar.gz rust-5f4f4fbb989b3f966b4fc1fd7bd3d5089c458cd2.zip | |
Rollup merge of #124701 - scottmcm:unchecked_sub_docs, r=Nilstrieb
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.
| -rw-r--r-- | library/core/src/num/uint_macros.rs | 25 |
1 files changed, 25 insertions, 0 deletions
diff --git a/library/core/src/num/uint_macros.rs b/library/core/src/num/uint_macros.rs index 6682f875eb8..673144cb328 100644 --- a/library/core/src/num/uint_macros.rs +++ b/library/core/src/num/uint_macros.rs @@ -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 |
