diff --git a/Sources/IntegerUtilities/README.md b/Sources/IntegerUtilities/README.md index ee7318c..e626681 100644 --- a/Sources/IntegerUtilities/README.md +++ b/Sources/IntegerUtilities/README.md @@ -4,7 +4,7 @@ _Note: This module is only present on `main`, and has not yet been stabilized an ## Utilities defined for `BinaryInteger` -The following API are defined for all integer types conforming to `BinaryInteger`: +The following API are defined for all integer types: - The `gcd(_:_:)` free function implements the _Greatest Common Divisor_ operation. @@ -36,6 +36,32 @@ The following API are defined for signed integer types: - The `rotated(right:)` and `rotated(left:)` methods implement _bitwise rotation_ for signed and unsigned integer types. The count parameter may be any `BinaryInteger` type. + +### Saturating Arithmetic + +The following saturating operations are defined as methods on +`FixedWidthInteger` types: + +- `addingWithSaturation(_:)` +- `subtractingWithSaturation(_:)` +- `negatedWithSaturation(_:)` +- `multipliedWithSaturation(by:)` + +These implement _saturating arithmetic_. These are an alternative to the +usual `+`, `-`, and `*` operators, which trap if the result cannot be +represented in the argument type, and `&+`, `&-`, and `&*` which wrap +out-of-range results modulo 2ⁿ for some n. Instead these methods clamp +the result to the representable range of the type: +``` +let x: Int8 = 84 +let y: Int8 = 100 +let a = x + y // traps due to overflow +let b = x &+ y // wraps to -72 +let c = x.addingWithSaturation(y) // saturates to 127 +``` + +There is one other method, `shiftedWithSaturation(leftBy:rounding:)`, +which performs a bitwise shift with rounding and saturation. ## Types diff --git a/Sources/IntegerUtilities/SaturatingArithmetic.swift b/Sources/IntegerUtilities/SaturatingArithmetic.swift index 14aebd4..91ba75d 100644 --- a/Sources/IntegerUtilities/SaturatingArithmetic.swift +++ b/Sources/IntegerUtilities/SaturatingArithmetic.swift @@ -13,6 +13,19 @@ extension FixedWidthInteger { @_transparent @usableFromInline var signExtension: Self { self &>> -1 } + /// Saturating integer addition + /// + /// `self + other` clamped to the representable range of the type. e.g.: + /// ``` + /// let a: Int8 = 84 + /// let b: Int8 = 100 + /// // 84 + 100 = 184 is not representable as + /// // Int8, so `c` is clamped to Int8.max (127). + /// let c = a.addingWithSaturation(b) + /// ``` + /// + /// Anytime the "normal addition" `self + other` does not trap, + /// `addingWithSaturation` produces the same result. @inlinable public func addingWithSaturation(_ other: Self) -> Self { let (wrapped, overflow) = addingReportingOverflow(other) @@ -20,6 +33,23 @@ extension FixedWidthInteger { return Self.max &- signExtension } + /// Saturating integer subtraction + /// + /// `self - other` clamped to the representable range of the type. e.g.: + /// ``` + /// let a: UInt = 37 + /// let b: UInt = 42 + /// // 37 - 42 = -5, which is not representable as + /// // UInt, so `c` is clamped to UInt.min (zero). + /// let c = a.subtractingWithSaturation(b) + /// ``` + /// + /// Note that `a.addingWithSaturation(-b)` is not always equivalent to + /// `a.subtractingWithSaturation(b)`, because `-b` is not representable + /// if `b` is the minimum value of a signed type. + /// + /// Anytime the "normal subtraction" `self - other` does not trap, + /// `subtractingWithSaturation` produces the same result. @inlinable public func subtractingWithSaturation(_ other: Self) -> Self { let (wrapped, overflow) = subtractingReportingOverflow(other) @@ -27,6 +57,30 @@ extension FixedWidthInteger { return Self.max &- signExtension } + /// Saturating integer negation + /// + /// For unsigned types, the result is always zero. This is not very + /// interesting, but may occasionally be useful in generic contexts. + /// For signed types, the result is `-self` unless `self` is `.min`, + /// in which case the result is `.max`. + @inlinable + public func negatedWithSaturation() -> Self { + Self.zero.subtractingWithSaturation(self) + } + + /// Saturating integer multiplication + /// + /// `self * other` clamped to the representable range of the type. e.g.: + /// ``` + /// let a: Int8 = -16 + /// let b: Int8 = -8 + /// // -16 * -8 = 128 is not representable as + /// // Int8, so `c` is clamped to Int8.max (127). + /// let c = a.multipliedWithSaturation(by: b) + /// ``` + /// + /// Anytime the "normal multiplication" `self * other` does not trap, + /// `multipliedWithSaturation` produces the same result. @inlinable public func multipliedWithSaturation(by other: Self) -> Self { let (high, low) = multipliedFullWidth(by: other) @@ -35,6 +89,18 @@ extension FixedWidthInteger { return Self.max &- high.signExtension } + /// Bitwise left with rounding and saturation. + /// + /// `self` multiplied by the rational number 2^(`count`), saturated to the + /// range `Self.min ... Self.max`, and rounded according to `rule`. + /// + /// See `shifted(rightBy:rounding:)` for more discussion of rounding + /// shifts with examples. + /// + /// - Parameters: + /// - leftBy count: the number of bits to shift by. If positive, this is a left-shift, + /// and if negative a right shift. + /// - rounding rule: the direction in which to round if `count` is negative. @inlinable public func shiftedWithSaturation( leftBy count: Count, rounding rule: RoundingRule = .down @@ -42,8 +108,10 @@ extension FixedWidthInteger { // If count is zero or negative, negate it and do a right // shift without saturation instead, as that's easier. guard count > 0 else { - // TODO: fixup case where 0 - count overflows - return shifted(rightBy: 0 - count, rounding: rule) + return shifted( + rightBy: Self(clamping: count).negatedWithSaturation(), + rounding: rule + ) } guard count < Self.bitWidth else { // If count is bitWidth or greater, we always overflow diff --git a/Sources/IntegerUtilities/ShiftWithRounding.swift b/Sources/IntegerUtilities/ShiftWithRounding.swift index baaa8f4..67ff8b9 100644 --- a/Sources/IntegerUtilities/ShiftWithRounding.swift +++ b/Sources/IntegerUtilities/ShiftWithRounding.swift @@ -62,10 +62,10 @@ extension BinaryInteger { // rounding, and then shifting the remaining bitWidth - 1 bits with // the desired rounding mode. let count = count - Count(bitWidth - 1) - var floor = self >> count + let floor = self >> count let lost = self - (floor << count) - if lost != 0 { floor |= 1 } // insert sticky bit - return floor.shifted(rightBy: bitWidth - 1, rounding: rule) + let sticky = floor | (lost == 0 ? 0 : 1) + return sticky.shifted(rightBy: bitWidth - 1, rounding: rule) } // Now we are in the happy case: 0 < count < bitWidth, which makes all // the math to handle rounding simpler.