Skip to content

Add safety preconditions to core/src/iter/range.rs #331

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions library/core/src/iter/range.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
use safety::requires;

use super::{
FusedIterator, TrustedLen, TrustedRandomAccess, TrustedRandomAccessNoCoerce, TrustedStep,
};
use crate::ascii::Char as AsciiChar;
#[cfg(kani)]
use crate::kani;
use crate::mem;
use crate::net::{Ipv4Addr, Ipv6Addr};
use crate::num::NonZero;
Expand Down Expand Up @@ -183,12 +187,14 @@ pub trait Step: Clone + PartialOrd + Sized {
// than the signed::MAX value. Therefore `as` casting to the signed type would be incorrect.
macro_rules! step_signed_methods {
($unsigned: ty) => {
#[requires(start.checked_add_unsigned(n as $unsigned).is_some())]
#[inline]
unsafe fn forward_unchecked(start: Self, n: usize) -> Self {
// SAFETY: the caller has to guarantee that `start + n` doesn't overflow.
unsafe { start.checked_add_unsigned(n as $unsigned).unwrap_unchecked() }
}

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

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

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