Skip to content

fix bit_map! with aliasing #50781

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions base/bitarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1791,9 +1791,10 @@ function bit_map!(f::F, dest::BitArray, A::BitArray) where F
dest_last = destc[len_Ac]
_msk = _msk_end(A)
# first zero out the bits mask is going to change
destc[len_Ac] = (dest_last & (~_msk))
# then update bits by `or`ing with a masked RHS
destc[len_Ac] |= f(Ac[len_Ac]) & _msk
# DO NOT SEPARATE ONTO TO LINES.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
# DO NOT SEPARATE ONTO TO LINES.
# DO NOT SEPARATE INTO TWO LINES.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oops :)

# Otherwise there will be bugs when Ac aliases destc
destc[len_Ac] = (dest_last & (~_msk)) | f(Ac[len_Ac]) & _msk
dest
end
function bit_map!(f::F, dest::BitArray, A::BitArray, B::BitArray) where F
Expand All @@ -1812,9 +1813,10 @@ function bit_map!(f::F, dest::BitArray, A::BitArray, B::BitArray) where F
dest_last = destc[len_Ac]
_msk = _msk_end(min_bitlen)
# first zero out the bits mask is going to change
destc[len_Ac] = (dest_last & ~(_msk))
# then update bits by `or`ing with a masked RHS
destc[len_Ac] |= f(Ac[end], Bc[end]) & _msk
# DO NOT SEPARATE ONTO TO LINES.
# Otherwise there will be bugs when Ac or Bc aliases destc
destc[len_Ac] = (dest_last & ~(_msk)) | f(Ac[end], Bc[end]) & _msk
dest
end

Expand Down
15 changes: 15 additions & 0 deletions test/bitarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1539,6 +1539,21 @@ timesofar("reductions")
end
end
end
@testset "Issue #50780, map! bitarray map! where dest aliases source" begin
a = BitVector([1,0])
b = map(!, a)
map!(!, a, a) # a .= !.a
@test a == b == BitVector([0,1])

a = BitVector([1,0])
c = map(|, a, b)
map!(|, a, a, b)
@test c == a == BitVector([1, 1])

a = BitVector([1,0])
map!(|, b, a, b)
@test c == b == BitVector([1, 1])
end
end

## Filter ##
Expand Down