Trying to translate some Rust code to C++, so this might be the wrong place, but I thought it'd be more likely that rust people know C++ than the other way around.
Rust original:
const fn prime_gen(limit: usize) -> [u8; COUNT] {
let mut numbers = [0u8; COUNT];
numbers[0] = 1;
let mut i = 3;
while i * i < limit {
let res = {
let index = i / 2;
let actual_index = index / 8;
let inner_index = get_inner_index(index);
(numbers[actual_index] & inner_index) == inner_index
};
if !res {
let mut j = i * i;
while j < limit {
let half_j = j / 2;
let actual_index = half_j / 8;
let inner_index = get_inner_index(half_j);
numbers[actual_index] |= inner_index;
j += i << 1;
}
}
i += 2;
}
numbers
}
const fn get_inner_index(index: usize) -> u8 {
match index & 7 {
0 => 0b_0000_0001,
1 => 0b_0000_0010,
2 => 0b_0000_0100,
3 => 0b_0000_1000,
4 => 0b_0001_0000,
5 => 0b_0010_0000,
6 => 0b_0100_0000,
7 => 0b_1000_0000,
_ => panic!(),
}
}
Rust output:
91 34 4B 9B 65 ED 92 7E CD B3
C++ version:
constexpr char get_inner_index (char index) {
switch (index % 8) {
case 0: return 0b00000001;
case 2: return 0b00000011;
case 3: return 0b00000111;
case 4: return 0b00001111;
case 5: return 0b00011111;
case 6: return 0b00111111;
case 7: return 0b01111111;
default: return 0;
}
}
constexpr std::array<unsigned char, COUNT> prime_gen (const ulong limit) {
auto numbers = []{
std::array<unsigned char, COUNT> a{};
for (auto& e : a) {
e = 0;
}
return a;
}();
numbers[0] = 1;
auto i = 3u;
while (i * i < limit) {
auto res = [&]{
auto index = i / 2;
auto actual_index = index / 8;
auto inner_index = get_inner_index(index);
return (numbers[actual_index] & inner_index) == inner_index;
}();
if (!res) {
auto j = i * i;
while (j < limit) {
auto half_j = j / 2;
auto actual_index = half_j / 8;
auto inner_index = get_inner_index(half_j);
numbers[actual_index] |= inner_index;
j += i / 2;
}
}
i += 2;
}
return numbers;
}
C++ output:
1 7F 7F 7F 7F 7F 7F 7F 0 0 0 0 0 0 0 0
They somehow don't give me the same output (only comparing the 10 first bytes). The rust version needs to be on nightly and have a few feature flags for const fn, but that should be irrelevant since it works the same way as if it weren't const