Skip to content

Commit f535c93

Browse files
authored
prime_less_than_next_pow_2_or_1 template for unsigned types (#6)
1 parent f44d0e4 commit f535c93

File tree

3 files changed

+38
-2
lines changed

3 files changed

+38
-2
lines changed

internals/tests/testing/primes_test.cpp

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22

33
#include "testing_v1/test.hpp"
44

5+
#include <cstddef>
6+
#include <cstdint>
7+
58
using namespace testing_v1;
69

710
#define VERIFY_IS_PRIME_OR_1 0
@@ -33,7 +36,23 @@ template <class T> static void test() {
3336
}
3437
}
3538

39+
template <class T> static void test_overload() {
40+
verify(127 ==
41+
dumpster_v1::prime_less_than_next_pow_2_or_1(static_cast<T>(101)));
42+
}
43+
3644
auto primes_test = test([]() {
3745
test<uint32_t>();
3846
test<uint64_t>();
47+
48+
test_overload<uint8_t>();
49+
test_overload<uint16_t>();
50+
51+
test_overload<unsigned char>();
52+
test_overload<unsigned short>();
53+
test_overload<unsigned int>();
54+
test_overload<unsigned long>();
55+
test_overload<unsigned long long>();
56+
57+
test_overload<size_t>();
3958
});
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,13 @@
11
#pragma once
22

33
#include "dumpster_v1/synopsis.hpp"
4+
5+
template <class UnsignedType, class>
6+
UnsignedType dumpster_v1::prime_less_than_next_pow_2_or_1(UnsignedType x) {
7+
if constexpr (sizeof(UnsignedType) <= sizeof(uint32_t))
8+
return static_cast<UnsignedType>(
9+
prime_less_than_next_pow_2_or_1(static_cast<uint32_t>(x)));
10+
else
11+
return static_cast<UnsignedType>(
12+
prime_less_than_next_pow_2_or_1(static_cast<uint64_t>(x)));
13+
}

provides/include/dumpster_v1/synopsis.hpp

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,10 +65,17 @@ void insertion_sort(RandomIt values, Less less, IsSentinel is_sentinel);
6565
/// next power of 2 or 1.
6666
uint32_t prime_less_than_next_pow_2_or_1(uint32_t x);
6767

68-
/// Returns the largest prime that is less than the given value rounded
69-
/// to the next power of 2 or 1.
68+
/// Returns the largest prime that is less than the given value rounded to the
69+
/// next power of 2 or 1.
7070
uint64_t prime_less_than_next_pow_2_or_1(uint64_t x);
7171

72+
/// Returns the largest prime that is less than the given value rounded to the
73+
/// next power of 2 or 1.
74+
template <class UnsignedType,
75+
class = std::enable_if_t<(std::is_unsigned_v<UnsignedType> &&
76+
sizeof(UnsignedType) <= sizeof(uint64_t))>>
77+
UnsignedType prime_less_than_next_pow_2_or_1(UnsignedType x);
78+
7279
// ranqd1.hpp ==================================================================
7380

7481
/// The `ranqd1` generator from Numerical Recipes in C, 2nd Edition.

0 commit comments

Comments
 (0)