From 7953ef315a427b1e40d6772fb5b65550a4b0f080 Mon Sep 17 00:00:00 2001 From: Stephen Canon Date: Wed, 26 Apr 2023 16:43:50 -0400 Subject: [PATCH 01/13] First pass. --- Sources/IntegerUtilities/CMakeLists.txt | 1 + .../IntegerUtilities/DivideWithRounding.swift | 9 +-- Sources/IntegerUtilities/RoundingRule.swift | 28 +++++++++ .../SaturatingArithmetic.swift | 60 +++++++++++++++++++ 4 files changed, 94 insertions(+), 4 deletions(-) create mode 100644 Sources/IntegerUtilities/SaturatingArithmetic.swift diff --git a/Sources/IntegerUtilities/CMakeLists.txt b/Sources/IntegerUtilities/CMakeLists.txt index cd141a4..db167c7 100644 --- a/Sources/IntegerUtilities/CMakeLists.txt +++ b/Sources/IntegerUtilities/CMakeLists.txt @@ -12,6 +12,7 @@ add_library(IntegerUtilities GCD.swift Rotate.swift RoundingRule.swift + SaturatingArithmetic.swift ShiftWithRounding.swift) set_target_properties(IntegerUtilities PROPERTIES INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY}) diff --git a/Sources/IntegerUtilities/DivideWithRounding.swift b/Sources/IntegerUtilities/DivideWithRounding.swift index 87fabaa..c0cf0a6 100644 --- a/Sources/IntegerUtilities/DivideWithRounding.swift +++ b/Sources/IntegerUtilities/DivideWithRounding.swift @@ -126,12 +126,13 @@ extension BinaryInteger { } } - // TODO: make this API and make it possible to implement more - // efficiently. Customization point on new/revised integer - // protocol? Shouldn't have to go through .words. + // TODO: make this API and make it possible to implement more efficiently. + // Customization point on new/revised integer protocol? Shouldn't have to + // go through .words. + /// The index of the most-significant set bit. /// - /// - Precondition: self is assumed to be non-zero (to be changed + /// - Precondition: self is assumed to be non-zero (should be changed /// if/when this becomes API). @usableFromInline internal var _msb: Int { diff --git a/Sources/IntegerUtilities/RoundingRule.swift b/Sources/IntegerUtilities/RoundingRule.swift index 47d13c9..937ef07 100644 --- a/Sources/IntegerUtilities/RoundingRule.swift +++ b/Sources/IntegerUtilities/RoundingRule.swift @@ -60,6 +60,34 @@ public enum RoundingRule { /// Adds a uniform random value from [0, d) to the value being rounded, /// where d is the distance between the two closest representable values, /// then rounds the sum downwards. + /// + /// Unlike all the other rounding modes, this mode is _not deterministic_; + /// repeated calls to rounding operations with this mode will generally + /// produce different results. There is a tradeoff implicit in using this + /// mode: you can sacrifice _reproducible_ results to get _more accurate_ + /// results in aggregate. For a contrived but illustrative example, consider + /// the following: + /// ``` + /// let data = Array(repeating: 1, count: 100) + /// let result = data.reduce(0) { + /// $0 + $1.divided(by: 3, rounding: rule) + /// } + /// ``` + /// because 1/3 is always the same value between 0 and 1, any + /// deterministic rounding rule must produce either 0 or 100 for + /// this computation. But rounding `stochastically` will + /// produce a value close to 33. The _error_ of the computation + /// is smaller, but the result will now change between runs of the + /// program. + /// + /// For this simple case a better solution would be to add the + /// values first, and then divide. This gives a result that is both + /// reproducible _and_ accurate: + /// ``` + /// let result = data.reduce(0, +)/3 + /// ``` + /// but this isn't always possible in more sophisticated scenarios, + /// and in those cases this rounding rule may be useful. case stochastically /// If the value being rounded is representable, that value is returned. diff --git a/Sources/IntegerUtilities/SaturatingArithmetic.swift b/Sources/IntegerUtilities/SaturatingArithmetic.swift new file mode 100644 index 0000000..14aebd4 --- /dev/null +++ b/Sources/IntegerUtilities/SaturatingArithmetic.swift @@ -0,0 +1,60 @@ +//===--- SaturatingArithmetic.swift ---------------------------*- swift -*-===// +// +// This source file is part of the Swift Numerics open source project +// +// Copyright (c) 2023 Apple Inc. and the Swift Numerics project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +extension FixedWidthInteger { + @_transparent @usableFromInline + var signExtension: Self { self &>> -1 } + + @inlinable + public func addingWithSaturation(_ other: Self) -> Self { + let (wrapped, overflow) = addingReportingOverflow(other) + if !overflow { return wrapped } + return Self.max &- signExtension + } + + @inlinable + public func subtractingWithSaturation(_ other: Self) -> Self { + let (wrapped, overflow) = subtractingReportingOverflow(other) + if !overflow { return wrapped } + return Self.max &- signExtension + } + + @inlinable + public func multipliedWithSaturation(by other: Self) -> Self { + let (high, low) = multipliedFullWidth(by: other) + let wrapped = Self(truncatingIfNeeded: low) + if high == wrapped.signExtension { return wrapped } + return Self.max &- high.signExtension + } + + @inlinable + public func shiftedWithSaturation( + leftBy count: Count, rounding rule: RoundingRule = .down + ) -> Self { + // 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) + } + guard count < Self.bitWidth else { + // If count is bitWidth or greater, we always overflow + // unless self is zero. + return self == 0 ? 0 : Self.max &- signExtension + } + // Now we have 0 < count < bitWidth, so we can use a nice + // straightforward implementation; the shift overflows if + // the complementary shift doesn't match sign extension. + let wrapped = self << count + if self &>> ~count == signExtension { return wrapped } + return Self.max &- signExtension + } +} From dbffff1ea54d22ec41a673bb24e4bcea078c3dc7 Mon Sep 17 00:00:00 2001 From: Stephen Canon Date: Wed, 26 Apr 2023 18:34:48 -0400 Subject: [PATCH 02/13] Add some basic documentation. --- Sources/IntegerUtilities/README.md | 28 +++++++- .../SaturatingArithmetic.swift | 72 ++++++++++++++++++- .../IntegerUtilities/ShiftWithRounding.swift | 6 +- 3 files changed, 100 insertions(+), 6 deletions(-) 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. From 4779aef9902d3a1e21ea5d295b4223206d1d7c90 Mon Sep 17 00:00:00 2001 From: Stephen Canon Date: Wed, 26 Apr 2023 21:20:57 -0400 Subject: [PATCH 03/13] Test coverage for saturating shift + fix the bug that it turned up. --- .../SaturatingArithmetic.swift | 48 +++++++++++---- Tests/IntegerUtilitiesTests/ShiftTests.swift | 61 ++++++++++++++++++- 2 files changed, 93 insertions(+), 16 deletions(-) diff --git a/Sources/IntegerUtilities/SaturatingArithmetic.swift b/Sources/IntegerUtilities/SaturatingArithmetic.swift index 91ba75d..082fb5d 100644 --- a/Sources/IntegerUtilities/SaturatingArithmetic.swift +++ b/Sources/IntegerUtilities/SaturatingArithmetic.swift @@ -11,7 +11,7 @@ extension FixedWidthInteger { @_transparent @usableFromInline - var signExtension: Self { self &>> -1 } + var sextOrZext: Self { self >> Self.bitWidth } /// Saturating integer addition /// @@ -30,7 +30,7 @@ extension FixedWidthInteger { public func addingWithSaturation(_ other: Self) -> Self { let (wrapped, overflow) = addingReportingOverflow(other) if !overflow { return wrapped } - return Self.max &- signExtension + return Self.max &- sextOrZext } /// Saturating integer subtraction @@ -54,7 +54,7 @@ extension FixedWidthInteger { public func subtractingWithSaturation(_ other: Self) -> Self { let (wrapped, overflow) = subtractingReportingOverflow(other) if !overflow { return wrapped } - return Self.max &- signExtension + return Self.max &- sextOrZext } /// Saturating integer negation @@ -85,8 +85,8 @@ extension FixedWidthInteger { public func multipliedWithSaturation(by other: Self) -> Self { let (high, low) = multipliedFullWidth(by: other) let wrapped = Self(truncatingIfNeeded: low) - if high == wrapped.signExtension { return wrapped } - return Self.max &- high.signExtension + if high == wrapped.sextOrZext { return wrapped } + return Self.max &- high.sextOrZext } /// Bitwise left with rounding and saturation. @@ -106,23 +106,45 @@ extension FixedWidthInteger { leftBy count: Count, rounding rule: RoundingRule = .down ) -> Self { // If count is zero or negative, negate it and do a right - // shift without saturation instead, as that's easier. + // shift without saturation instead, since we already have + // that implemented. guard count > 0 else { + // negating count is tricky, because count's type can be + // an arbitrary BinaryInteger; in particular, it could be + // .min of a signed type, so that its negation cannot be + // represented in the same type. Fortunately, Int64 is + // always big enough to represent arbitrary shifts of + // arbitrary types, so we can use that as an intermediate + // type, and then we can use negatedWithSaturation() to + // handle the .min case. + let int64Count = Int64(clamping: count) return shifted( - rightBy: Self(clamping: count).negatedWithSaturation(), + rightBy: int64Count.negatedWithSaturation(), rounding: rule ) } + let clamped = Self.max &- sextOrZext guard count < Self.bitWidth else { // If count is bitWidth or greater, we always overflow // unless self is zero. - return self == 0 ? 0 : Self.max &- signExtension + return self == 0 ? 0 : clamped } // Now we have 0 < count < bitWidth, so we can use a nice - // straightforward implementation; the shift overflows if - // the complementary shift doesn't match sign extension. - let wrapped = self << count - if self &>> ~count == signExtension { return wrapped } - return Self.max &- signExtension + // straightforward implementation; a shift overflows if + // the complementary shift doesn't match sign-or-zero + // extension. E.g.: + // + // - signed 0b0010_1111 << 2 overflows, because + // 0b0010_1111 >> 5 is 0b0000_0001, which does not + // equal 0b0000_0000 + // + // - unsigned 0b0010_1111 << 2 does not overflow, + // because 0b0010_0000 >> 6 is 0b0000_0000, which + // does equal 0b0000_0000. + let valueBits = Self.bitWidth &- (Self.isSigned ? 1 : 0) + let wrapped = self &<< count + let complement = valueBits &- Int(count) + if self &>> complement == sextOrZext { return wrapped } + return clamped } } diff --git a/Tests/IntegerUtilitiesTests/ShiftTests.swift b/Tests/IntegerUtilitiesTests/ShiftTests.swift index 2fb609c..8475766 100644 --- a/Tests/IntegerUtilitiesTests/ShiftTests.swift +++ b/Tests/IntegerUtilitiesTests/ShiftTests.swift @@ -16,9 +16,9 @@ import _TestSupport final class IntegerUtilitiesShiftTests: XCTestCase { - func testRoundingShift( - _ value: T, _ count: Int, rounding rule: RoundingRule - ) { + func testRoundingShift( + _ value: T, _ count: C, rounding rule: RoundingRule + ) where T: FixedWidthInteger, C: BinaryInteger { let floor = value >> count let lost = value &- floor << count let exact = count <= 0 || lost == 0 @@ -95,6 +95,10 @@ final class IntegerUtilitiesShiftTests: XCTestCase { testRoundingShift(T.random(in: .min ... .max), count, rounding: rule) } } + + for count in Int8.min ... .max { + testRoundingShift(T.random(in: .min ... .max), count, rounding: rule) + } } func testRoundingShifts() { @@ -190,4 +194,55 @@ final class IntegerUtilitiesShiftTests: XCTestCase { testStochasticAverage(DoubleWidth.random(in: .min ... .max)) testStochasticAverage(DoubleWidth.random(in: .min ... .max)) } + + func testSaturatingShift( + _ value: T, _ count: C, rounding rule: RoundingRule + ) where T: FixedWidthInteger, C: FixedWidthInteger { + let observed = value.shiftedWithSaturation(leftBy: count, rounding: rule) + var expected: T = 0 + if count <= 0 { + expected = value.shifted(rightBy: -Int64(count), rounding: rule) + } else { + let multiplier: T = 1 << count + if multiplier <= 0 { + expected = value == 0 ? 0 : + value < 0 ? .min : .max + } else { + expected = value.multipliedWithSaturation(by: multiplier) + } + } + if observed != expected { + print("Error found in \(T.self).shiftedWithSaturation(leftBy: \(count), rounding: \(rule)).") + print(" Value: \(String(value, radix: 16))") + print("Expected: \(String(expected, radix: 16))") + print("Observed: \(String(observed, radix: 16))") + XCTFail() + return + } + } + + func testSaturatingShift( + _ type: T.Type, rounding rule: RoundingRule + ) { + for count in Int8.min ... .max { + testSaturatingShift(0, count, rounding: rule) + for bits in 0 ..< T.bitWidth { + let msb: T.Magnitude = 1 << bits + let value = T(truncatingIfNeeded: msb) | .random(in: 0 ... T(msb-1)) + testSaturatingShift(value, count, rounding: rule) + testSaturatingShift(0 &- value, count, rounding: rule) + } + } + } + + func testSaturatingShifts() { + testSaturatingShift(Int8.self, rounding: .toOdd) + testSaturatingShift(UInt8.self, rounding: .toOdd) + testSaturatingShift(Int.self, rounding: .toOdd) + testSaturatingShift(UInt.self, rounding: .toOdd) + } + + func testEdgeCaseForNegativeCount() { + XCTAssertEqual(1.shiftedWithSaturation(leftBy: Int.min), 0) + } } From f00824e9fa90a09c6c4813d4525189e4301527fa Mon Sep 17 00:00:00 2001 From: Stephen Canon Date: Wed, 26 Apr 2023 21:50:23 -0400 Subject: [PATCH 04/13] More tests for saturating arithmetic -- exhaustive sampling of [U]Int8 arguments. --- .../SaturatingArithmetic.swift | 5 +- Tests/IntegerUtilitiesTests/CMakeLists.txt | 1 + .../SaturatingArithmeticTests.swift | 179 ++++++++++++++++++ Tests/IntegerUtilitiesTests/ShiftTests.swift | 51 ----- 4 files changed, 182 insertions(+), 54 deletions(-) create mode 100644 Tests/IntegerUtilitiesTests/SaturatingArithmeticTests.swift diff --git a/Sources/IntegerUtilities/SaturatingArithmetic.swift b/Sources/IntegerUtilities/SaturatingArithmetic.swift index 082fb5d..a454585 100644 --- a/Sources/IntegerUtilities/SaturatingArithmetic.swift +++ b/Sources/IntegerUtilities/SaturatingArithmetic.swift @@ -54,7 +54,7 @@ extension FixedWidthInteger { public func subtractingWithSaturation(_ other: Self) -> Self { let (wrapped, overflow) = subtractingReportingOverflow(other) if !overflow { return wrapped } - return Self.max &- sextOrZext + return Self.isSigned ? Self.max &- sextOrZext : 0 } /// Saturating integer negation @@ -144,7 +144,6 @@ extension FixedWidthInteger { let valueBits = Self.bitWidth &- (Self.isSigned ? 1 : 0) let wrapped = self &<< count let complement = valueBits &- Int(count) - if self &>> complement == sextOrZext { return wrapped } - return clamped + return self &>> complement == sextOrZext ? wrapped : clamped } } diff --git a/Tests/IntegerUtilitiesTests/CMakeLists.txt b/Tests/IntegerUtilitiesTests/CMakeLists.txt index a6522d2..1537662 100644 --- a/Tests/IntegerUtilitiesTests/CMakeLists.txt +++ b/Tests/IntegerUtilitiesTests/CMakeLists.txt @@ -12,6 +12,7 @@ add_library(IntegerUtilitiesTests DoubleWidthTests.swift GCDTests.swift RotateTests.swift + SaturatingArithmeticTests.swift ShiftTests.swift) target_compile_options(IntegerUtilitiesTests PRIVATE -enable-testing) diff --git a/Tests/IntegerUtilitiesTests/SaturatingArithmeticTests.swift b/Tests/IntegerUtilitiesTests/SaturatingArithmeticTests.swift new file mode 100644 index 0000000..e4ebfaa --- /dev/null +++ b/Tests/IntegerUtilitiesTests/SaturatingArithmeticTests.swift @@ -0,0 +1,179 @@ +//===--- SaturatingArithmeticTests.swift ----------------------*- swift -*-===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2023 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +import IntegerUtilities +import XCTest +import _TestSupport + +final class IntegerUtilitiesSaturatingTests: XCTestCase { + + func testSaturatingAddSigned() { + for a in Int8.min ... Int8.max { + for b in Int8.min ... Int8.max { + let expected = Int8(clamping: Int16(a) + Int16(b)) + let observed = a.addingWithSaturation(b) + if expected != observed { + print("Error found in (\(a)).addingWithSaturation(\(b)).") + print("Expected: \(String(expected, radix: 16))") + print("Observed: \(String(observed, radix: 16))") + XCTFail() + return + } + } + } + } + + func testSaturatingSubtractSigned() { + for a in Int8.min ... Int8.max { + for b in Int8.min ... Int8.max { + let expected = Int8(clamping: Int16(a) - Int16(b)) + let observed = a.subtractingWithSaturation(b) + if expected != observed { + print("Error found in (\(a)).subtractingWithSaturation(\(b)).") + print("Expected: \(String(expected, radix: 16))") + print("Observed: \(String(observed, radix: 16))") + XCTFail() + return + } + } + } + } + + func testSaturatingNegation() { + for a in Int8.min ... Int8.max { + let expected = Int8(clamping: 0 - Int16(a)) + let observed = a.negatedWithSaturation() + if expected != observed { + print("Error found in (\(a)).negatedWithSaturation().") + print("Expected: \(String(expected, radix: 16))") + print("Observed: \(String(observed, radix: 16))") + XCTFail() + return + } + } + } + + func testSaturatingMultiplicationSigned() { + for a in Int8.min ... Int8.max { + for b in Int8.min ... Int8.max { + let expected = Int8(clamping: Int16(a) * Int16(b)) + let observed = a.multipliedWithSaturation(by: b) + if expected != observed { + print("Error found in (\(a)).multipliedWithSaturation(by: \(b)).") + print("Expected: \(String(expected, radix: 16))") + print("Observed: \(String(observed, radix: 16))") + XCTFail() + return + } + } + } + } + + func testSaturatingAddUnsigned() { + for a in UInt8.min ... UInt8.max { + for b in UInt8.min ... UInt8.max { + let expected = UInt8(clamping: UInt16(a) + UInt16(b)) + let observed = a.addingWithSaturation(b) + if expected != observed { + print("Error found in (\(a)).addingWithSaturation(\(b)).") + print("Expected: \(String(expected, radix: 16))") + print("Observed: \(String(observed, radix: 16))") + XCTFail() + return + } + } + } + } + + func testSaturatingSubtractUnsigned() { + for a in UInt8.min ... UInt8.max { + for b in UInt8.min ... UInt8.max { + let expected = UInt8(clamping: Int16(a) - Int16(b)) + let observed = a.subtractingWithSaturation(b) + if expected != observed { + print("Error found in (\(a)).subtractingWithSaturation(\(b)).") + print("Expected: \(String(expected, radix: 16))") + print("Observed: \(String(observed, radix: 16))") + XCTFail() + return + } + } + } + } + + func testSaturatingMultiplicationUnsigned() { + for a in UInt8.min ... UInt8.max { + for b in UInt8.min ... UInt8.max { + let expected = UInt8(clamping: UInt16(a) * UInt16(b)) + let observed = a.multipliedWithSaturation(by: b) + if expected != observed { + print("Error found in (\(a)).multipliedWithSaturation(by: \(b)).") + print("Expected: \(String(expected, radix: 16))") + print("Observed: \(String(observed, radix: 16))") + XCTFail() + } + } + } + } + + func testSaturatingShift( + _ value: T, _ count: C, rounding rule: RoundingRule + ) where T: FixedWidthInteger, C: FixedWidthInteger { + let observed = value.shiftedWithSaturation(leftBy: count, rounding: rule) + var expected: T = 0 + if count <= 0 { + expected = value.shifted(rightBy: -Int64(count), rounding: rule) + } else { + let multiplier: T = 1 << count + if multiplier <= 0 { + expected = value == 0 ? 0 : + value < 0 ? .min : .max + } else { + expected = value.multipliedWithSaturation(by: multiplier) + } + } + if observed != expected { + print("Error found in \(T.self).shiftedWithSaturation(leftBy: \(count), rounding: \(rule)).") + print(" Value: \(String(value, radix: 16))") + print("Expected: \(String(expected, radix: 16))") + print("Observed: \(String(observed, radix: 16))") + XCTFail() + return + } + } + + func testSaturatingShift( + _ type: T.Type, rounding rule: RoundingRule + ) { + for count in Int8.min ... .max { + testSaturatingShift(0, count, rounding: rule) + for bits in 0 ..< T.bitWidth { + let msb: T.Magnitude = 1 << bits + let value = T(truncatingIfNeeded: msb) | .random(in: 0 ... T(msb-1)) + testSaturatingShift(value, count, rounding: rule) + testSaturatingShift(0 &- value, count, rounding: rule) + } + } + } + + func testSaturatingShifts() { + testSaturatingShift(Int8.self, rounding: .toOdd) + testSaturatingShift(UInt8.self, rounding: .toOdd) + testSaturatingShift(Int.self, rounding: .toOdd) + testSaturatingShift(UInt.self, rounding: .toOdd) + } + + func testEdgeCaseForNegativeCount() { + XCTAssertEqual(1.shiftedWithSaturation(leftBy: Int.min), 0) + } + +} diff --git a/Tests/IntegerUtilitiesTests/ShiftTests.swift b/Tests/IntegerUtilitiesTests/ShiftTests.swift index 8475766..36b8185 100644 --- a/Tests/IntegerUtilitiesTests/ShiftTests.swift +++ b/Tests/IntegerUtilitiesTests/ShiftTests.swift @@ -194,55 +194,4 @@ final class IntegerUtilitiesShiftTests: XCTestCase { testStochasticAverage(DoubleWidth.random(in: .min ... .max)) testStochasticAverage(DoubleWidth.random(in: .min ... .max)) } - - func testSaturatingShift( - _ value: T, _ count: C, rounding rule: RoundingRule - ) where T: FixedWidthInteger, C: FixedWidthInteger { - let observed = value.shiftedWithSaturation(leftBy: count, rounding: rule) - var expected: T = 0 - if count <= 0 { - expected = value.shifted(rightBy: -Int64(count), rounding: rule) - } else { - let multiplier: T = 1 << count - if multiplier <= 0 { - expected = value == 0 ? 0 : - value < 0 ? .min : .max - } else { - expected = value.multipliedWithSaturation(by: multiplier) - } - } - if observed != expected { - print("Error found in \(T.self).shiftedWithSaturation(leftBy: \(count), rounding: \(rule)).") - print(" Value: \(String(value, radix: 16))") - print("Expected: \(String(expected, radix: 16))") - print("Observed: \(String(observed, radix: 16))") - XCTFail() - return - } - } - - func testSaturatingShift( - _ type: T.Type, rounding rule: RoundingRule - ) { - for count in Int8.min ... .max { - testSaturatingShift(0, count, rounding: rule) - for bits in 0 ..< T.bitWidth { - let msb: T.Magnitude = 1 << bits - let value = T(truncatingIfNeeded: msb) | .random(in: 0 ... T(msb-1)) - testSaturatingShift(value, count, rounding: rule) - testSaturatingShift(0 &- value, count, rounding: rule) - } - } - } - - func testSaturatingShifts() { - testSaturatingShift(Int8.self, rounding: .toOdd) - testSaturatingShift(UInt8.self, rounding: .toOdd) - testSaturatingShift(Int.self, rounding: .toOdd) - testSaturatingShift(UInt.self, rounding: .toOdd) - } - - func testEdgeCaseForNegativeCount() { - XCTAssertEqual(1.shiftedWithSaturation(leftBy: Int.min), 0) - } } From fe151134b05b1fdfd2d6e06f9bc085b9d60254e1 Mon Sep 17 00:00:00 2001 From: Stephen Canon Date: Thu, 27 Apr 2023 16:19:40 -0400 Subject: [PATCH 05/13] Further saturating arithmetic test and implementation cleanups --- .../SaturatingArithmetic.swift | 70 ++++++++++++------- .../IntegerUtilities/ShiftWithRounding.swift | 45 +++++++++++- .../SaturatingArithmeticTests.swift | 23 ++++-- Tests/WindowsMain.swift | 16 +++++ 4 files changed, 120 insertions(+), 34 deletions(-) diff --git a/Sources/IntegerUtilities/SaturatingArithmetic.swift b/Sources/IntegerUtilities/SaturatingArithmetic.swift index a454585..08663e0 100644 --- a/Sources/IntegerUtilities/SaturatingArithmetic.swift +++ b/Sources/IntegerUtilities/SaturatingArithmetic.swift @@ -10,8 +10,15 @@ //===----------------------------------------------------------------------===// extension FixedWidthInteger { - @_transparent @usableFromInline - var sextOrZext: Self { self >> Self.bitWidth } + /// `~0` (all-ones) if this value is negative, otherwise `0`. + /// + /// Note that if `Self` is unsigned, this always returns `0`, + /// but it is useful for writing algorithms that are generic over + /// signed and unsigned integers. + @inline(__always) @usableFromInline + var signbit: Self { + return self < .zero ? ~.zero : .zero + } /// Saturating integer addition /// @@ -29,8 +36,7 @@ extension FixedWidthInteger { @inlinable public func addingWithSaturation(_ other: Self) -> Self { let (wrapped, overflow) = addingReportingOverflow(other) - if !overflow { return wrapped } - return Self.max &- sextOrZext + return overflow ? Self.max &- signbit : wrapped } /// Saturating integer subtraction @@ -54,7 +60,7 @@ extension FixedWidthInteger { public func subtractingWithSaturation(_ other: Self) -> Self { let (wrapped, overflow) = subtractingReportingOverflow(other) if !overflow { return wrapped } - return Self.isSigned ? Self.max &- sextOrZext : 0 + return Self.isSigned ? Self.max &- signbit : 0 } /// Saturating integer negation @@ -85,10 +91,10 @@ extension FixedWidthInteger { public func multipliedWithSaturation(by other: Self) -> Self { let (high, low) = multipliedFullWidth(by: other) let wrapped = Self(truncatingIfNeeded: low) - if high == wrapped.sextOrZext { return wrapped } - return Self.max &- high.sextOrZext + if high == wrapped.signbit { return wrapped } + return Self.max &- high.signbit } - + /// Bitwise left with rounding and saturation. /// /// `self` multiplied by the rational number 2^(`count`), saturated to the @@ -102,28 +108,20 @@ extension FixedWidthInteger { /// 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 + public func shiftedWithSaturation( + leftBy count: Int, + rounding rule: RoundingRule = .down ) -> Self { - // If count is zero or negative, negate it and do a right - // shift without saturation instead, since we already have - // that implemented. + if count == 0 { return self } + // If count is negative, negate it and do a right shift without + // saturation instead, since we already have that implemented. guard count > 0 else { - // negating count is tricky, because count's type can be - // an arbitrary BinaryInteger; in particular, it could be - // .min of a signed type, so that its negation cannot be - // represented in the same type. Fortunately, Int64 is - // always big enough to represent arbitrary shifts of - // arbitrary types, so we can use that as an intermediate - // type, and then we can use negatedWithSaturation() to - // handle the .min case. - let int64Count = Int64(clamping: count) return shifted( - rightBy: int64Count.negatedWithSaturation(), + rightBy: count.negatedWithSaturation(), rounding: rule ) } - let clamped = Self.max &- sextOrZext + let clamped = Self.max &- signbit guard count < Self.bitWidth else { // If count is bitWidth or greater, we always overflow // unless self is zero. @@ -143,7 +141,27 @@ extension FixedWidthInteger { // does equal 0b0000_0000. let valueBits = Self.bitWidth &- (Self.isSigned ? 1 : 0) let wrapped = self &<< count - let complement = valueBits &- Int(count) - return self &>> complement == sextOrZext ? wrapped : clamped + let complement = valueBits &- count + return self &>> complement == signbit ? wrapped : clamped + } + + /// 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. + @_transparent + public func shiftedWithSaturation( + leftBy count: some BinaryInteger, + rounding rule: RoundingRule = .down + ) -> Self { + self.shiftedWithSaturation(leftBy: Int(clamping: count), rounding: rule) } } diff --git a/Sources/IntegerUtilities/ShiftWithRounding.swift b/Sources/IntegerUtilities/ShiftWithRounding.swift index 67ff8b9..d88dea4 100644 --- a/Sources/IntegerUtilities/ShiftWithRounding.swift +++ b/Sources/IntegerUtilities/ShiftWithRounding.swift @@ -42,8 +42,8 @@ extension BinaryInteger { /// a.shifted(rightBy: count, rounding: rule) /// a.divided(by: 1 << count, rounding: rule) @inlinable - public func shifted( - rightBy count: Count, + public func shifted( + rightBy count: Int, rounding rule: RoundingRule = .down ) -> Self { // Easiest case: count is zero or negative, so shift is always exact; @@ -61,7 +61,7 @@ extension BinaryInteger { // shifts by first shifting all but bitWidth - 1 bits with sticky // rounding, and then shifting the remaining bitWidth - 1 bits with // the desired rounding mode. - let count = count - Count(bitWidth - 1) + let count = count - (bitWidth - 1) let floor = self >> count let lost = self - (floor << count) let sticky = floor | (lost == 0 ? 0 : 1) @@ -155,4 +155,43 @@ extension BinaryInteger { return floor } } + + /// `self` divided by 2^(`count`), rounding the result according to `rule`. + /// + /// The default rounding rule is `.down`, which matches the behavior of + /// the `>>` operator from the standard library. + /// + /// Some examples of different rounding rules: + /// + /// // 3/2 is 1.5, which rounds (down by default) to 1. + /// 3.shifted(rightBy: 1) + /// + /// // 1.5 rounds up to 2. + /// 3.shifted(rightBy: 1, rounding: .up) + /// + /// // The two closest values are 1 and 2, 1 is returned because it + /// // is odd. + /// 3.shifted(rightBy: 1, rounding: .toOdd) + /// + /// // 7/2^2 = 1.75, so the result is 1 with probability 1/4, and 2 + /// // with probability 3/4. + /// 7.shifted(rightBy: 2, rounding: .stochastically) + /// + /// // 4/2^2 = 4/4 = 1, exactly. + /// 4.shifted(rightBy: 2, rounding: .trap) + /// + /// // 5/2 is 2.5, which is not exact, so this traps. + /// 5.shifted(rightBy: 1, rounding: .requireExact) + /// + /// When `Self(1) << count` is positive, the following are equivalent: + /// + /// a.shifted(rightBy: count, rounding: rule) + /// a.divided(by: 1 << count, rounding: rule) + @_transparent + public func shifted( + rightBy count: some BinaryInteger, + rounding rule: RoundingRule = .down + ) -> Self { + self.shifted(rightBy: Int(clamping: count), rounding: rule) + } } diff --git a/Tests/IntegerUtilitiesTests/SaturatingArithmeticTests.swift b/Tests/IntegerUtilitiesTests/SaturatingArithmeticTests.swift index e4ebfaa..d6a9190 100644 --- a/Tests/IntegerUtilitiesTests/SaturatingArithmeticTests.swift +++ b/Tests/IntegerUtilitiesTests/SaturatingArithmeticTests.swift @@ -32,7 +32,7 @@ final class IntegerUtilitiesSaturatingTests: XCTestCase { } } - func testSaturatingSubtractSigned() { + func testSaturatingSubSigned() { for a in Int8.min ... Int8.max { for b in Int8.min ... Int8.max { let expected = Int8(clamping: Int16(a) - Int16(b)) @@ -48,7 +48,7 @@ final class IntegerUtilitiesSaturatingTests: XCTestCase { } } - func testSaturatingNegation() { + func testSaturatingNegSigned() { for a in Int8.min ... Int8.max { let expected = Int8(clamping: 0 - Int16(a)) let observed = a.negatedWithSaturation() @@ -62,7 +62,7 @@ final class IntegerUtilitiesSaturatingTests: XCTestCase { } } - func testSaturatingMultiplicationSigned() { + func testSaturatingMulSigned() { for a in Int8.min ... Int8.max { for b in Int8.min ... Int8.max { let expected = Int8(clamping: Int16(a) * Int16(b)) @@ -94,7 +94,7 @@ final class IntegerUtilitiesSaturatingTests: XCTestCase { } } - func testSaturatingSubtractUnsigned() { + func testSaturatingSubUnsigned() { for a in UInt8.min ... UInt8.max { for b in UInt8.min ... UInt8.max { let expected = UInt8(clamping: Int16(a) - Int16(b)) @@ -110,7 +110,20 @@ final class IntegerUtilitiesSaturatingTests: XCTestCase { } } - func testSaturatingMultiplicationUnsigned() { + func testSaturatingNegUnsigned() { + for a in UInt8.min ... UInt8.max { + let observed = a.negatedWithSaturation() + if 0 != observed { + print("Error found in (\(a)).negatedWithSaturation().") + print("Expected: zero") + print("Observed: \(String(observed, radix: 16))") + XCTFail() + return + } + } + } + + func testSaturatingMulUnsigned() { for a in UInt8.min ... UInt8.max { for b in UInt8.min ... UInt8.max { let expected = UInt8(clamping: UInt16(a) * UInt16(b)) diff --git a/Tests/WindowsMain.swift b/Tests/WindowsMain.swift index 74a00d6..4c3c65b 100644 --- a/Tests/WindowsMain.swift +++ b/Tests/WindowsMain.swift @@ -119,6 +119,21 @@ extension IntegerUtilitiesRotateTests { ]) } +extension IntegerUtilitiesSaturatingTests { + static var all = testCase([ + ("testSaturatingAddSigned", IntegerUtilitiesSaturatingTests.testSaturatingAddSigned), + ("testSaturatingSubSigned", IntegerUtilitiesSaturatingTests.testSaturatingSubSigned), + ("testSaturatingNegSigned", IntegerUtilitiesSaturatingTests.testSaturatingNegSigned), + ("testSaturatingMulSigned", IntegerUtilitiesSaturatingTests.testSaturatingMulSigned), + ("testSaturatingAddUnsigned", IntegerUtilitiesSaturatingTests.testSaturatingAddUnsigned), + ("testSaturatingSubUnsigned", IntegerUtilitiesSaturatingTests.testSaturatingSubUnsigned), + ("testSaturatingNegUnsigned", IntegerUtilitiesSaturatingTests.testSaturatingNegUnsigned), + ("testSaturatingMulUnsigned", IntegerUtilitiesSaturatingTests.testSaturatingMulUnsigned), + ("testSaturatingShifts", IntegerUtilitiesSaturatingTests.testSaturatingShifts), + ("testEdgeCaseForNegativeCount", IntegerUtilitiesSaturatingTests.testEdgeCaseForNegativeCount) + ]) +} + extension IntegerUtilitiesShiftTests { static var all = testCase([ ("testRoundingShifts", IntegerUtilitiesShiftTests.testRoundingShifts), @@ -170,6 +185,7 @@ var testCases = [ IntegerUtilitiesGCDTests.all, IntegerUtilitiesRotateTests.all, IntegerUtilitiesShiftTests.all, + IntegerUtilitiesSaturatingTests.all, IntegerUtilitiesTests.DoubleWidthTests.all, ] From f7075cc79a0620ca03979caf477a268a96792752 Mon Sep 17 00:00:00 2001 From: Stephen Canon Date: Thu, 27 Apr 2023 16:27:37 -0400 Subject: [PATCH 06/13] Add a link to BinaryInteger.init(clamping:) in the section on new saturating arithmetic API. --- Sources/IntegerUtilities/README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Sources/IntegerUtilities/README.md b/Sources/IntegerUtilities/README.md index e626681..fdaab92 100644 --- a/Sources/IntegerUtilities/README.md +++ b/Sources/IntegerUtilities/README.md @@ -63,6 +63,11 @@ 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. +If you are using saturating arithmetic, you may also want to perform +saturating conversions between integer types; this functionality is provided +by the standard library via the [`init(clamping:)` API] +(https://developer.apple.com/documentation/swift/binaryinteger/init(clamping:)) + ## Types The `RoundingRule` enum is used with shift, division, and round operations to specify how to round their results to a representable value. From 8680be387bf80af2317f30fd4f38b239f6ff9b19 Mon Sep 17 00:00:00 2001 From: Stephen Canon Date: Thu, 27 Apr 2023 16:30:31 -0400 Subject: [PATCH 07/13] Update README.md --- Sources/IntegerUtilities/README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Sources/IntegerUtilities/README.md b/Sources/IntegerUtilities/README.md index fdaab92..4466d66 100644 --- a/Sources/IntegerUtilities/README.md +++ b/Sources/IntegerUtilities/README.md @@ -65,9 +65,10 @@ which performs a bitwise shift with rounding and saturation. If you are using saturating arithmetic, you may also want to perform saturating conversions between integer types; this functionality is provided -by the standard library via the [`init(clamping:)` API] -(https://developer.apple.com/documentation/swift/binaryinteger/init(clamping:)) +by the standard library via the [`init(clamping:)` API][clamping] ## Types The `RoundingRule` enum is used with shift, division, and round operations to specify how to round their results to a representable value. + +[clamping]: https://developer.apple.com/documentation/swift/binaryinteger/init(clamping:) From 58f4e72d8aa82a1e9d92a3a52d72538da527a7c9 Mon Sep 17 00:00:00 2001 From: Stephen Canon Date: Fri, 28 Apr 2023 13:33:18 -0400 Subject: [PATCH 08/13] Documentation improvements. --- Sources/IntegerUtilities/RoundingRule.swift | 97 ++++++++++++++++++- .../IntegerUtilities/ShiftWithRounding.swift | 28 +++--- 2 files changed, 108 insertions(+), 17 deletions(-) diff --git a/Sources/IntegerUtilities/RoundingRule.swift b/Sources/IntegerUtilities/RoundingRule.swift index 937ef07..687ce14 100644 --- a/Sources/IntegerUtilities/RoundingRule.swift +++ b/Sources/IntegerUtilities/RoundingRule.swift @@ -14,24 +14,84 @@ /// /// [Wikipedia](https://en.wikipedia.org/wiki/Rounding#Rounding_to_integer) /// provides a good overview of different rounding rules. +/// +/// Examples using rounding to integer to illustrate the various options: +/// ``` +/// value | down | up | towardZero | awayFromZero | +/// =======+==============+==============+==============+==============+ +/// 1.5 | 1 | 2 | 1 | 2 | +/// -------+--------------+--------------+--------------+--------------+ +/// -0.5 | -1 | 0 | 0 | -1 | +/// -------+--------------+--------------+--------------+--------------+ +/// 0.3 | 0 | 1 | 0 | 1 | +/// -------+--------------+--------------+--------------+--------------+ +/// 2 | 2 | 2 | 2 | 2 | +/// -------+--------------+--------------+--------------+--------------+ +/// +/// value | toOdd | toNearestOrAwayFromZero | toNearestOrEven | +/// =======+==============+=========================+==================+ +/// 1.5 | 1 | 2 | 2 | +/// -------+--------------+-------------------------+------------------+ +/// -0.5 | -1 | -1 | 0 | +/// -------+--------------+-------------------------+------------------+ +/// 0.3 | 1 | 0 | 0 | +/// -------+--------------+-------------------------+------------------+ +/// 2 | 2 | 2 | 2 | +/// -------+--------------+-------------------------+------------------+ +/// +/// value | stochastically | requireExact | +/// =======+=======================+================+ +/// 1.5 | 50% 1, 50% 2 | trap | +/// -------+-----------------------+----------------+ +/// -0.5 | 50% -1, 50% 0 | trap | +/// -------+-----------------------+----------------+ +/// 0.3 | 70% 0, 30% 1 | trap | +/// -------+-----------------------+----------------+ +/// 2 | 2 | 2 | +/// -------+-----------------------+----------------+ +/// ``` public enum RoundingRule { /// Produces the closest representable value that is less than or equal /// to the value being rounded. /// /// This is the default rounding mode for integer shifts, including the - /// shift operators defined in the standard library. + /// shift operators defined in the standard library. + /// + /// Examples: + /// - `(-4).divided(by: 3, rounding: .down)` is `-2`, because –2 is the + /// largest integer less than –4/3 = –1.3̅ + /// - `5.shifted(rightBy: 1, rounding: .down)` is `2`, because 2 is the + /// largest integer less than 5/2 = 2.5. case down /// Produces the closest representable value that is greater than or equal /// to the value being rounded. + /// + /// Examples: + /// - `(-4).divided(by: 3, rounding: .up)` is `-1`, because –1 is the + /// smallest integer greater than –4/3 = –1.3̅ + /// - `5.shifted(rightBy: 1, rounding: .up)` is `3`, because 3 is the + /// smallest integer greater than 5/2 = 2.5. case up /// Produces the closest representable value whose magnitude is less than /// or equal to that of the value being rounded. + /// + /// Examples: + /// - `(-4).divided(by: 3, rounding: .towardZero)` is `-1`, because –1 + /// is the closest integer to –4/3 = –1.3̅ with smaller magnitude. + /// - `5.shifted(rightBy: 1, rounding: .towardZero)` is `2`, because 2 + /// is the closest integer to 5/2 = 2.5 with smaller magnitude. case towardZero - /// Produces the closest representable value whose magnitude is greater than - /// or equal to that of the value being rounded. + /// Produces the closest representable value whose magnitude is greater + /// than or equal to that of the value being rounded. + /// + /// Examples: + /// - `(-4).divided(by: 3, rounding: .awayFromZero)` is `-2`, because –2 + /// is the closest integer to –4/3 = –1.3̅ with greater magnitude. + /// - `5.shifted(rightBy: 1, rounding: .awayFromZero)` is `3`, because 3 + /// is the closest integer to 5/2 = 2.5 with greater magnitude. case awayFromZero /// If the value being rounded is representable, that value is returned. @@ -45,16 +105,37 @@ public enum RoundingRule { /// we get is the same as if we rounded directly to p₂ in the desired mode /// so long as p₂ + 1 < p₁. Other rounding modes do not have this property, /// and admit _double roundings_ when interoperating with some modes. + /// + /// Examples: + /// - `(-4).divided(by: 3, rounding: .toOdd)` is `-1`, because –4/3 = –1.3̅ + /// is not an exact integer, and –1 is the closest odd integer. + /// - `4.shifted(rightBy: 1, rounding: .toOdd)` is `2`, + /// even though 2 is even, because 4/2 is exactly 2 and no rounding occurs. case toOdd /// Produces the representable value that is closest to the value being /// rounded. If two values are equally close, the one that has greater /// magnitude is returned. + /// + /// Examples: + /// - `(-4).divided(by: 3, rounding: .toNearestOrAwayFromZero)` + /// is `-1`, because –4/3 = –1.3̅ is closer to –1 than it is to –2. + /// + /// - `5.shifted(rightBy: 1, rounding: .toNearestOrAwayFromZero)` is `3`, + /// because 5/2 = 2.5 is equally close to 2 and 3, and 3 is further away + /// from zero. case toNearestOrAwayFromZero /// Produces the representable value that is closest to the value being /// rounded. If two values are equally close, the one whose least /// significant bit is not set is returned. + /// + /// Examples: + /// - `(-4).divided(by: 3, rounding: .toNearestOrEven)` + /// is `-1`, because –4/3 = –1.3̅ is closer to –1 than it is to –2. + /// + /// - `5.shifted(rightBy: 1, rounding: .toNearestOrEven)` is `2`, + /// because 5/2 = 2.5 is equally close to 2 and 3, and 2 is even. case toNearestOrEven /// Adds a uniform random value from [0, d) to the value being rounded, @@ -88,9 +169,19 @@ public enum RoundingRule { /// ``` /// but this isn't always possible in more sophisticated scenarios, /// and in those cases this rounding rule may be useful. + /// + /// Examples: + /// - `(-4).divided(by: 3, rounding: .stochastically)` + /// will be –1 with probability 2/3 and –2 with probability 1/3. + /// - `5.shifted(rightBy: 1, rounding: .stochastically)` + /// will be 2 with probability 1/2 and 3 with probability 1/2. case stochastically /// If the value being rounded is representable, that value is returned. /// Otherwise, a precondition failure occurs. + /// + /// Examples: + /// - `(-4).divided(by: 3, rounding: .requireExact)` will trap, + /// because –4/3 = –1.3̅ is not an integer. case requireExact } diff --git a/Sources/IntegerUtilities/ShiftWithRounding.swift b/Sources/IntegerUtilities/ShiftWithRounding.swift index d88dea4..01bf080 100644 --- a/Sources/IntegerUtilities/ShiftWithRounding.swift +++ b/Sources/IntegerUtilities/ShiftWithRounding.swift @@ -27,14 +27,14 @@ extension BinaryInteger { /// // is odd. /// 3.shifted(rightBy: 1, rounding: .toOdd) /// - /// // 7/2^2 = 1.75, so the result is 1 with probability 1/4, and 2 + /// // 7/4 = 1.75, so the result is 1 with probability 1/4, and 2 /// // with probability 3/4. /// 7.shifted(rightBy: 2, rounding: .stochastically) /// - /// // 4/2^2 = 4/4 = 1, exactly. + /// // 4/4 is exactly 1, so this does not trap. /// 4.shifted(rightBy: 2, rounding: .trap) /// - /// // 5/2 is 2.5, which is not exact, so this traps. + /// // 5/2 is 2.5, which is not an integer, so this traps. /// 5.shifted(rightBy: 1, rounding: .requireExact) /// /// When `Self(1) << count` is positive, the following are equivalent: @@ -124,18 +124,18 @@ extension BinaryInteger { return floor + Self((round + lost) >> count) case .stochastically: // TODO: it's unfortunate that we can't specify a custom random source - // for the stochastically rounding rule, but I don't see a nice way to have - // that share the API with the other rounding rules, because we'd then - // have to take the RNG in-out. The same problem applies to rounding - // with dithering. We should consider adding a stateful rounding API - // down the road to support those use cases. + // for the stochastically rounding rule, but I don't see a nice way to + // have that share the API with the other rounding rules, because we'd + // then have to take the RNG in-out. The same problem applies to + // rounding with dithering. We should consider adding a stateful + // rounding API down the road to support those use cases. // // In theory, u01 should be Self.random(in: 0 ..< onesBit), but the // random(in:) method does not exist on BinaryInteger. This is // (arguably) good, though, because there's actually no reason to - // generate large amounts of randomness just to implement stochastically - // rounding for bigints; 32b suffices for most purposes, and 64b is - // more than enough. + // generate large amounts of randomness just to implement stochastic + // rounding; 32b suffices for almost all purposes, and 64b is more + // than enough. var g = SystemRandomNumberGenerator() let u01 = g.next() if count < 64 { @@ -173,14 +173,14 @@ extension BinaryInteger { /// // is odd. /// 3.shifted(rightBy: 1, rounding: .toOdd) /// - /// // 7/2^2 = 1.75, so the result is 1 with probability 1/4, and 2 + /// // 7/4 = 1.75, so the result is 1 with probability 1/4, and 2 /// // with probability 3/4. /// 7.shifted(rightBy: 2, rounding: .stochastically) /// - /// // 4/2^2 = 4/4 = 1, exactly. + /// // 4/4 is exactly 1, so this does not trap. /// 4.shifted(rightBy: 2, rounding: .trap) /// - /// // 5/2 is 2.5, which is not exact, so this traps. + /// // 5/2 is 2.5, which is not an integer, so this traps. /// 5.shifted(rightBy: 1, rounding: .requireExact) /// /// When `Self(1) << count` is positive, the following are equivalent: From a118de987809258b1def09eda5dd30d49ae24a2b Mon Sep 17 00:00:00 2001 From: Stephen Canon Date: Fri, 28 Apr 2023 13:58:37 -0400 Subject: [PATCH 09/13] Polish README.md --- Sources/IntegerUtilities/README.md | 22 ++++++++-------------- 1 file changed, 8 insertions(+), 14 deletions(-) diff --git a/Sources/IntegerUtilities/README.md b/Sources/IntegerUtilities/README.md index 4466d66..2af9f79 100644 --- a/Sources/IntegerUtilities/README.md +++ b/Sources/IntegerUtilities/README.md @@ -37,21 +37,19 @@ 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 +### [Saturating Arithmetic][saturating] -The following saturating operations are defined as methods on -`FixedWidthInteger` types: +The following saturating operations are defined as methods on `FixedWidthInteger`: - `addingWithSaturation(_:)` - `subtractingWithSaturation(_:)` - `negatedWithSaturation(_:)` - `multipliedWithSaturation(by:)` +- `shiftedWithSaturation(leftBy:rounding:)` -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: +These implement _saturating arithmetic_. +They 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 @@ -60,15 +58,11 @@ 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. - -If you are using saturating arithmetic, you may also want to perform -saturating conversions between integer types; this functionality is provided -by the standard library via the [`init(clamping:)` API][clamping] +If you are using saturating arithmetic, you may also want to perform saturating conversions between integer types; this functionality is provided by the standard library via the [`init(clamping:)` API][clamping]. ## Types The `RoundingRule` enum is used with shift, division, and round operations to specify how to round their results to a representable value. +[saturating]: https://en.wikipedia.org/wiki/Saturation_arithmetic [clamping]: https://developer.apple.com/documentation/swift/binaryinteger/init(clamping:) From d59ec36291e01df6e0647916d75990b08becaf4d Mon Sep 17 00:00:00 2001 From: Stephen Canon Date: Fri, 28 Apr 2023 14:36:40 -0400 Subject: [PATCH 10/13] Only run benchmarks in Release, they're meaningless in Debug. --- Tests/RealTests/RelaxedArithmeticTests.swift | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/Tests/RealTests/RelaxedArithmeticTests.swift b/Tests/RealTests/RelaxedArithmeticTests.swift index a02de90..5140c9b 100644 --- a/Tests/RealTests/RelaxedArithmeticTests.swift +++ b/Tests/RealTests/RelaxedArithmeticTests.swift @@ -16,6 +16,7 @@ import _TestSupport import Accelerate #endif +#if !DEBUG func strictSum(_ array: [T]) -> T { array.reduce(0, +) } @@ -36,11 +37,7 @@ func relaxedSumOfSquares(_ array: [T]) -> T { // limitations of what XCT measure { } lets us do easily. Good enough for now. func benchmarkReduction(_ data: [Float], _ reduction: ([Float]) -> Float) { var accum: Float = 0 -#if DEBUG - let iters = 1_000 -#else let iters = 100_000 -#endif for _ in 0 ..< iters { accum += reduction(data) } @@ -129,3 +126,4 @@ final class RelaxedArithmeticTests: XCTestCase { #endif } } +#endif From ef6dbc6e78238ebedef30481101c034f04f586e2 Mon Sep 17 00:00:00 2001 From: Stephen Canon Date: Fri, 28 Apr 2023 22:29:13 -0400 Subject: [PATCH 11/13] Update Sources/IntegerUtilities/ShiftWithRounding.swift Co-authored-by: Guillaume Lessard --- Sources/IntegerUtilities/ShiftWithRounding.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/IntegerUtilities/ShiftWithRounding.swift b/Sources/IntegerUtilities/ShiftWithRounding.swift index 01bf080..721c567 100644 --- a/Sources/IntegerUtilities/ShiftWithRounding.swift +++ b/Sources/IntegerUtilities/ShiftWithRounding.swift @@ -32,7 +32,7 @@ extension BinaryInteger { /// 7.shifted(rightBy: 2, rounding: .stochastically) /// /// // 4/4 is exactly 1, so this does not trap. - /// 4.shifted(rightBy: 2, rounding: .trap) + /// 4.shifted(rightBy: 2, rounding: .requireExact) /// /// // 5/2 is 2.5, which is not an integer, so this traps. /// 5.shifted(rightBy: 1, rounding: .requireExact) From bc9f6e736893a38dc86aff502dcd056459c16716 Mon Sep 17 00:00:00 2001 From: Stephen Canon Date: Fri, 28 Apr 2023 22:29:25 -0400 Subject: [PATCH 12/13] Update Sources/IntegerUtilities/ShiftWithRounding.swift Co-authored-by: Guillaume Lessard --- Sources/IntegerUtilities/ShiftWithRounding.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/IntegerUtilities/ShiftWithRounding.swift b/Sources/IntegerUtilities/ShiftWithRounding.swift index 721c567..1adcd18 100644 --- a/Sources/IntegerUtilities/ShiftWithRounding.swift +++ b/Sources/IntegerUtilities/ShiftWithRounding.swift @@ -27,7 +27,7 @@ extension BinaryInteger { /// // is odd. /// 3.shifted(rightBy: 1, rounding: .toOdd) /// - /// // 7/4 = 1.75, so the result is 1 with probability 1/4, and 2 + /// // 7/4 = 1.75, so the result is 1 with probability 1/4, or 2 /// // with probability 3/4. /// 7.shifted(rightBy: 2, rounding: .stochastically) /// From 35e15a381f0a5f4fab33185996f5369bfc1f12b6 Mon Sep 17 00:00:00 2001 From: Stephen Canon Date: Fri, 28 Apr 2023 22:31:31 -0400 Subject: [PATCH 13/13] Additional comment fixes from Guillaume --- Sources/IntegerUtilities/ShiftWithRounding.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Sources/IntegerUtilities/ShiftWithRounding.swift b/Sources/IntegerUtilities/ShiftWithRounding.swift index 1adcd18..989a88f 100644 --- a/Sources/IntegerUtilities/ShiftWithRounding.swift +++ b/Sources/IntegerUtilities/ShiftWithRounding.swift @@ -173,12 +173,12 @@ extension BinaryInteger { /// // is odd. /// 3.shifted(rightBy: 1, rounding: .toOdd) /// - /// // 7/4 = 1.75, so the result is 1 with probability 1/4, and 2 + /// // 7/4 = 1.75, so the result is 1 with probability 1/4, or 2 /// // with probability 3/4. /// 7.shifted(rightBy: 2, rounding: .stochastically) /// /// // 4/4 is exactly 1, so this does not trap. - /// 4.shifted(rightBy: 2, rounding: .trap) + /// 4.shifted(rightBy: 2, rounding: .requireExact) /// /// // 5/2 is 2.5, which is not an integer, so this traps. /// 5.shifted(rightBy: 1, rounding: .requireExact)