From 6fc4e9f0d342d5e17bb2c3022a5323f5528ce2b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Johanna=20S=C3=B6rng=C3=A5rd?= <44257381+JSorngard@users.noreply.github.com> Date: Fri, 29 Nov 2024 14:05:09 +0100 Subject: [PATCH] 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 --- src/search.rs | 24 +++++------------------- 1 file changed, 5 insertions(+), 19 deletions(-) diff --git a/src/search.rs b/src/search.rs index cb54006..7e14134 100644 --- a/src/search.rs +++ b/src/search.rs @@ -5,8 +5,8 @@ use crate::is_prime; /// Generalised function for nearest search by incrementing/decrementing by 1 /// Any attempt at optimising this would be largely pointless since the largest prime gap under 2^64 is only 1550 /// And is_prime's trial division already eliminates most of those -const fn bounded_search(mut n: u64, stride: Stride) -> Option { - let stride = stride.into_u64(); +const fn bounded_search(mut n: u64, stride: u64) -> Option { + debug_assert!(stride == 1 || stride == u64::MAX); loop { // 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 { /// ``` #[must_use = "the function only returns a new value and does not modify its input"] pub const fn previous_prime(n: u64) -> Option { - bounded_search(n, Stride::Down) + // Adding by 2^64-1 over Z/2^64 is equivalent to subtracting by 1 + bounded_search(n, u64::MAX) } /// Returns the smallest prime greater than `n` if there is one that @@ -73,20 +74,5 @@ pub const fn previous_prime(n: u64) -> Option { /// ``` #[must_use = "the function only returns a new value and does not modify its input"] pub const fn next_prime(n: u64) -> Option { - bounded_search(n, Stride::Up) -} - -enum Stride { - Up, - Down, -} - -impl Stride { - const fn into_u64(self) -> u64 { - match self { - Self::Up => 1, - // Adding by 2^64-1 over Z/2^64 is equivalent to subtracting by 1 - Self::Down => u64::MAX, - } - } + bounded_search(n, 1) }