[swift-users] abs() Bug?
C. Keith Ray
keithray at mac.com
Tue Dec 12 14:06:07 CST 2017
Should these be consistent?
All crashing or none crashing?
print(abs(Int8.min)) // crash
print(abs(Int16.min)) // crash
print(abs(Int32.min)) // prints -2147483648
print(abs(Int64.min)) // crash
Should this be reported by Radar or another mechanism?
I'm using this as a replacement:
func safeAbs<T: SignedInteger & FixedWidthInteger>(_ i: T) -> T {
if i >= 0 {
return i
} else if i == T.min { // can't negate this value
// return i // unconverted, violates postcondition, assert(result >= 0)
// return 0 // or return an arbitrary "safe" value
return -(1+i) // or return approximately the right value
} else {
return -i
}
}
print(safeAbs(Int8.min)) // prints 127
print(safeAbs(Int16.min)) // prints 32767
print(safeAbs(Int32.min)) // prints 2147483647
print(safeAbs(Int64.min)) // prints 9223372036854775807
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20171212/30f968f2/attachment.html>
More information about the swift-users
mailing list