mirror of
https://github.com/apple/swift-numerics
synced 2026-11-22 04:30:45 +00:00
Merge pull request #218 from stephentyrone/saturating-arithmetic
Implement saturating arithmetic on FixedWidthInteger
This commit is contained in:
10 files changed
+595
-29
No files matched your search
@@ -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})
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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,7 +36,33 @@ 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]
|
||||
|
||||
The following saturating operations are defined as methods on `FixedWidthInteger`:
|
||||
|
||||
- `addingWithSaturation(_:)`
|
||||
- `subtractingWithSaturation(_:)`
|
||||
- `negatedWithSaturation(_:)`
|
||||
- `multipliedWithSaturation(by:)`
|
||||
- `shiftedWithSaturation(leftBy:rounding:)`
|
||||
|
||||
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
|
||||
let a = x + y // traps due to overflow
|
||||
let b = x &+ y // wraps to -72
|
||||
let c = x.addingWithSaturation(y) // saturates to 127
|
||||
```
|
||||
|
||||
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:)
|
||||
@@ -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,24 +105,83 @@ 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,
|
||||
/// 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.
|
||||
///
|
||||
/// 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
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
//===--- 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 {
|
||||
/// `~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
|
||||
///
|
||||
/// `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)
|
||||
return overflow ? Self.max &- signbit : wrapped
|
||||
}
|
||||
|
||||
/// 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)
|
||||
if !overflow { return wrapped }
|
||||
return Self.isSigned ? Self.max &- signbit : 0
|
||||
}
|
||||
|
||||
/// 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)
|
||||
let wrapped = Self(truncatingIfNeeded: low)
|
||||
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
|
||||
/// 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: Int,
|
||||
rounding rule: RoundingRule = .down
|
||||
) -> Self {
|
||||
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 {
|
||||
return shifted(
|
||||
rightBy: count.negatedWithSaturation(),
|
||||
rounding: rule
|
||||
)
|
||||
}
|
||||
let clamped = Self.max &- signbit
|
||||
guard count < Self.bitWidth else {
|
||||
// If count is bitWidth or greater, we always overflow
|
||||
// unless self is zero.
|
||||
return self == 0 ? 0 : clamped
|
||||
}
|
||||
// Now we have 0 < count < bitWidth, so we can use a nice
|
||||
// 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 &- 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)
|
||||
}
|
||||
}
|
||||
@@ -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, or 2
|
||||
/// // with probability 3/4.
|
||||
/// 7.shifted(rightBy: 2, rounding: .stochastically)
|
||||
///
|
||||
/// // 4/2^2 = 4/4 = 1, exactly.
|
||||
/// 4.shifted(rightBy: 2, rounding: .trap)
|
||||
/// // 4/4 is exactly 1, so this does not trap.
|
||||
/// 4.shifted(rightBy: 2, rounding: .requireExact)
|
||||
///
|
||||
/// // 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:
|
||||
@@ -42,8 +42,8 @@ extension BinaryInteger {
|
||||
/// a.shifted(rightBy: count, rounding: rule)
|
||||
/// a.divided(by: 1 << count, rounding: rule)
|
||||
@inlinable
|
||||
public func shifted<Count: BinaryInteger>(
|
||||
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,11 +61,11 @@ 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)
|
||||
var floor = self >> count
|
||||
let count = count - (bitWidth - 1)
|
||||
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.
|
||||
@@ -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 {
|
||||
@@ -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/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: .requireExact)
|
||||
///
|
||||
/// // 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:
|
||||
///
|
||||
/// 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)
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ add_library(IntegerUtilitiesTests
|
||||
DoubleWidthTests.swift
|
||||
GCDTests.swift
|
||||
RotateTests.swift
|
||||
SaturatingArithmeticTests.swift
|
||||
ShiftTests.swift)
|
||||
target_compile_options(IntegerUtilitiesTests PRIVATE
|
||||
-enable-testing)
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
//===--- 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 testSaturatingSubSigned() {
|
||||
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 testSaturatingNegSigned() {
|
||||
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 testSaturatingMulSigned() {
|
||||
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 testSaturatingSubUnsigned() {
|
||||
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 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))
|
||||
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<T, C>(
|
||||
_ 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<T: FixedWidthInteger>(
|
||||
_ 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)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -16,9 +16,9 @@ import _TestSupport
|
||||
|
||||
final class IntegerUtilitiesShiftTests: XCTestCase {
|
||||
|
||||
func testRoundingShift<T: FixedWidthInteger>(
|
||||
_ value: T, _ count: Int, rounding rule: RoundingRule
|
||||
) {
|
||||
func testRoundingShift<T, C>(
|
||||
_ 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() {
|
||||
|
||||
@@ -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,
|
||||
]
|
||||
|
||||
|
||||
Reference in new issue
Block a user