Skip to content

Commit

Permalink
Throw BoundsError on insert! beyond end of existing BitVector as well
Browse files Browse the repository at this point in the history
Ref #7373

Also fix return value of insert! to be the BitVector so it matches the
behavior for Vectors
  • Loading branch information
simonster committed Jun 23, 2014
1 parent 9effcb3 commit b368c9f
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 23 deletions.
38 changes: 17 additions & 21 deletions base/bitarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -592,34 +592,30 @@ function shift!(B::BitVector)
end

function insert!(B::BitVector, i::Integer, item)
i < 1 && throw(BoundsError())
item = convert(Bool, item)

n = length(B)
if i > n
x = falses(i - n)
append!(B, x)
else
Bc = B.chunks
1 <= i <= n+1 || throw(BoundsError())
item = convert(Bool, item)

k, j = get_chunks_id(i)
Bc = B.chunks

l = @_mod64 length(B)
if l == 0
ccall(:jl_array_grow_end, Void, (Any, Uint), Bc, 1)
Bc[end] = uint64(0)
end
B.len += 1
k, j = get_chunks_id(i)

for t = length(Bc) : -1 : k + 1
Bc[t] = (Bc[t] << 1) | (Bc[t - 1] >>> 63)
end
l = @_mod64 length(B)
if l == 0
ccall(:jl_array_grow_end, Void, (Any, Uint), Bc, 1)
Bc[end] = uint64(0)
end
B.len += 1

msk_aft = (_msk64 << j)
msk_bef = ~msk_aft
Bc[k] = (msk_bef & Bc[k]) | ((msk_aft & Bc[k]) << 1)
for t = length(Bc) : -1 : k + 1
Bc[t] = (Bc[t] << 1) | (Bc[t - 1] >>> 63)
end

msk_aft = (_msk64 << j)
msk_bef = ~msk_aft
Bc[k] = (msk_bef & Bc[k]) | ((msk_aft & Bc[k]) << 1)
B[i] = item
B
end

function _deleteat!(B::BitVector, i::Integer)
Expand Down
6 changes: 4 additions & 2 deletions test/bitarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -382,11 +382,13 @@ end
@test length(b1) == 0

b1 = BitArray(0)
@test_throws BoundsError insert!(b1, 2, false)
@test_throws BoundsError insert!(b1, 0, false)
i1 = bitunpack(b1)
for m = 1 : v1
j = rand(1:m)
x = randbool()
insert!(b1, j, x)
@test insert!(b1, j, x) === b1
insert!(i1, j, x)
@test isequal(bitunpack(b1), i1)
end
Expand All @@ -395,7 +397,7 @@ b1 = randbool(v1)
i1 = bitunpack(b1)
for j in [63, 64, 65, 127, 128, 129, 191, 192, 193]
x = rand(0:1)
insert!(b1, j, x)
@test insert!(b1, j, x) === b1
insert!(i1, j, x)
@test isequal(bitunpack(b1), i1)
end
Expand Down

0 comments on commit b368c9f

Please sign in to comment.