Skip to content
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

fix mod for mixes of Signed and Unsigned #57853

Merged
merged 4 commits into from
Mar 23, 2025
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: 8 additions & 2 deletions base/int.jl
Original file line number Diff line number Diff line change
Expand Up @@ -286,8 +286,14 @@ function mod(x::T, y::T) where T<:Integer
y == -1 && return T(0) # avoid potential overflow in fld
return x - fld(x, y) * y
end
mod(x::BitSigned, y::Unsigned) = rem(y + unsigned(rem(x, y)), y)
mod(x::Unsigned, y::Signed) = rem(y + signed(rem(x, y)), y)
function mod(x::BitSigned, y::Unsigned)
remval = rem(x, y) # correct iff remval>=0
return unsigned(remval + (remval<zero(remval))*y)
end
function mod(x::Unsigned, y::Signed)
remval = signed(rem(x, y)) #remval>0 so correct iff y>0 or remval==0
return remval + (!iszero(remval) && y<zero(y))*y
end
mod(x::T, y::T) where {T<:Unsigned} = rem(x, y)

# Don't promote integers for div/rem/mod since there is no danger of overflow,
Expand Down
17 changes: 17 additions & 0 deletions test/int.jl
Original file line number Diff line number Diff line change
Expand Up @@ -362,6 +362,23 @@ end
end
end
end
# exhaustive UInt8/Int8 tests for mixed signedness
for f in (mod, rem)
for i in -128:127
for j in 0:255
if iszero(i)
@test_throws DivideError f(UInt8(j), Int8(i))
else
@test f(UInt8(j), Int8(i)) == f(j, i)
end
if iszero(j)
@test_throws DivideError f(Int8(i), UInt8(j))
else
@test f(Int8(i), UInt8(j)) == f(i,j)
end
end
end
end
end

@testset "Underscores in big_str" begin
Expand Down