Skip to content

Commit 907493a

Browse files
kmsquireStefanKarpinski
authored andcommitted
Fix findnext on BitArrays
1 parent c3471b6 commit 907493a

File tree

2 files changed

+34
-2
lines changed

2 files changed

+34
-2
lines changed

base/bitarray.jl

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1449,7 +1449,16 @@ end
14491449
# returns the index of the next non-zero element, or 0 if all zeros
14501450
function findnext(B::BitArray, start::Integer)
14511451
Bc = B.chunks
1452-
for i = div(start-1,64)+1:length(Bc)
1452+
1453+
chunk_start = div(start-1, 64)+1
1454+
within_chunk_start = start-1-chunk_start*64
1455+
mask = _msk64-((1<<within_chunk_start)-1)
1456+
1457+
if Bc[chunk_start] & mask != 0
1458+
return (chunk_start-1) << 6 + trailing_zeros(Bc[chunk_start] & mask) + 1
1459+
end
1460+
1461+
for i = chunk_start+1:length(Bc)
14531462
if Bc[i] != 0
14541463
return (i-1) << 6 + trailing_zeros(Bc[i]) + 1
14551464
end
@@ -1465,7 +1474,16 @@ function findnextnot(B::BitArray, start::Integer)
14651474
if l == 0
14661475
return 0
14671476
end
1468-
for i = div(start-1,64)+1:l-1
1477+
1478+
chunk_start = div(start-1, 64)+1
1479+
within_chunk_start = start-1-chunk_start*64
1480+
mask = (1<<within_chunk_start)-1
1481+
1482+
if Bc[chunk_start] | mask != _msk64
1483+
return (chunk_start-1) << 6 + trailing_ones(Bc[chunk_start] | mask) + 1
1484+
end
1485+
1486+
for i = chunk_start+1:l-1
14691487
if Bc[i] != _msk64
14701488
return (i-1) << 6 + trailing_ones(Bc[i]) + 1
14711489
end

test/bitarray.jl

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -521,6 +521,20 @@ b1 = randbool(v1)
521521

522522
@check_bit_operation find Vector{Int} (b1,)
523523

524+
b1 = trues(v1)
525+
for i = 0:v1-1
526+
@test findfirst(b1 >> i) == i+1
527+
@test Base.findfirstnot(~(b1 >> i)) == i+1
528+
end
529+
530+
for i = 3:v1-1
531+
for j = 2:i
532+
submask = b1 << (v1-j+1)
533+
@test findnext((b1 >> i) | submask,j) == i+1
534+
@test Base.findnextnot((~(b1 >> i)) $ submask,j) == i+1
535+
end
536+
end
537+
524538
b1 = randbool(n1, n2)
525539
@check_bit_operation findn_nzs (Vector{Int}, Vector{Int}, BitArray) (b1,)
526540

0 commit comments

Comments
 (0)