putil: Fix SparseArray get_lowest_on_bit and get_lowest_off_bit

This commit is contained in:
rdb 2024-11-14 20:07:48 +01:00
parent 804d49fdbb
commit d173086a6f
2 changed files with 40 additions and 3 deletions

View File

@ -89,12 +89,16 @@ get_num_off_bits() const {
/**
* Returns the index of the lowest 1 bit in the array. Returns -1 if there
* are no 1 bits or if there are an infinite number of 1 bits.
* are no 1 bits and 0 if there are an infinite number of 1 bits.
*/
int SparseArray::
get_lowest_on_bit() const {
if (_inverse) {
return -1;
if (_subranges.empty() || _subranges[0]._begin > 0) {
return 0;
} else {
return _subranges[0]._end;
}
}
if (_subranges.empty()) {
@ -111,7 +115,11 @@ get_lowest_on_bit() const {
int SparseArray::
get_lowest_off_bit() const {
if (!_inverse) {
return -1;
if (_subranges.empty() || _subranges[0]._begin > 0) {
return 0;
} else {
return _subranges[0]._end;
}
}
if (_subranges.empty()) {

View File

@ -251,6 +251,35 @@ def test_sparse_array_nonzero():
assert sa
def test_sparse_array_lowest_bit():
sa = core.SparseArray()
assert sa.get_lowest_off_bit() == 0
assert sa.get_lowest_on_bit() == -1
sa.invert_in_place()
assert sa.get_lowest_off_bit() == -1
assert sa.get_lowest_on_bit() == 0
sa = core.SparseArray()
sa.set_bit(0)
sa.set_bit(1)
assert sa.get_lowest_off_bit() == 2
assert sa.get_lowest_on_bit() == 0
sa.invert_in_place()
assert sa.get_lowest_off_bit() == 0
assert sa.get_lowest_on_bit() == 2
sa = core.SparseArray()
sa.set_bit(2)
assert sa.get_lowest_off_bit() == 0
assert sa.get_lowest_on_bit() == 2
sa.invert_in_place()
assert sa.get_lowest_off_bit() == 2
assert sa.get_lowest_on_bit() == 0
def test_sparse_array_getstate():
sa = core.SparseArray()
assert sa.__getstate__() == ()