Skip to content

Commit 6fc4e9f

Browse files
authored
Undo typed stride as that introduces a runtime branch. Use suggestion by @JASory in #84 (#87)
* Undo typed stride as that introduces a runtime branch. Use suggestion by @JASory in #84 * Add debug assert
1 parent 411ef5c commit 6fc4e9f

File tree

1 file changed

+5
-19
lines changed

1 file changed

+5
-19
lines changed

src/search.rs

Lines changed: 5 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@ use crate::is_prime;
55
/// Generalised function for nearest search by incrementing/decrementing by 1
66
/// Any attempt at optimising this would be largely pointless since the largest prime gap under 2^64 is only 1550
77
/// And is_prime's trial division already eliminates most of those
8-
const fn bounded_search(mut n: u64, stride: Stride) -> Option<u64> {
9-
let stride = stride.into_u64();
8+
const fn bounded_search(mut n: u64, stride: u64) -> Option<u64> {
9+
debug_assert!(stride == 1 || stride == u64::MAX);
1010

1111
loop {
1212
// Addition over Z/2^64, aka regular addition under optimisation flags
@@ -46,7 +46,8 @@ const fn bounded_search(mut n: u64, stride: Stride) -> Option<u64> {
4646
/// ```
4747
#[must_use = "the function only returns a new value and does not modify its input"]
4848
pub const fn previous_prime(n: u64) -> Option<u64> {
49-
bounded_search(n, Stride::Down)
49+
// Adding by 2^64-1 over Z/2^64 is equivalent to subtracting by 1
50+
bounded_search(n, u64::MAX)
5051
}
5152

5253
/// Returns the smallest prime greater than `n` if there is one that
@@ -73,20 +74,5 @@ pub const fn previous_prime(n: u64) -> Option<u64> {
7374
/// ```
7475
#[must_use = "the function only returns a new value and does not modify its input"]
7576
pub const fn next_prime(n: u64) -> Option<u64> {
76-
bounded_search(n, Stride::Up)
77-
}
78-
79-
enum Stride {
80-
Up,
81-
Down,
82-
}
83-
84-
impl Stride {
85-
const fn into_u64(self) -> u64 {
86-
match self {
87-
Self::Up => 1,
88-
// Adding by 2^64-1 over Z/2^64 is equivalent to subtracting by 1
89-
Self::Down => u64::MAX,
90-
}
91-
}
77+
bounded_search(n, 1)
9278
}

0 commit comments

Comments
 (0)