Skip to content

Commit c2f3b8b

Browse files
committed
Add safety preconditions to core/src/iter/range.rs
For the signed and unsigned methods in the macros, I added contracts that require the checked operations to succeed, which is what the safety comments are stating. These contracts formalize the safety requirements that were previously only documented in comments.
1 parent 3b80a4c commit c2f3b8b

File tree

1 file changed

+7
-0
lines changed

1 file changed

+7
-0
lines changed

library/core/src/iter/range.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@ use crate::mem;
66
use crate::net::{Ipv4Addr, Ipv6Addr};
77
use crate::num::NonZero;
88
use crate::ops::{self, Try};
9+
#[cfg(kani)]
10+
use crate::kani;
11+
use safety::requires;
912

1013
// Safety: All invariants are upheld.
1114
macro_rules! unsafe_impl_trusted_step {
@@ -183,12 +186,14 @@ pub trait Step: Clone + PartialOrd + Sized {
183186
// than the signed::MAX value. Therefore `as` casting to the signed type would be incorrect.
184187
macro_rules! step_signed_methods {
185188
($unsigned: ty) => {
189+
#[requires(start.checked_add_unsigned(n as $unsigned).is_some())]
186190
#[inline]
187191
unsafe fn forward_unchecked(start: Self, n: usize) -> Self {
188192
// SAFETY: the caller has to guarantee that `start + n` doesn't overflow.
189193
unsafe { start.checked_add_unsigned(n as $unsigned).unwrap_unchecked() }
190194
}
191195

196+
#[requires(start.checked_sub_unsigned(n as $unsigned).is_some())]
192197
#[inline]
193198
unsafe fn backward_unchecked(start: Self, n: usize) -> Self {
194199
// SAFETY: the caller has to guarantee that `start - n` doesn't overflow.
@@ -199,12 +204,14 @@ macro_rules! step_signed_methods {
199204

200205
macro_rules! step_unsigned_methods {
201206
() => {
207+
#[requires(start.checked_add(n as Self).is_some())]
202208
#[inline]
203209
unsafe fn forward_unchecked(start: Self, n: usize) -> Self {
204210
// SAFETY: the caller has to guarantee that `start + n` doesn't overflow.
205211
unsafe { start.unchecked_add(n as Self) }
206212
}
207213

214+
#[requires(start.checked_sub(n as Self).is_some())]
208215
#[inline]
209216
unsafe fn backward_unchecked(start: Self, n: usize) -> Self {
210217
// SAFETY: the caller has to guarantee that `start - n` doesn't overflow.

0 commit comments

Comments
 (0)