use std lib function in pmmr for all_ones() and most_significant_pos() (#924)

* use std lib function in pmmr for all_ones() and most_significant_pos()

* fix all_ones() edge case with 0 and add comparison tests with old functions
This commit is contained in:
Riccardo Casatta 2018-04-04 14:25:03 +02:00 committed by Yeastplume
parent ac979d021d
commit 40212942da

View file

@ -987,28 +987,13 @@ fn bintree_jump_left(num: u64) -> u64 {
// Check if the binary representation of a number is all ones.
fn all_ones(num: u64) -> bool {
if num == 0 {
return false;
}
let mut bit = 1;
while num >= bit {
if num & bit == 0 {
return false;
}
bit = bit << 1;
}
true
let ones = num.count_ones();
num.leading_zeros() + ones == 64 && ones > 0
}
// Get the position of the most significant bit in a number.
fn most_significant_pos(num: u64) -> u64 {
let mut pos = 0;
let mut bit = 1;
while num >= bit {
bit = bit << 1;
pos += 1;
}
pos
64 - u64::from(num.leading_zeros())
}
#[cfg(test)]
@ -1140,7 +1125,7 @@ mod test {
for n in vec![1, 7, 255] {
assert!(all_ones(n), "{} should be all ones", n);
}
for n in vec![6, 9, 128] {
for n in vec![0, 6, 9, 128] {
assert!(!all_ones(n), "{} should not be all ones", n);
}
}
@ -1915,4 +1900,45 @@ mod test {
assert_eq!(n_leaves(9), 6);
assert_eq!(n_leaves(10), 6);
}
#[test]
fn check_all_ones() {
for i in 0..1000000 {
assert_eq!(old_all_ones(i),all_ones(i));
}
}
// Check if the binary representation of a number is all ones.
fn old_all_ones(num: u64) -> bool {
if num == 0 {
return false;
}
let mut bit = 1;
while num >= bit {
if num & bit == 0 {
return false;
}
bit = bit << 1;
}
true
}
#[test]
fn check_most_significant_pos() {
for i in 0u64..1000000 {
assert_eq!(old_most_significant_pos(i),most_significant_pos(i));
}
}
// Get the position of the most significant bit in a number.
fn old_most_significant_pos(num: u64) -> u64 {
let mut pos = 0;
let mut bit = 1;
while num >= bit {
bit = bit << 1;
pos += 1;
}
pos
}
}