Skip to content

rand: inform the optimiser that indexing is never out-of-bounds. #16965

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

Merged
merged 1 commit into from
Sep 9, 2014
Merged
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
20 changes: 18 additions & 2 deletions src/librand/isaac.rs
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,19 @@ impl Rng for IsaacRng {
self.isaac();
}
self.cnt -= 1;
self.rsl[self.cnt as uint]

// self.cnt is at most RAND_SIZE, but that is before the
// subtraction above. We want to index without bounds
// checking, but this could lead to incorrect code if someone
// misrefactors, so we check, sometimes.
//
// (Changes here should be reflected in Isaac64Rng.next_u64.)
debug_assert!(self.cnt < RAND_SIZE);

// (the % is cheaply telling the optimiser that we're always
// in bounds, without unsafe. NB. this is a power of two, so
// it optimises to a bitwise mask).
self.rsl[(self.cnt % RAND_SIZE) as uint]
}
}

Expand Down Expand Up @@ -416,7 +428,11 @@ impl Rng for Isaac64Rng {
self.isaac64();
}
self.cnt -= 1;
unsafe { *self.rsl.unsafe_get(self.cnt) }

// See corresponding location in IsaacRng.next_u32 for
// explanation.
debug_assert!(self.cnt < RAND_SIZE_64)
self.rsl[(self.cnt % RAND_SIZE_64) as uint]
}
}

Expand Down