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

Documented abs overflow behavior, added checked_abs for overflow prot… #13841

Merged
merged 3 commits into from
Nov 2, 2015
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
25 changes: 25 additions & 0 deletions base/int.jl
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,33 @@ copysign(x::Signed, y::Float64) = copysign(x, reinterpret(Int64,y))
copysign(x::Signed, y::Real) = copysign(x, -oftype(x,signbit(y)))

abs(x::Unsigned) = x

"""
abs(x::Signed)

The absolute value of x. When `abs` is applied to signed integers,
overflow may occur, resulting in the return of a negative value. This
overflow occurs only when `abs` is applied to the minimum
representable value of a signed integer. That is when `x ==
typemin(typeof(x))`, `abs(x) == x`, not `-x` as might be expected.

"""
abs(x::Signed) = flipsign(x,x)

"""
checked_abs(x::Signed)

The absolute value of x, with signed integer overflow error trapping.
`checked_abs` will throw an `OverflowError` when `x ==
typemin(typeof(x))`. Otherwise `checked_abs` behaves as `abs`, though
the overflow protection may impose a perceptible performance penalty.

"""
function checked_abs{T<:Signed}(x::T)
x == typemin(T) && throw(OverflowError())
abs(x)
end

~(n::Integer) = -n-1

unsigned(x::Signed) = reinterpret(typeof(convert(Unsigned,zero(x))), x)
Expand Down
7 changes: 6 additions & 1 deletion test/int.jl
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ end

# checked operations

import Base: checked_add, checked_sub, checked_mul
import Base: checked_add, checked_sub, checked_mul, checked_abs
@test checked_sub(UInt(4), UInt(3)) === UInt(1)
@test_throws OverflowError checked_sub(UInt(5), UInt(6))
@test checked_mul(UInt(4), UInt(3)) === UInt(12)
Expand All @@ -138,6 +138,11 @@ else
@test_throws OverflowError checked_mul(UInt(2)^62, UInt(2)^2)
end

for T in SItypes
@test checked_abs(-one(T)) == one(T)
@test_throws OverflowError checked_abs(typemin(T))
end

# Checked operations on UInt128 are currently broken
# FIXME: #4905

Expand Down