Skip to content

Commit 8d36f84

Browse files
committed
Return sensible values in min/maxRepresentableNumber for bitsCount larger than bit width
1 parent 5d1c0e8 commit 8d36f84

1 file changed

Lines changed: 6 additions & 5 deletions

File tree

Sources/SignedNumberRepresentation.swift

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,17 +21,17 @@ public enum SignedNumberRepresentation {
2121
case .signMagnitude:
2222
fallthrough
2323
case .oneComplementNegatives:
24-
return bitsCount == Int.bitWidth ? Int.min : -(1 << (bitsCount - 1) - 1)
24+
return bitsCount >= Int.bitWidth ? Int.min : -(1 << (bitsCount - 1) - 1)
2525
case .twoComplementNegatives:
2626
// Technically, we don't need to be extremely careful in the 2's-complement case, since it is the
2727
// representation used internally by Swift, however, in practice, we still get arithmetic overflow
2828
// in the bitsCount == Int.bitWidth case, if we use the formula, so we check for this case specifically.
29-
return bitsCount == Int.bitWidth ? Int.min : -(1 << (bitsCount - 1))
29+
return bitsCount >= Int.bitWidth ? Int.min : -(1 << (bitsCount - 1))
3030
case .biased(let bias):
3131
precondition(bias >= 0)
3232
return -bias
3333
case .radixNegativeTwo:
34-
if bitsCount == Int.bitWidth {
34+
if bitsCount >= Int.bitWidth {
3535
return Int.min
3636
}
3737
// Minimum corresponds to all of the odd bits being set.
@@ -54,11 +54,12 @@ public enum SignedNumberRepresentation {
5454
case .oneComplementNegatives:
5555
fallthrough
5656
case .twoComplementNegatives:
57-
return bitsCount == Int.bitWidth ? Int.max : 1 << (bitsCount - 1) - 1
57+
return bitsCount >= Int.bitWidth ? Int.max : 1 << (bitsCount - 1) - 1
5858
case .biased(let bias):
5959
precondition(bias >= 0)
60-
return bitsCount == Int.bitWidth ? Int.max - bias : (1 << bitsCount) - 1 - bias
60+
return bitsCount >= Int.bitWidth ? Int.max - bias : (1 << bitsCount) - 1 - bias
6161
case .radixNegativeTwo:
62+
// Maximum corresponds to all of the even bits being set.
6263
var result = 0
6364
var mult = 1
6465
for _ in stride(from: 0, to: bitsCount, by: 2) {

0 commit comments

Comments
 (0)