24 Commits
Author SHA1 Message Date
Stephen Canon fa10086dc1 Merge pull request #356 from stephentyrone/oct-2026-backport-main-to-1.1
Oct 2026 backport main to 1.1
2026-10-08 11:14:17 -04:00
Stephen Canon 41d7ab5c35 Merge pull request #355 from reginaldalfret/docs/approximate-equality
docs: add dedicated documentation for ApproximateEquality
2026-10-08 10:59:00 -04:00
Stephen Canon 088fee24e1 Merge pull request #350 from pkubaj/add-freebsd-ppc64
cmake: recognize FreeBSD powerpc64le/powerpc64 in get_swift_host_arch
2026-10-08 10:56:49 -04:00
Stephen Canon 78ee55c9fc Merge pull request #328 from stephentyrone/complex-divide-docs
Added some notes on complex division.
2026-10-08 10:54:16 -04:00
Stephen Canon 162a5ae459 Merge pull request #316 from stephentyrone/enable-macos-github
Enable macos checks via github workflows.
2026-10-08 10:53:40 -04:00
Melissa Kilby 784da6559b chore: restrict GitHub workflow permissions - future-proof
Signed-off-by: Melissa Kilby <mkilby@apple.com>
2026-10-08 10:51:36 -04:00
Stephen Canon cc1ddd89a2 Merge pull request #353 from stephentyrone/1.1-backports-from-main
[1.1] backports from main
2026-09-10 11:35:46 -04:00
Stephen Canon e21bdc8ff6 Merge pull request #352 from stephentyrone/fix-cosh-sinh-signs
Fix signs of cosh and sinh near the overflow boundary.
2026-09-10 11:02:44 -04:00
Stephen Canon 0a96cd370e Merge pull request #351 from stephentyrone/recip-documentation
Relax documented behavior of Complex.reciprocal
2026-09-10 11:02:01 -04:00
Stephen Canon 0c0290ff6b Merge pull request #331 from stephentyrone/embedded-support-1.1
Cherry-pick #330 to release/1.1 branch
2025-09-25 11:22:16 -04:00
Stephen Canon cc9f8e3c5f Merge pull request #330 from ebariaux/main
Support Embedded Swift
2025-09-25 11:17:34 -04:00
Stephen Canon bbadd4b853 Merge pull request #326 from stephentyrone/wasm-testing-1.1
[1.1] enable wasm testing
2025-08-14 13:11:52 -04:00
Stephen Canon e46ddfe087 Merge pull request #325 from stephentyrone/enable-wasm-testing
Enable workflows testing for wasm.
2025-08-14 12:59:30 -04:00
Stephen Canon 1653d35461 Merge pull request #323 from stephentyrone/docc-stuff-1.1
[1.1] pull in documentation revamp from main
2025-08-14 09:36:49 -04:00
Stephen Canon 207fea2fc1 Pull documentation revamp from main into release/1.1 2025-08-13 23:18:57 -04:00
Stephen Canon c16e7a9617 Merge pull request #322 from stephentyrone/augmented-sum-assert-1.1
[1.1] Remove assert in Augmented.sum(large:small:)
2025-08-11 19:52:47 -04:00
Stephen Canon 416b94a80e Merge pull request #321 from stephentyrone/remove-2sum-assert
Remove precondition assert from Augmented.sum(large:small:)
2025-08-11 19:35:39 -04:00
Stephen Canon 1a19d0d28d Merge pull request #318 from stephentyrone/constrain-algebraic-field-1.1
[1.1] Constrain algebraic field to Magnitude: AlgebraicField
2025-08-09 12:48:26 -04:00
Stephen Canon d91884bb27 Merge pull request #315 from stephentyrone/algebraic-field-magnitude
Constrain AlgebraicField to required Magnitude:AlgebraicField
2025-08-08 17:19:36 -04:00
Stephen Canon 6bd8a0cc08 Merge pull request #317 from apple/stephentyrone-patch-1
Update README.md
2025-08-08 17:16:58 -04:00
Stephen Canon 05472f917c Update README.md
Move baseline to 1.1.0 in the how to adopt section
2025-08-08 17:16:45 -04:00
Stephen Canon 658bcd12f4 Merge pull request #313 from stephentyrone/relax-f16-x86-1.1
[1.1] Enable relaxed f16 arithmetic for x86
2025-08-08 10:07:13 -04:00
Stephen Canon b95ca135a6 Restore relaxed mul/add bindings for Float16 on x86
The ABI is stable, so these operations can be turned on.
2025-08-08 09:47:03 -04:00
Stephen Canon fd82b65b04 Create release/1.1 branch to prepare for tag.
This is a cut of main with IntegerUtilities removed; I plan to tag 1.1 with non-integer feature work from main, and 1.2 will be the first tag with IntegerUtilities.
2025-08-08 09:37:13 -04:00
29 changed files with 9 additions and 2928 deletions

No files matched your search

-1
View File
@@ -16,7 +16,6 @@ jobs:
windows_exclude_swift_versions: '[{"swift_version": "5.9"}]'
enable_wasm_sdk_build: true
wasm_sdk_build_command: swift build --target Numerics
enable_freebsd_checks: true
soundness:
name: Soundness
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@main
+1 -1
View File
@@ -7,7 +7,7 @@ Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
#]]
cmake_minimum_required(VERSION 3.29)
cmake_minimum_required(VERSION 3.16)
project(swift-numerics
LANGUAGES Swift)
+1 -16
View File
@@ -31,15 +31,9 @@ let package = Package(
exclude: excludedFilenames
),
.target(
name: "IntegerUtilities",
dependencies: [],
exclude: excludedFilenames
),
.target(
name: "Numerics",
dependencies: ["ComplexModule", "IntegerUtilities", "RealModule"],
dependencies: ["ComplexModule", "RealModule"],
exclude: excludedFilenames
),
@@ -47,9 +41,6 @@ let package = Package(
name: "RealModule",
dependencies: ["_NumericsShims"],
exclude: excludedFilenames,
swiftSettings: [
.enableExperimentalFeature("BuiltinModule")
],
linkerSettings: [
.linkedLibrary("m", .when(platforms: [.linux, .android]))
]
@@ -74,12 +65,6 @@ let package = Package(
exclude: ["CMakeLists.txt"]
),
.testTarget(
name: "IntegerUtilitiesTests",
dependencies: ["IntegerUtilities", "_TestSupport"],
exclude: ["CMakeLists.txt"]
),
.testTarget(
name: "RealTests",
dependencies: ["_TestSupport"],
+1 -2
View File
@@ -42,7 +42,7 @@ To use Swift Numerics in a SwiftPM project:
1. Add the following line to the dependencies in your `Package.swift` file:
```swift
.package(url: "https://github.com/apple/swift-numerics", from: "1.0.0"),
.package(url: "https://github.com/apple/swift-numerics", from: "1.1.0"),
```
2. Add `Numerics` as a dependency for your target:
@@ -105,7 +105,6 @@ Questions about how to use Swift Numerics modules, or issues that are not clearl
1. [`RealModule`](Sources/RealModule/README.md)
2. [`ComplexModule`](Sources/ComplexModule/README.md)
3. [`IntegerUtilities`](Sources/IntegerUtilities/README.md) (on main only, not yet present in a released tag)
## Future expansion
-1
View File
@@ -9,7 +9,6 @@ See https://swift.org/LICENSE.txt for license information
add_subdirectory(_NumericsShims)
add_subdirectory(ComplexModule)
add_subdirectory(IntegerUtilities)
add_subdirectory(Numerics)
add_subdirectory(RealModule)
if(BUILD_TESTING)
-21
View File
@@ -1,21 +0,0 @@
#[[
This source file is part of the Swift Numerics open source project
Copyright (c) 2019-2021 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
#]]
add_library(IntegerUtilities
DivideWithRounding.swift
GCD.swift
Rotate.swift
RoundingRule.swift
SaturatingArithmetic.swift
ShiftWithRounding.swift)
set_target_properties(IntegerUtilities PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
_install_target(IntegerUtilities)
set_property(GLOBAL APPEND PROPERTY SWIFT_NUMERICS_EXPORTS IntegerUtilities)
@@ -1,325 +0,0 @@
//===--- DivideWithRounding.swift -----------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2021 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 BinaryInteger {
/// `self` divided by `other`, rounding the result according to `rule`.
///
/// By default, this function uses ``RoundingRule/down``, which **is not
/// the same** as the rounding of the `/` operator from the Swift standard
/// library. They agree when the signs of the arguments match, but produce
/// different results when the quotient is negative. This behavior is
/// chosen because it generally produces a more useful remainder; in
/// particular, when the divisor is positive, the remainder is always
/// positive. To match the behavior of `/`, use ``RoundingRule/towardZero``.
///
/// Note that the remainder of division is not always representable in an
/// unsigned type if a rounding rule other than ``RoundingRule/down``,
/// ``RoundingRule/towardZero``, or ``RoundingRule/requireExact`` is
/// used. For example:
/// ```swift
/// let a: UInt = 5
/// let b: UInt = 3
/// let q = a.divided(by: b, rounding: .up) // 2
/// let r = a - b*q // 5 - 3*2 overflows UInt.
/// ```
/// For this reason, there is no `remainder(dividingBy:rounding:)`
/// operation defined on `BinaryInteger`. Signed integers do not have
/// this problem, so the `SignedInteger` protocol is extended with
/// ``SignedInteger/divided(by:rounding:)`` returning both quotient
/// and remainder.
@inlinable
public func divided(
by other: Self,
rounding rule: RoundingRule = .down
) -> Self {
// "Normal divsion" rounds toward zero, so we get self = q*other + r
// with |r| < |other| and r matching the sign of self.
let q = self / other
let r = self - q*other
// In every rounding mode, the result is the same when the result is
// exact.
if r == 0 { return q }
// From this point forward, we can assume r != 0.
//
// To get the quotient and remainder rounded as directed by rule, we
// will adjust q and r. Note that the quotient is either q-1 or q (if
// q is negative) or q or q+1 (if q is positive), because q has been
// rounded toward zero.
//
// If we subtract 1 from q, we add other to r to compensate, because:
//
// self = q*other + r
// = (q-1)*other + (r+other)
//
// Similarly, if we add 1 to q, we subtract other from r to compensate.
switch rule {
case .down:
// For rounding down, we want to have r match the sign of other
// rather than self; this means that if the signs of r and other
// disagree, we have to adjust q downward and r to match.
if other.signum() != r.signum() { return q-1 }
return q
case .up:
// For rounding up, we want to have r have the opposite sign of
// other; if not, we adjust q upward and r to match.
if other.signum() == r.signum() { return q+1 }
return q
case .towardZero:
// This is exactly what the `/` operator did for us.
return q
case .awayFromZero:
break
case .toNearestOrDown:
if r.magnitude > other.magnitude.shifted(rightBy: 1, rounding: .down) ||
2*r.magnitude == other.magnitude && other.signum() != r.signum() {
break
}
return q
case .toNearestOrUp:
if r.magnitude > other.magnitude.shifted(rightBy: 1, rounding: .down) ||
2*r.magnitude == other.magnitude && other.signum() == r.signum() {
break
}
return q
case .toNearestOrZero:
if r.magnitude <= other.magnitude.shifted(rightBy: 1, rounding: .down) {
return q
}
// Otherwise, round q away from zero.
case .toNearestOrAway:
if r.magnitude < other.magnitude.shifted(rightBy: 1, rounding: .up) {
return q
}
case .toNearestOrEven:
// First guarantee that |r| <= |other/2|; if not we have to round away
// instead, so break to do that.
if r.magnitude > other.magnitude.shifted(rightBy: 1, rounding: .down) ||
2*r.magnitude == other.magnitude && !q.isMultiple(of: 2) {
break
}
return q
case .toOdd:
// If q is already odd, we have the correct result.
if q._lowWord & 1 == 1 { return q }
case .requireExact:
preconditionFailure("Division was not exact.")
}
// We didn't have the right result, so round q away from zero.
return other.signum() == r.signum() ? q+1 : q-1
}
// 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 (should be changed
/// if/when this becomes API).
@usableFromInline
internal var _msb: Int {
// a == 0 is never used for division, because this is called
// on the divisor which cannot be zero as a precondition; if
// this becomes API, the behavior for this case will have to
// be defined.
assert(self != 0)
// Because self is non-zero, mswIndex is guaranteed to exist,
// hence force-unwrap is appropriate.
let mswIndex = words.lastIndex { $0 != 0 }!
let mswBits = UInt.bitWidth * words.distance(from: words.startIndex, to: mswIndex)
return mswBits + (UInt.bitWidth - words[mswIndex].leadingZeroBitCount - 1)
}
}
extension SignedInteger {
/// Divides `self` by `other`, rounding the quotient according to `rule`,
/// and returns the remainder.
///
/// The default rounding rule is ``RoundingRule/down``, which _is not the
/// same_ as the behavior of the `%` operator from the Swift standard
/// library, but is chosen because it generally produces a more useful
/// remainder. To match the behavior of `%`, use ``RoundingRule/towardZero``.
///
/// - Precondition: `other` cannot be zero.
@inlinable
public func remainder(
dividingBy other: Self,
rounding rule: RoundingRule = .down
) -> Self {
// Produce correct remainder for the .min/-1 case, rather than trapping.
if other == -1 { return 0 }
return self.divided(by: other, rounding: rule).remainder
}
/// Divides `self` by `other`, rounding the quotient according to `rule`,
/// and returns both the quotient and remainder.
///
/// The default rounding rule is ``RoundingRule/down``, which _is not the
/// same_ as the behavior of the `%` operator from the Swift standard
/// library, but is chosen because it generally produces a more useful
/// remainder. To match the behavior of `/`, use ``RoundingRule/towardZero``.
///
/// Because the default rounding mode does not match Swift's standard
/// library, this function is a disfavored overload of `divided(by:)`
/// instead of using the name `quotientAndRemainder(dividingBy:)`, which
/// would shadow the standard library operation and change the behavior
/// of any existing use sites. To call this method, you must explicitly
/// bind the result to a tuple:
///
/// // This calls BinaryInteger's method, which returns only
/// // the quotient.
/// let result = 5.divided(by: 3, rounding: .up) // 2
///
/// // This calls SignedInteger's method, which returns both
/// // the quotient and remainder.
/// let (q, r) = 5.divided(by: 3, rounding: .up) // (q = 2, r = -1)
@inlinable @inline(__always) @_disfavoredOverload
public func divided(
by other: Self,
rounding rule: RoundingRule = .down
) -> (quotient: Self, remainder: Self) {
// "Normal divsion" rounds toward zero, so we get self = q*other + r
// with |r| < |other| and r matching the sign of self.
let q = self / other
let r = self - q*other
// In every rounding mode, the result is the same when the result is
// exact.
if r == 0 { return (q, r) }
// From this point forward, we can assume r != 0.
//
// To get the quotient and remainder rounded as directed by rule, we
// will adjust q and r. Note that the quotient is either q-1 or q (if
// q is negative) or q or q+1 (if q is positive), because q has been
// rounded toward zero.
//
// If we subtract 1 from q, we add other to r to compensate, because:
//
// self = q*other + r
// = (q-1)*other + (r+other)
//
// Similarly, if we add 1 to q, we subtract other from r to compensate.
switch rule {
case .down:
// For rounding down, we want to have r match the sign of other
// rather than self; this means that if the signs of r and other
// disagree, we have to adjust q downward and r to match.
return other.signum() == r.signum() ? (q, r) : (q-1, r+other)
case .up:
// For rounding up, we want to have r have the opposite sign of
// other; if not, we adjust q upward and r to match.
return other.signum() == r.signum() ? (q+1, r-other) : (q, r)
case .towardZero:
// This is exactly what the `/` operator did for us.
return (q, r)
case .awayFromZero:
break
case .toNearestOrDown:
// If |r| < |other/2|, we already rounded q to nearest. If the are
// equal and q is negative, then we already broke the tie in the right
// direction. However, we don't have access to the before-rounding q,
// which may have rounded up to zero, losing the sign information, so
// we have to look at other and r instead.
if 2*r.magnitude < other.magnitude ||
2*r.magnitude == other.magnitude && other.signum() == r.signum() {
return (q, r)
}
case .toNearestOrUp:
// If |r| < |other/2|, we already rounded q to nearest. If the are
// equal and q is non-negative, then we already broke the tie in the
// right direction.
if 2*r.magnitude < other.magnitude ||
2*r.magnitude == other.magnitude && other.signum() != r.signum() {
return (q, r)
}
case .toNearestOrZero:
// Check first if |r| <= |other/2|. If this holds, we have already
// rounded q correctly. Because we're working with magnitudes, we can
// safely compute 2r without worrying about overflow, even for fixed-
// width types, because r cannot be .min (because |r| < |other| by
// construction).
if 2*r.magnitude <= other.magnitude {
return (q, r)
}
case .toNearestOrAway:
// Check first if |r| < |other/2|. If this holds, we already rounded
// q to nearest.
if 2*r.magnitude < other.magnitude {
return (q, r)
}
case .toNearestOrEven:
// If |r| < |other/2|, we already rounded q to nearest. If the are
// equal and q is even, then we already broke the tie in the right
// direction.
if 2*r.magnitude < other.magnitude ||
2*r.magnitude == other.magnitude && q.isMultiple(of: 2) {
return (q, r)
}
case .toOdd:
// If q is already odd, we have the correct result.
if q._lowWord & 1 == 1 { return (q, r) }
case .requireExact:
preconditionFailure("Division was not exact.")
}
// Fallthrough behavior is to round q away from zero and adjust r to
// match.
return other.signum() == r.signum() ? (q+1, r-other) : (q-1, r+other)
}
}
/// `a = quotient*b + remainder`, with `remainder >= 0`.
///
/// When `a` and `b` are both positive, `quotient` is `a/b` and `remainder`
/// is `a%b`.
///
/// Rounding the quotient so that the remainder is non-negative is called
/// "Euclidean division". This is not a _rounding rule_, as `quotient`
/// cannot be determined from the unrounded value `a/b`; we need to also
/// know the sign of `a` or `b` or `r` to know which way to round. Because
/// of this, is not present in the `RoundingRule` enum and uses a separate
/// API from the other division operations.
///
/// - Parameters:
/// - a: The dividend
/// - b: The divisor
///
/// - Precondition: `b` must be non-zero, and the quotient `a/b` must be
/// representable. In particular, if `T` is a signed fixed-width integer
/// type, then `euclideanDivision(T.min, -1)` will trap, because `-T.min`
/// is not representable.
///
/// - Returns: `(quotient, remainder)`, with `0 <= remainder < b.magnitude`.
public func euclideanDivision<T>(_ a: T, _ b: T) -> (quotient: T, remainder: T)
where T: SignedInteger
{
a.divided(by: b, rounding: a >= 0 ? .towardZero : .awayFromZero)
}
-40
View File
@@ -1,40 +0,0 @@
//===--- GCD.swift --------------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2021-2024 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
//
//===----------------------------------------------------------------------===//
/// The [greatest common divisor][gcd] of `a` and `b`.
///
/// If both inputs are zero, the result is zero. If one input is zero, the
/// result is the absolute value of the other input.
///
/// The result must be representable within its type. In particular, the gcd
/// of a signed, fixed-width integer type's minimum with itself (or zero)
/// cannot be represented, and results in a trap.
///
/// gcd(Int.min, Int.min) // Overflow error
/// gcd(Int.min, 0) // Overflow error
///
/// [gcd]: https://en.wikipedia.org/wiki/Greatest_common_divisor
@inlinable
public func gcd<T: BinaryInteger>(_ a: T, _ b: T) -> T {
var x = a
var y = b
if x.magnitude < y.magnitude { swap(&x, &y) }
// Avoid overflow when x = signed min, y = -1.
if y.magnitude == 1 { return 1 }
// Euclidean algorithm for GCD. It's worth using Lehmer instead for larger
// integer types, but for now this is good and dead-simple and faster than
// the other obvious choice, the binary algorithm.
while y != 0 { (x, y) = (y, x%y) }
// Try to convert result to T.
if let result = T(exactly: x.magnitude) { return result }
// If that fails, produce a diagnostic.
fatalError("GCD (\(x)) is not representable as \(T.self).")
}
-68
View File
@@ -1,68 +0,0 @@
# Integer Utilities
_Note: This module is only present on `main`, and has not yet been stabilized and released in a tag._
## Utilities defined for `BinaryInteger`
The following API are defined for all integer types:
- The `gcd(_:_:)` free function implements the _Greatest Common Divisor_ operation.
- The `shifted(rightBy:rounding:)` method implements _bitwise shift with rounding_.
- The `divided(by:rounding:)` method implements division with specified rounding.
(See also `SignedInteger.divided(by:rounding:)`, `remainder(dividingBy:rounding:)`, and `euclideanDivision(_:_:)` below).
## Utilities defined for `SignedInteger`
The following API are defined for signed integer types:
- The `divided(by:rounding:)` method implementing division with specified rounding, returning both quotient and remainder.
This requires a signed type because the remainder is not generally representable for unsigned types.
This is a disfavored overload; by default, you will get only the quotient as the result:
```
let p = 5.divided(by: 3, rounding: .up) // p = 2
let (q, r) = 5.divided(by: 3, rounding: .up) // q = 2, r = -1
```
- The `remainder(dividingBy:rounding:)` method implementing the remainder operation; the `rounding` argument describes how to round the _quotient_, which is not returned.
(The remainder is always exact, and hence is not rounded).
- The `euclideanDivision(_:_:)` free function implements _Euclidean division_.
In this operation, the remainder is chosen to always be non-negative.
This does not correspond to any rounding rule on the quotient, which is why it uses a distinct API.
## Utilities defined for `FixedWidthInteger`
- 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:)
-43
View File
@@ -1,43 +0,0 @@
//===--- Rotate.swift -----------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2021 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
internal func rotateImplementation(right count: Int) -> Self {
// We don't have an unsigned right shift operation for signed values, so
// we need to convert to an unsigned type. The only unsigned type that's
// guaranteed to be able to represent the bit pattern of any Self value
// is Magnitude. It would be possible to have Magnitude be _wider_ than
// Self, but that's OK as long as we're careful to complement the shift
// count using Self.bitWidth and not Magnitude.bitWidth or zero.
let bitPattern = Magnitude(truncatingIfNeeded: self)
let countComplement = Self.bitWidth &- count
return Self(truncatingIfNeeded:
bitPattern &>> count | bitPattern &<< countComplement
)
}
/// `self` rotated bitwise right by `count` bits.
///
/// Equivalent to `rotated(left: 0 &- count)`.
@inlinable
public func rotated<Count: BinaryInteger>(right count: Count) -> Self {
rotateImplementation(right: Int(truncatingIfNeeded: count))
}
/// `self` rotated bitwise left by `count` bits.
///
/// Equivalent to `rotated(right: 0 &- count)`.
@inlinable
public func rotated<Count: BinaryInteger>(left count: Count) -> Self {
rotateImplementation(right: 0 &- Int(truncatingIfNeeded: count))
}
}
-266
View File
@@ -1,266 +0,0 @@
//===--- RoundingRule.swift -----------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2021-2025 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
//
//===----------------------------------------------------------------------===//
/// A rule that defines how to select one of the two representable results
/// closest to a given value.
///
/// [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:
/// ```
/// Directed rounding rules
///
/// value | down | up | towardZero | awayFromZero |
/// =======+==============+==============+==============+==============+
/// -1.5 | -2 | -1 | -1 | -2 |
/// -------+--------------+--------------+--------------+--------------+
/// -0.5 | -1 | 0 | 0 | -1 |
/// -------+--------------+--------------+--------------+--------------+
/// 0.5 | 0 | 1 | 0 | 1 |
/// -------+--------------+--------------+--------------+--------------+
/// 0.7 | 0 | 1 | 0 | 1 |
/// -------+--------------+--------------+--------------+--------------+
/// 1.2 | 1 | 2 | 1 | 2 |
/// -------+--------------+--------------+--------------+--------------+
/// 2.0 | 2 | 2 | 2 | 2 |
/// -------+--------------+--------------+--------------+--------------+
///
/// toNearestOr... rounding rules
///
/// value | orDown | orUp | orZero | orAway | orEven |
/// =======+==========+==========+==========+==========+==========+
/// -1.5 | -2 | -1 | -1 | -2 | -2 |
/// -------+----------+----------+----------+----------+----------+
/// -0.5 | -1 | 0 | 0 | -1 | 0 |
/// -------+----------+----------+----------+----------+----------+
/// 0.5 | 0 | 1 | 0 | 1 | 0 |
/// -------+----------+----------+----------+----------+----------+
/// 0.7 | 1 | 1 | 1 | 1 | 1 |
/// -------+----------+----------+----------+----------+----------+
/// 1.2 | 1 | 1 | 1 | 1 | 1 |
/// -------+----------+----------+----------+----------+----------+
/// 2.0 | 2 | 2 | 2 | 2 | 2 |
/// -------+----------+----------+----------+----------+----------+
///
/// Specialized rounding rules
///
/// value | toOdd | requireExact |
/// =======+==============+================+
/// -1.5 | -1 | trap |
/// -------+--------------+----------------+
/// -0.5 | -1 | trap |
/// -------+--------------+----------------+
/// 0.5 | 1 | trap |
/// -------+--------------+----------------+
/// 0.7 | 1 | trap |
/// -------+--------------+----------------+
/// 1.2 | 1 | trap |
/// -------+--------------+----------------+
/// 2.0 | 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.
///
/// 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.
///
/// 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.
/// Otherwise, whichever of the two closest representable values has its
/// least significant bit set is returned.
///
/// This is also called _sticky rounding_, and it is useful as an
/// implementation detail because it has the property that if we do
/// rounding in two steps, first to intermediate precision p₁ with .toOdd,
/// then to the final precision p₂ with any other rounding mode, the result
/// 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 is less than
/// the value being rounded is chosen.
///
/// Examples:
/// - `(-4).divided(by: 3, rounding: .toNearestOrDown)`
/// is `-1`, because –4/3 = –1.3̅ is closer to –1 than it is to –2.
///
/// - `5.shifted(rightBy: 1, rounding: .toNearestOrDown)` is `2`,
/// because 5/2 = 2.5 is equally close to 2 and 3, and 2 is less.
case toNearestOrDown
/// Produces the representable value that is closest to the value being
/// rounded. If two values are equally close, the one that is greater than
/// the value being rounded is chosen.
///
/// Examples:
/// - `(-4).divided(by: 3, rounding: .toNearestOrUp)`
/// is `-1`, because –4/3 = –1.3̅ is closer to –1 than it is to –2.
///
/// - `5.shifted(rightBy: 1, rounding: .toNearestOrUp)` is `3`,
/// because 5/2 = 2.5 is equally close to 2 and 3, and 3 is greater.
case toNearestOrUp
/// Produces the representable value that is closest to the value being
/// rounded. If two values are equally close, the one that has smaller
/// magnitude is returned.
///
/// Examples:
/// - `(-4).divided(by: 3, rounding: .toNearestOrZero)`
/// is `-1`, because –4/3 = –1.3̅ is closer to –1 than it is to –2.
///
/// - `5.shifted(rightBy: 1, rounding: .toNearestOrZero)` is `2`,
/// because 5/2 = 2.5 is equally close to 2 and 3, and 2 is closer to zero.
case toNearestOrZero
/// 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: .toNearestOrAway)`
/// is `-1`, because –4/3 = –1.3̅ is closer to –1 than it is to –2.
///
/// - `5.shifted(rightBy: 1, rounding: .toNearestOrAway)` is `3`,
/// because 5/2 = 2.5 is equally close to 2 and 3, and 3 is further away
/// from zero.
case toNearestOrAway
/// 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
/// 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
}
extension RoundingRule {
/// 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.
///
/// > Deprecated: Use `.toNearestOrAway` instead.
@inlinable
@available(*, deprecated, renamed: "toNearestOrAway")
public static var toNearestOrAwayFromZero: Self { .toNearestOrAway }
}
extension FloatingPoint {
/// `self` rounded to integer according to `rule`.
///
/// This mirrors the standard library `rounded` API, providing access to
/// the expanded set of rounding rules defined in IntegerUtilities. It is
/// not just a shadow because that would lead to ambiguity errors in
/// existing code that uses the shortened `rounded(.down)` form.
@inlinable @inline(__always)
public func rounding(_ rule: RoundingRule) -> Self {
switch rule {
case .down:
return rounded(.down)
case .up:
return rounded(.up)
case .towardZero:
return rounded(.towardZero)
case .awayFromZero:
return rounded(.awayFromZero)
case .toNearestOrDown:
// FP doesn't have toNearestOrDown, so round toNearestOrEven and fixup
// any exact-halfway cases.
let nearest = rounded(.toNearestOrEven)
return nearest - self == 1/2 ? rounded(.down) : nearest
case .toNearestOrUp:
// FP doesn't have toNearestOrUp, so round toNearestOrEven and fixup
// any exact-halfway cases.
let nearest = rounded(.toNearestOrEven)
return self - nearest == 1/2 ? rounded(.up) : nearest
case .toNearestOrZero:
// FP doesn't have toNearestOrZero, so round toNearestOrEven and fixup
// any exact-halfway cases.
let nearest = rounded(.toNearestOrEven)
return (self - nearest).magnitude == 1/2 ? rounded(.towardZero) : nearest
case .toNearestOrAway:
return self.rounded(.toNearestOrAwayFromZero)
case .toNearestOrEven:
return self.rounded(.toNearestOrEven)
case .toOdd:
let trunc = rounded(.towardZero)
if trunc == self { return trunc }
let one = Self(signOf: self, magnitudeOf: 1)
// We have eliminated all large values at this point; add ±0.5, and see
// which way that rounds, then select the other value.
let even = (trunc + one/2).rounded(.toNearestOrEven)
return trunc == even ? trunc + one : trunc
case .requireExact:
let trunc = rounded(.towardZero)
precondition(isInfinite || trunc == self, "\(self) is not an exact integer.")
return self
}
}
}
@@ -1,167 +0,0 @@
//===--- 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)
/// ```
///
/// If the "normal addition" `self + other` does not trap,
/// this method 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.
///
/// If the "normal subtraction" `self - other` does not trap,
/// this method 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)
/// ```
///
/// If the "normal multiplication" `self * other` does not trap,
/// this method 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 shift 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:)`, defined on `BinaryInteger`, 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<Count: BinaryInteger>(
leftBy count: Count,
rounding rule: RoundingRule = .down
) -> Self {
self.shiftedWithSaturation(leftBy: Int(clamping: count), rounding: rule)
}
}
@@ -1,175 +0,0 @@
//===--- ShiftWithRounding.swift ------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2021 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 BinaryInteger {
/// `self` divided by 2^(`count`), rounding the result according to `rule`.
///
/// The default rounding rule is ``RoundingRule/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)
///
/// // 6/4 = 1.5, so the tie is broken in favor of the even value 2.
/// 6.shifted(rightBy: 2, rounding: .toNearestOrEven)
///
/// // 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)
@inlinable
public func shifted(
rightBy count: Int,
rounding rule: RoundingRule = .down
) -> Self {
// Easiest case: count is zero or negative, so shift is always exact;
// delegate to the normal >> operator.
if count <= 0 { return self >> count }
if count >= bitWidth {
// Note: what follows would cause an infinite loop if bitWidth <= 1.
// This will essentially never happen, but in the highly unlikely event
// that we encounter such a case, we promote to Int8, do the shift, and
// then convert back to the appropriate result type.
if bitWidth <= 1 {
return Self(Int8(self).shifted(rightBy: count, rounding: rule))
}
// That pathological case taken care of, we can now handle over-wide
// 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 - (bitWidth - 1)
let floor = self >> count
let lost = self - (floor << count)
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.
//
// TODO: If we were really, really careful about overflow, some of these
// could be made simpler. E.g. mathematically round up is implemented here
// via:
//
// floor = self >> count
// mask = 1 << count - 1
// lost = self & mask
// return floor + (lost == 0 ? 0 : 1)
//
// _if_ we didn't have to worry about intermediate overflow (either because
// self is bounded away from .max or because we don't have a fixed-width
// type), then we could use the following instead:
//
// mask = 1 << count - 1
// return (self + mask) >> count
//
// However, self + mask can overflow, e.g. if we're shifting .max by 1:
//
// mask = 1 << 1 - 1 = 1
// self + mask = .max + 1 // uh-oh
//
// This cannot occur for arbitrary-precision numbers, so we could use
// the simpler expressions for those (but those are precisely the cases
// where performance of rounding does not matter much, because shifts
// get swamped by even basic arithmetic). More interesting, we could
// promote fixed-width numbers to a wider type, preventing this
// intermediate overflow and allowing us to use the simpler expressions
// much of the time. We could also explicitly _detect_ the overflow if
// it happens and patch up the result, though this is a little bit tricky
// because addingReportingOverflow and friends do not exist on
// BinaryInteger. Hence, this is a TODO for the future.
let mask = Magnitude(1) << count - 1
let lost = Magnitude(truncatingIfNeeded: self) & mask
let floor = self >> count
let ceiling = floor + (lost == 0 ? 0 : 1)
let half: Magnitude = (1 as Magnitude) << (count &- 1)
switch rule {
case .down:
return floor
case .up:
return ceiling
case .towardZero:
return self > 0 ? floor : ceiling
case .awayFromZero:
return self < 0 ? floor : ceiling
case .toNearestOrDown:
return floor + Self((lost + (half - 1)) >> count)
case .toNearestOrUp:
return floor + Self((lost + half) >> count)
case .toNearestOrZero:
let round = half - (self < 0 ? 0 : 1)
return floor + Self((round + lost) >> count)
case .toNearestOrAway:
let round = half - (self > 0 ? 0 : 1)
return floor + Self((round + lost) >> count)
case .toNearestOrEven:
let round = mask >> 1 + Magnitude(floor & 1)
return floor + Self((round + lost) >> count)
case .toOdd:
return floor | (lost == 0 ? 0 : 1)
case .requireExact:
precondition(lost == 0, "shift was not exact.")
return floor
}
}
/// `self` divided by 2^(`count`), rounding the result according to `rule`.
///
/// The default rounding rule is ``RoundingRule/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)
///
/// // 6/4 = 1.5, so the tie is broken in favor of the even value 2.
/// 6.shifted(rightBy: 2, rounding: .toNearestOrEven)
///
/// // 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<Count: BinaryInteger>(
rightBy count: Count,
rounding rule: RoundingRule = .down
) -> Self {
self.shifted(rightBy: Int(clamping: count), rounding: rule)
}
}
-1
View File
@@ -20,7 +20,6 @@ target_compile_options(Numerics PUBLIC
-Xfrontend -validate-tbd-against-ir=none)
target_link_libraries(Numerics PUBLIC
ComplexModule
IntegerUtilities
RealModule)
-1
View File
@@ -11,5 +11,4 @@
// A module that re-exports the complete Swift Numerics public API.
@_exported import ComplexModule
@_exported import IntegerUtilities
@_exported import RealModule
+4 -5
View File
@@ -109,11 +109,10 @@ extension Augmented {
/// error from that computation rounded to the closest representable
/// value.
///
/// The magnitude of the summands does not change the result of this
/// operation. If you know statically that `a.magnitude >= b.magnitude`,
/// you may want to consider using ``sum(large:small:)`` to get the same
/// result somewhat more efficiently. If you do not have such a static
/// bound, you usually want to use this function instead.
/// Unlike ``sum(large:small:)``, the magnitude of the summands does not
/// matter. If you know statically that `a.magnitude >= b.magnitude`, you
/// should use ``sum(large:small:)``. If you do not have such a static
/// bound, you should use this function instead.
///
/// Unlike ``product(_:_:)``, the rounding error of `sum` never underflows.
///
-9
View File
@@ -10,7 +10,6 @@
//===----------------------------------------------------------------------===//
import _NumericsShims
import Builtin
extension Double: Real {
@_transparent
@@ -223,19 +222,11 @@ extension Double: Real {
@_transparent
public static func _relaxedAdd(_ a: Double, _ b: Double) -> Double {
#if hasFeature(BuiltinRelaxedFP) // Swift 6.5 and later
Double(Builtin.fadd_relaxed_FPIEEE64(a._value, b._value))
#else
_numerics_relaxed_add(a, b)
#endif
}
@_transparent
public static func _relaxedMul(_ a: Double, _ b: Double) -> Double {
#if hasFeature(BuiltinRelaxedFP) // Swift 6.5 and later
Double(Builtin.fmul_relaxed_FPIEEE64(a._value, b._value))
#else
_numerics_relaxed_mul(a, b)
#endif
}
}
-9
View File
@@ -10,7 +10,6 @@
//===----------------------------------------------------------------------===//
import _NumericsShims
import Builtin
extension Float: Real {
@_transparent
@@ -196,19 +195,11 @@ extension Float: Real {
@_transparent
public static func _relaxedAdd(_ a: Float, _ b: Float) -> Float {
#if hasFeature(BuiltinRelaxedFP) // Swift 6.5 and later
Float(Builtin.fadd_relaxed_FPIEEE32(a._value, b._value))
#else
_numerics_relaxed_addf(a, b)
#endif
}
@_transparent
public static func _relaxedMul(_ a: Float, _ b: Float) -> Float {
#if hasFeature(BuiltinRelaxedFP) // Swift 6.5 and later
Float(Builtin.fmul_relaxed_FPIEEE32(a._value, b._value))
#else
_numerics_relaxed_mulf(a, b)
#endif
}
}
+2 -12
View File
@@ -10,7 +10,6 @@
//===----------------------------------------------------------------------===//
import _NumericsShims
import Builtin
// Float16 is only available on macOS when targeting arm64.
#if !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))
@@ -174,27 +173,18 @@ extension Float16: Real {
}
#endif
#if !arch(wasm32) || hasFeature(BuiltinRelaxedFP)
#if !arch(wasm32)
// WASM doesn't have _Float16 on the C side, so we can't define the C hooks
// that these use. However, if we have BuiltinRelaxedFP we can use builtins
// to do this directly without needing the C hooks.
// that these use. TODO: implement these as Swift builtins instead.
@_transparent
public static func _relaxedAdd(_ a: Float16, _ b: Float16) -> Float16 {
#if hasFeature(BuiltinRelaxedFP) // Swift 6.5 and later
Float16(Builtin.fadd_relaxed_FPIEEE16(a._value, b._value))
#else
_numerics_relaxed_addf16(a, b)
#endif
}
@_transparent
public static func _relaxedMul(_ a: Float16, _ b: Float16) -> Float16 {
#if hasFeature(BuiltinRelaxedFP) // Swift 6.5 and later
Float16(Builtin.fmul_relaxed_FPIEEE16(a._value, b._value))
#else
_numerics_relaxed_mulf16(a, b)
#endif
}
#endif
}
-9
View File
@@ -10,7 +10,6 @@
//===----------------------------------------------------------------------===//
import _NumericsShims
import Builtin
// Restrict extension to platforms for which Float80 exists.
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
@@ -169,20 +168,12 @@ extension Float80: Real {
@_transparent
public static func _relaxedAdd(_ a: Float80, _ b: Float80) -> Float80 {
#if hasFeature(BuiltinRelaxedFP) // Swift 6.5 and later
Float80(Builtin.fadd_relaxed_FPIEEE80(a._value, b._value))
#else
_numerics_relaxed_addl(a, b)
#endif
}
@_transparent
public static func _relaxedMul(_ a: Float80, _ b: Float80) -> Float80 {
#if hasFeature(BuiltinRelaxedFP) // Swift 6.5 and later
Float80(Builtin.fmul_relaxed_FPIEEE80(a._value, b._value))
#else
_numerics_relaxed_mull(a, b)
#endif
}
}
#endif
@@ -1,23 +0,0 @@
#[[
This source file is part of the Swift Numerics open source project
Copyright (c) 2019-2021 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
#]]
add_library(IntegerUtilitiesTests
DivideTests.swift
DoubleWidthTests.swift
GCDTests.swift
RotateTests.swift
SaturatingArithmeticTests.swift
ShiftTests.swift)
target_compile_options(IntegerUtilitiesTests PRIVATE
-enable-testing)
target_link_libraries(IntegerUtilitiesTests PUBLIC
$<$<NOT:$<PLATFORM_ID:Darwin>>:Foundation>
Numerics
_TestSupport
XCTest)
@@ -1,484 +0,0 @@
//===--- DivideTests.swift ------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2021 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
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import IntegerUtilities
import _TestSupport
import XCTest
final class IntegerUtilitiesDivideTests: XCTestCase {
func divisionRuleHolds<T: BinaryInteger>(_ a: T, _ b: T, _ q: T, _ r: T) -> Bool {
// Validate division rule holds: a = qb + r (have to be careful about
// computing qb, though, to ensure it does not overflow due to
// rounding of q; compute it in two pieces, subtracting the first from
// a to avoid intermediate overflow).
let b1 = b >> 1
let b2 = b - b1
let ref = a - q*b1 - q*b2
if r != ref {
XCTFail("""
\(a).divided(by: \(b)) failed the division rule.
a - qb was \(ref), but r is \(r).
""")
return false
}
if r.magnitude >= b.magnitude {
XCTFail("""
\(a).divided(by: \(b)) failed check on r.
|remainder| must be smaller than |divisor|, but was \(r).
""")
return false
}
return true
}
func testDivideDown<T: SignedInteger & FixedWidthInteger>(_ values: [T]) {
for a in values {
for b in values where b != 0 {
// Skip any SignedInt.min / -1 cases, because those will trap.
if a == .min && b == -1 { continue }
let (q, r) = a.divided(by: b, rounding: .down)
let justq = a.divided(by: b, rounding: .down)
if q != justq {
XCTFail("""
\(a).divided(by: \(b), rounding: .down) failed check:
BinaryInteger overload did not produce the same quotient as SignedInteger.
BinaryInteger result was \(justq), but SignedInteger was \(q).
""")
return
}
if divisionRuleHolds(a, b, q, r) {
// We know a = bq + r with |r| < |b|. Now validate sign(r) == sign(b).
guard r == 0 || r.signum() == b.signum() else {
XCTFail("""
\(a).divided(by: \(b), rounding: .down) failed check on r.
remainder must match sign of divisor, but was \(r).
""")
return
}
}
}
}
}
func testDivideUp<T: SignedInteger & FixedWidthInteger>(_ values: [T]) {
for a in values {
for b in values where b != 0 {
// Skip any SignedInt.min / -1 cases, because those will trap.
if a == .min && b == -1 { continue }
let (q, r) = a.divided(by: b, rounding: .up)
let justq = a.divided(by: b, rounding: .up)
if q != justq {
XCTFail("""
\(a).divided(by: \(b), rounding: .up) failed check:
BinaryInteger overload did not produce the same quotient as SignedInteger.
BinaryInteger result was \(justq), but SignedInteger was \(q).
""")
return
}
if divisionRuleHolds(a, b, q, r) {
// We know a = bq + r with |r| < |b|. Now validate sign(r) != sign(b).
guard r == 0 || r.signum() != b.signum() else {
XCTFail("""
\(a).divided(by: \(b), rounding: .up) failed check on r.
remainder must oppose sign of divisor, but was \(r).
""")
return
}
}
}
}
}
func testDivideTowardZero<T: SignedInteger & FixedWidthInteger>(_ values: [T]) {
for a in values {
for b in values where b != 0 {
// Skip any SignedInt.min / -1 cases, because those will trap.
if a == .min && b == -1 { continue }
let (q, r) = a.divided(by: b, rounding: .towardZero)
let justq = a.divided(by: b, rounding: .towardZero)
if q != justq {
XCTFail("""
\(a).divided(by: \(b), rounding: .towardZero) failed check:
BinaryInteger overload did not produce the same quotient as SignedInteger.
BinaryInteger result was \(justq), but SignedInteger was \(q).
""")
return
}
if divisionRuleHolds(a, b, q, r) {
// We know a = bq + r with |r| < |b|. Now validate sign(r) == sign(a).
guard r == 0 || r.signum() == a.signum() else {
XCTFail("""
\(a).divided(by: \(b), rounding: .towardZero) failed check on r.
remainder must match sign of dividend, but was \(r).
""")
return
}
}
}
}
}
func testDivideAwayFromZero<T: SignedInteger & FixedWidthInteger>(_ values: [T]) {
for a in values {
for b in values where b != 0 {
// Skip any SignedInt.min / -1 cases, because those will trap.
if a == .min && b == -1 { continue }
let (q, r) = a.divided(by: b, rounding: .awayFromZero)
let justq = a.divided(by: b, rounding: .awayFromZero)
if q != justq {
XCTFail("""
\(a).divided(by: \(b), rounding: .awayFromZero) failed check:
BinaryInteger overload did not produce the same quotient as SignedInteger.
BinaryInteger result was \(justq), but SignedInteger was \(q).
""")
return
}
if divisionRuleHolds(a, b, q, r) {
// We know a = bq + r with |r| < |b|. Now validate sign(r) != sign(a).
guard r == 0 || r.signum() != a.signum() else {
XCTFail("""
\(a).divided(by: \(b), rounding: .awayFromZero) failed check on r.
remainder must oppose sign of dividend, but was \(r).
""")
return
}
}
}
}
}
func testDivideToNearestOrDown<T: SignedInteger & FixedWidthInteger>(_ values: [T]) {
for a in values {
for b in values where b != 0 {
// Skip any SignedInt.min / -1 cases, because those will trap.
if a == .min && b == -1 { continue }
let (q, r) = a.divided(by: b, rounding: .toNearestOrDown)
let justq = a.divided(by: b, rounding: .toNearestOrDown)
if q != justq {
XCTFail("""
\(a).divided(by: \(b), rounding: .toNearestOrDown) failed check:
BinaryInteger overload did not produce the same quotient as SignedInteger.
BinaryInteger result was \(justq), but SignedInteger was \(q).
""")
return
}
XCTAssertEqual(q, justq)
if divisionRuleHolds(a, b, q, r) {
// We know a = bq + r with |r| < |b|. Now check |r| <= |b|/2
// with equality only if q rounded down.
if 2*r.magnitude > b.magnitude {
XCTFail("""
\(a).divided(by: \(b), rounding: .toNearestOrDown) failed check:
|remainder| must be less than or equal to |divisor|/2, but remainder was \(r).
""")
return
}
if 2*r.magnitude == b.magnitude && r.signum() != b.signum() {
XCTFail("""
\(a).divided(by: \(b), rounding: .toNearestOrDown) failed check:
If |remainder| equals |divisor|/2, remainder must have same sign as divisor, but was \(r).
""")
return
}
}
}
}
}
func testDivideToNearestOrUp<T: SignedInteger & FixedWidthInteger>(_ values: [T]) {
for a in values {
for b in values where b != 0 {
// Skip any SignedInt.min / -1 cases, because those will trap.
if a == .min && b == -1 { continue }
let (q, r) = a.divided(by: b, rounding: .toNearestOrUp)
let justq = a.divided(by: b, rounding: .toNearestOrUp)
if q != justq {
XCTFail("""
\(a).divided(by: \(b), rounding: .toNearestOrUp) failed check:
BinaryInteger overload did not produce the same quotient as SignedInteger.
BinaryInteger result was \(justq), but SignedInteger was \(q).
""")
return
}
if divisionRuleHolds(a, b, q, r) {
// We know a = bq + r with |r| < |b|. Now check |r| <= |b|/2
// with equality only if q rounded up.
if 2*r.magnitude > b.magnitude {
XCTFail("""
\(a).divided(by: \(b), rounding: .toNearestOrUp) failed check:
|remainder| must be less than or equal to |divisor|/2, but remainder was \(r).
""")
return
}
if 2*r.magnitude == b.magnitude && r.signum() == b.signum() {
XCTFail("""
\(a).divided(by: \(b), rounding: .toNearestOrUp) failed check:
If |remainder| equals |divisor|/2, remainder must have opposite sign of divisor, but was \(r).
""")
return
}
}
}
}
}
func testDivideToNearestOrZero<T: SignedInteger & FixedWidthInteger>(_ values: [T]) {
for a in values {
for b in values where b != 0 {
// Skip any SignedInt.min / -1 cases, because those will trap.
if a == .min && b == -1 { continue }
let (q, r) = a.divided(by: b, rounding: .toNearestOrZero)
let justq = a.divided(by: b, rounding: .toNearestOrZero)
if q != justq {
XCTFail("""
\(a).divided(by: \(b), rounding: .toNearestOrZero) failed check:
BinaryInteger overload did not produce the same quotient as SignedInteger.
BinaryInteger result was \(justq), but SignedInteger was \(q).
""")
return
}
if divisionRuleHolds(a, b, q, r) {
// We know a = bq + r with |r| < |b|. Now check |r| <= |b|/2
// with equality only if sign(r) == sign(a).
if 2*r.magnitude > b.magnitude {
XCTFail("""
\(a).divided(by: \(b), rounding: .toNearestOrZero) failed check:
|remainder| must be less than or equal to |divisor|/2, but remainder was \(r).
""")
return
}
if 2*r.magnitude == b.magnitude && r.signum() != a.signum() {
XCTFail("""
\(a).divided(by: \(b), rounding: .toNearestOrZero) failed check:
If |remainder| equals |divisor|/2, remainder must match sign of dividend, but was \(r).
""")
return
}
}
}
}
}
func testDivideToNearestOrAway<T: SignedInteger & FixedWidthInteger>(_ values: [T]) {
for a in values {
for b in values where b != 0 {
// Skip any SignedInt.min / -1 cases, because those will trap.
if a == .min && b == -1 { continue }
let (q, r) = a.divided(by: b, rounding: .toNearestOrAway)
let justq = a.divided(by: b, rounding: .toNearestOrAway)
if q != justq {
XCTFail("""
\(a).divided(by: \(b), rounding: .toNearestOrAway) failed check:
BinaryInteger overload did not produce the same quotient as SignedInteger.
BinaryInteger result was \(justq), but SignedInteger was \(q).
""")
return
}
if divisionRuleHolds(a, b, q, r) {
// We know a = bq + r with |r| < |b|. Now check |r| <= |b|/2
// with equality only if sign(r) != sign(a).
if 2*r.magnitude > b.magnitude {
XCTFail("""
\(a).divided(by: \(b), rounding: .toNearestOrAway) failed check:
|remainder| must be less than or equal to |divisor|/2, but remainder was \(r).
""")
return
}
if 2*r.magnitude == b.magnitude && r.signum() == a.signum() {
XCTFail("""
\(a).divided(by: \(b), rounding: .toNearestOrAway) failed check:
If |remainder| equals |divisor|/2, remainder must oppose sign of dividend, but was \(r).
""")
return
}
}
}
}
}
func testDivideToNearestOrEven<T: SignedInteger & FixedWidthInteger>(_ values: [T]) {
for a in values {
for b in values where b != 0 {
// Skip any SignedInt.min / -1 cases, because those will trap.
if a == .min && b == -1 { continue }
let (q, r) = a.divided(by: b, rounding: .toNearestOrEven)
let justq = a.divided(by: b, rounding: .toNearestOrEven)
if q != justq {
XCTFail("""
\(a).divided(by: \(b), rounding: .toNearestOrEven) failed check:
BinaryInteger overload did not produce the same quotient as SignedInteger.
BinaryInteger result was \(justq), but SignedInteger was \(q).
""")
return
}
if divisionRuleHolds(a, b, q, r) {
// We know a = bq + r with |r| < |b|. Now check |r| <= |b|/2
// with equality only if q is even.
if 2*r.magnitude > b.magnitude {
XCTFail("""
\(a).divided(by: \(b), rounding: .toNearestOrEven) failed check:
|remainder| must be less than or equal to |divisor|/2, but remainder was \(r).
""")
return
}
if 2*r.magnitude == b.magnitude && q & 1 == 1 {
XCTFail("""
\(a).divided(by: \(b), rounding: .toNearestOrEven) failed check:
If |remainder| equals |divisor|/2, quotient must be even, but quotient was \(q) and remainder was \(r).
""")
return
}
}
}
}
}
func testDivideToOdd<T: SignedInteger & FixedWidthInteger>(_ values: [T]) {
for a in values {
for b in values where b != 0 {
// Skip any SignedInt.min / -1 cases, because those will trap.
if a == .min && b == -1 { continue }
let (q, r) = a.divided(by: b, rounding: .toOdd)
let justq = a.divided(by: b, rounding: .toOdd)
if q != justq {
XCTFail("""
\(a).divided(by: \(b), rounding: .toOdd) failed check:
BinaryInteger overload did not produce the same quotient as SignedInteger.
BinaryInteger result was \(justq), but SignedInteger was \(q).
""")
return
}
if divisionRuleHolds(a, b, q, r) {
// We know a = bq + r with |r| < |b|. Now validate q is odd if r is
// non-zero.
guard r == 0 || q & 1 == 1 else {
XCTFail("""
\(a).divided(by: \(b), rounding: .toOdd) failed check:
quotient must be odd if remainder is non-zero, but quotient was \(q) and remainder was \(r).
""")
return
}
}
}
}
}
func testDivideExact<T: SignedInteger & FixedWidthInteger>(_ values: [T]) {
for a in values {
for b in values where b != 0 {
// Skip any SignedInt.min / -1 cases, because those will trap.
if a == .min && b == -1 { continue }
// Skip any cases with a remainder (most of them!)
if a % b != 0 { continue }
// Test that division rule holds ignoring r for the cases that
// make it through.
let (q, _) = a.divided(by: b, rounding: .requireExact)
let _ = divisionRuleHolds(a, b, q, 0)
}
}
}
func testDivideInt8() {
let values = Array<Int8>(-128 ... 127)
testDivideDown(values)
testDivideUp(values)
testDivideTowardZero(values)
testDivideAwayFromZero(values)
testDivideToNearestOrDown(values)
testDivideToNearestOrUp(values)
testDivideToNearestOrZero(values)
testDivideToNearestOrAway(values)
testDivideToNearestOrEven(values)
testDivideToOdd(values)
testDivideExact(values)
}
func testDivideInt() {
var values = [Int](repeating: 0, count: 64)
for i in 0 ..< values.count {
while values[i] == 0 {
values[i] = .random(in: .min ... .max)
}
}
testDivideDown(values)
testDivideUp(values)
testDivideTowardZero(values)
testDivideAwayFromZero(values)
testDivideToNearestOrDown(values)
testDivideToNearestOrUp(values)
testDivideToNearestOrZero(values)
testDivideToNearestOrAway(values)
testDivideToNearestOrEven(values)
testDivideToOdd(values)
testDivideExact(values)
}
func testDivideInt128() {
var values = [DoubleWidth<Int64>](repeating: 0, count: 64)
for i in 0 ..< values.count {
while values[i] == 0 {
values[i] = .random(in: .min ... .max)
}
}
testDivideDown(values)
testDivideUp(values)
testDivideTowardZero(values)
testDivideAwayFromZero(values)
testDivideToNearestOrDown(values)
testDivideToNearestOrUp(values)
testDivideToNearestOrZero(values)
testDivideToNearestOrAway(values)
testDivideToNearestOrEven(values)
testDivideToOdd(values)
testDivideExact(values)
}
func divideUInt8(_ a: UInt8, _ b: UInt8, rounding rule: RoundingRule) {
let expected = UInt8(Int16(a).divided(by: Int16(b), rounding: rule).quotient)
let observed = a.divided(by: b, rounding: rule)
guard expected == observed else {
XCTFail("""
\(a).divided(by: \(b), rounding: \(rule)) did not match expected result:
Computed with Int16: \(expected)
Computed with UInt8: \(observed)
""")
return
}
}
func testDivideUInt8() {
let values = Array<UInt8>(0 ... 255)
for a in values {
for b in values where b != 0 {
divideUInt8(a, b, rounding: .down)
divideUInt8(a, b, rounding: .up)
divideUInt8(a, b, rounding: .towardZero)
divideUInt8(a, b, rounding: .awayFromZero)
divideUInt8(a, b, rounding: .toNearestOrDown)
divideUInt8(a, b, rounding: .toNearestOrUp)
divideUInt8(a, b, rounding: .toNearestOrZero)
divideUInt8(a, b, rounding: .toNearestOrAway)
divideUInt8(a, b, rounding: .toNearestOrEven)
divideUInt8(a, b, rounding: .toOdd)
}
}
}
func testRemainderByMinusOne() {
// These would trap if implemented as a - bq or similar, even though
// the remainder is well-defined.
XCTAssertEqual(0, Int.min.remainder(dividingBy: -1))
XCTAssertEqual(0, Int.min.remainder(dividingBy: -1, rounding: .up))
}
}
@@ -1,529 +0,0 @@
//===--- DoubleWidthTests.swift -------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2017-2024 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
//
//===----------------------------------------------------------------------===//
import _TestSupport
import XCTest
final class DoubleWidthTests: XCTestCase {
typealias _Int16 = DoubleWidth<Int8>
typealias _Int128 = DoubleWidth<Int64>
typealias _Int256 = DoubleWidth<_Int128>
typealias _Int512 = DoubleWidth<_Int256>
typealias _Int1024 = DoubleWidth<_Int512>
typealias _UInt16 = DoubleWidth<UInt8>
typealias _UInt128 = DoubleWidth<UInt64>
typealias _UInt256 = DoubleWidth<_UInt128>
typealias _UInt512 = DoubleWidth<_UInt256>
typealias _UInt1024 = DoubleWidth<_UInt512>
// <https://bugs.swift.org/browse/SR-6947>
// Swift 4.x took over 15 minutes to compile this test code.
// Swift 5.5 takes less than one second (`-Onone` or `-O` or `-Osize`).
func testCompileTime_SR_6947() {
typealias _Int32 = DoubleWidth<DoubleWidth<Int8>>
typealias _Int64 = DoubleWidth<DoubleWidth<DoubleWidth<Int8>>>
var sum = 0
let (q, r) = (_Int128(Int64.max) * 16).quotientAndRemainder(dividingBy: 16)
sum += Int(q * r)
XCTAssertEqual(sum, 0)
let x = _Int64(Int64.max / 4)
let y = _Int32(Int32.max)
let xx = _Int1024(x)
let yy = _Int512(y)
let (q3, r3) = yy.dividingFullWidth((xx.high, xx.low))
sum -= Int(q3 - r3)
XCTAssertEqual(sum, -1)
}
func testLiterals() {
let w: _UInt16 = 100
XCTAssertTrue(w == 100 as Int)
let x: _UInt16 = 1000
XCTAssertTrue(x == 1000 as Int)
let y: _Int16 = 1000
XCTAssertTrue(y == 1000 as Int)
let z: _Int16 = -1000
XCTAssertTrue(z == -1000 as Int)
}
func testLiterals_Underflow() {
// TODO: expectCrashLater()
// _ = -1 as _UInt16
}
#if false // TODO: _ExpressibleByBuiltinIntegerLiteral
func testLiterals_LargeSigned() {
let a: _Int256 =
0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
let b: _Int256 =
-0x8000000000000000000000000000000000000000000000000000000000000000
XCTAssertEqual(a, _Int256.max)
XCTAssertEqual(b, _Int256.min)
}
func testLiterals_LargeSigned_Underflow() {
// TODO: expectCrashLater()
// _ = -0x8000000000000000000000000000000000000000000000000000000000000001
// as _Int256
}
func testLiterals_LargeSigned_Overflow() {
// TODO: expectCrashLater()
// _ = 0x8000000000000000000000000000000000000000000000000000000000000000
// as _Int256
}
func testLiterals_LargeUnsigned() {
let a: _UInt256 =
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
let b: _UInt256 = 0
XCTAssertEqual(a, _UInt256.max)
XCTAssertEqual(b, _UInt256.min)
}
func testLiterals_LargeUnsigned_Underflow() {
// TODO: expectCrashLater()
// _ = -1 as _UInt256
}
func testLiterals_LargeUnsigned_Overflow() {
// TODO: expectCrashLater()
// _ = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0
// as _UInt256
}
#endif // TODO: _ExpressibleByBuiltinIntegerLiteral
func testArithmetic_Unsigned() {
let x: _UInt16 = 1000
let y: _UInt16 = 1111
XCTAssertEqual(x + 1, 1001)
XCTAssertEqual(x + x, 2000)
XCTAssertEqual(x - (1 as _UInt16), 999)
XCTAssertEqual(x - x, 0)
XCTAssertEqual(y - x, 111)
XCTAssertEqual(x * 7, 7000)
XCTAssertEqual(y * 7, 7777)
XCTAssertEqual(x / 3, 333)
XCTAssertEqual(x / x, 1)
XCTAssertEqual(x / y, 0)
XCTAssertEqual(y / x, 1)
XCTAssertEqual(x % 3, 1)
XCTAssertEqual(x % y, x)
do {
let lhs = _UInt16((high: 0b0011_0000, low: 0))
let rhs = _UInt16((high: 0b0010_0000, low: 0))
XCTAssertEqual(lhs % rhs, 4096)
}
do {
let lhs = _UInt128((high: 0xa0c7d7165cf01386, low: 0xbf3f66a93056143f))
let rhs = _UInt128((high: 0x9ac3a19b1e7d6b83, low: 0x513929792d588736))
XCTAssertEqual(String(lhs % rhs), "7997221894243298914179865336050715913")
}
do {
let lhs = _UInt128((high: 0xea8a9116b7af33b7, low: 0x3d9d6779ddd22ca3))
let rhs = _UInt128((high: 0xc3673efc7f1f37cc, low: 0x312f661057d0ba94))
XCTAssertEqual(String(lhs % rhs), "52023287460685389410162512181093036559")
}
do {
let lhs = _UInt256("2369676578372158364766242369061213561181961479062237766620")!
let rhs = _UInt256("102797312405202436815976773795958969482")!
XCTAssertEqual(String(lhs / rhs), "23051931251193218442")
}
do {
let lhs = _UInt256("96467201117289166187766181030232879447148862859323917044548749804018359008044")!
let rhs = _UInt256("4646260627574879223760172113656436161581617773435991717024")!
XCTAssertEqual(String(lhs / rhs), "20762331011904583253")
}
XCTAssertTrue((0xff01 as _UInt16).multipliedFullWidth(by: 0x101) == (high: 256, low: 1))
}
func testArithmetic_Signed() {
let x: _Int16 = 1000
let y: _Int16 = -1111
XCTAssertEqual(x + 1, 1001)
XCTAssertEqual(x + x, 2000)
XCTAssertEqual(x - (1 as _Int16), 999)
XCTAssertEqual(x - x, 0)
XCTAssertEqual(0 - x, -1000)
XCTAssertEqual(x + y, -111)
XCTAssertEqual(x - y, 2111)
XCTAssertEqual(x * 7, 7000)
XCTAssertEqual(y * 7, -7777)
XCTAssertEqual(x * -7, -7000)
XCTAssertEqual(y * -7, 7777)
XCTAssertEqual(x / 3, 333)
XCTAssertEqual(x / -3, -333)
XCTAssertEqual(x / x, 1)
XCTAssertEqual(x / y, 0)
XCTAssertEqual(y / x, -1)
XCTAssertEqual(y / y, 1)
XCTAssertEqual(x % 3, 1)
XCTAssertEqual(x % -3, 1)
XCTAssertEqual(y % 3, -1)
XCTAssertEqual(y % -3, -1)
XCTAssertEqual(-y, 1111)
XCTAssertEqual(-x, -1000)
}
func testNested() {
do {
let x = _UInt1024.max
let (y, o) = x.addingReportingOverflow(1)
XCTAssertEqual(y, 0)
XCTAssertTrue(y == (0 as Int))
XCTAssertTrue(o)
}
do {
let x = _Int1024.max
let (y, o) = x.addingReportingOverflow(1)
XCTAssertEqual(y, _Int1024.min)
XCTAssertLessThan(y, 0)
XCTAssertTrue(y < (0 as Int))
XCTAssertTrue(y < (0 as UInt))
XCTAssertTrue(o)
}
XCTAssertFalse(_UInt1024.isSigned)
XCTAssertEqual(_UInt1024.bitWidth, 1024)
XCTAssertTrue(_Int1024.isSigned)
XCTAssertEqual(_Int1024.bitWidth, 1024)
XCTAssertTrue(
_UInt1024.max.words.elementsEqual(
repeatElement(UInt.max, count: 1024 / UInt.bitWidth)
)
)
}
func testInitialization() {
XCTAssertTrue(_UInt16(UInt16.max) == UInt16.max)
XCTAssertNil(_UInt16(exactly: UInt32.max))
XCTAssertEqual(_UInt16(truncatingIfNeeded: UInt64.max), _UInt16.max)
}
func testInitialization_Overflow() {
// TODO: expectCrashLater()
// _ = _UInt16(UInt32.max)
}
func testMagnitude() {
XCTAssertTrue(_UInt16.min.magnitude == UInt16.min.magnitude)
XCTAssertTrue((42 as _UInt16).magnitude == (42 as UInt16).magnitude)
XCTAssertTrue(_UInt16.max.magnitude == UInt16.max.magnitude)
XCTAssertTrue(_Int16.min.magnitude == Int16.min.magnitude)
XCTAssertTrue((-42 as _Int16).magnitude == (-42 as Int16).magnitude)
XCTAssertTrue(_Int16().magnitude == Int16(0).magnitude) // See SR-6602.
XCTAssertTrue((42 as _Int16).magnitude == (42 as Int16).magnitude)
XCTAssertTrue(_Int16.max.magnitude == Int16.max.magnitude)
}
func testTwoWords() {
typealias DW = DoubleWidth<Int>
XCTAssertEqual(-1 as DW, DW(truncatingIfNeeded: -1 as Int8))
XCTAssertNil(Int(exactly: DW(Int.min) - 1))
XCTAssertNil(Int(exactly: DW(Int.max) + 1))
XCTAssertTrue(DW(Int.min) - 1 < Int.min)
XCTAssertTrue(DW(Int.max) + 1 > Int.max)
}
func testBitwise_LeftAndRightShifts() {
typealias _UInt64 = DoubleWidth<DoubleWidth<DoubleWidth<UInt8>>>
typealias _Int64 = DoubleWidth<DoubleWidth<DoubleWidth<Int8>>>
func f<T: FixedWidthInteger, U: FixedWidthInteger>(_ x: T, type: U.Type) {
let y = U(x)
XCTAssertEqual(T.bitWidth, U.bitWidth)
for i in -(T.bitWidth + 1)...(T.bitWidth + 1) {
XCTAssertTrue(x << i == y << i)
XCTAssertTrue(x >> i == y >> i)
XCTAssertTrue(x &<< i == y &<< i)
XCTAssertTrue(x &>> i == y &>> i)
}
}
f(1 as UInt64, type: _UInt64.self)
f(~(~0 as UInt64 >> 1), type: _UInt64.self)
f(UInt64.max, type: _UInt64.self)
// 0b01010101_10100101_11110000_10100101_11110000_10100101_11110000_10100101
f(17340530535757639845 as UInt64, type: _UInt64.self)
f(1 as Int64, type: _Int64.self)
f(Int64.min, type: _Int64.self)
f(Int64.max, type: _Int64.self)
// 0b01010101_10100101_11110000_10100101_11110000_10100101_11110000_10100101
f(6171603459878809765 as Int64, type: _Int64.self)
}
func testRemainder_ByZero() {
func f(_ x: _Int1024, _ y: _Int1024) -> _Int1024 {
return x % y
}
// TODO: expectCrashLater()
// _ = f(42, 0)
}
func testRemainder_ByMinusOne() {
func f(_ x: _Int256, _ y: _Int256) -> _Int256 {
return x.remainderReportingOverflow(dividingBy: y).partialValue
}
XCTAssertEqual(f(.max, -1), 0)
XCTAssertEqual(f(.min, -1), 0)
}
func testDivision_ByZero() {
func f(_ x: _Int1024, _ y: _Int1024) -> _Int1024 {
return x / y
}
// TODO: expectCrashLater()
// _ = f(42, 0)
}
func testDivision_ByMinusOne() {
func f(_ x: _Int1024) -> _Int1024 {
return x / -1
}
// TODO: expectCrashLater()
// _ = f(_Int1024.min)
}
func testMultipleOf() {
func isMultipleTest<T: FixedWidthInteger>(type: T.Type) {
XCTAssertTrue(T.min.isMultiple(of: 2))
XCTAssertFalse(T.max.isMultiple(of: 10))
// Test that these do not crash.
XCTAssertTrue((0 as T).isMultiple(of: 0))
XCTAssertFalse((1 as T).isMultiple(of: 0))
XCTAssertTrue(T.min.isMultiple(of: 0 &- 1))
}
isMultipleTest(type: _Int128.self)
isMultipleTest(type: _UInt128.self)
}
func testMultiplication_ByMinusOne() {
func f(_ x: _Int1024) -> _Int1024 {
return x * -1
}
// TODO: expectCrashLater()
// _ = f(_Int1024.min)
}
func testConversions() {
XCTAssertTrue(_Int16(1 << 15 - 1) == Int(1 << 15 - 1))
XCTAssertTrue(_Int16(-1 << 15) == Int(-1 << 15))
XCTAssertTrue(_UInt16(1 << 16 - 1) == Int(1 << 16 - 1))
XCTAssertTrue(_UInt16(0) == Int(0))
XCTAssertTrue(_Int16(Double(1 << 15 - 1)) == Int(1 << 15 - 1))
XCTAssertTrue(_Int16(Double(-1 << 15)) == Int(-1 << 15))
XCTAssertTrue(_UInt16(Double(1 << 16 - 1)) == Int(1 << 16 - 1))
XCTAssertTrue(_UInt16(Double(0)) == Int(0))
XCTAssertTrue(_Int16(Double(1 << 15 - 1) + 0.9) == Int(1 << 15 - 1))
XCTAssertTrue(_Int16(Double(-1 << 15) - 0.9) == Int(-1 << 15))
XCTAssertTrue(_UInt16(Double(1 << 16 - 1) + 0.9) == Int(1 << 16 - 1))
XCTAssertTrue(_UInt16(Double(0) - 0.9) == Int(0))
XCTAssertEqual(_Int16(0.00001), 0)
XCTAssertEqual(_UInt16(0.00001), 0)
}
func testConversions_Exact() {
XCTAssertEqual(
_Int16(Double(1 << 15 - 1)),
_Int16(exactly: Double(1 << 15 - 1))
)
XCTAssertEqual(
_Int16(Double(-1 << 15)),
_Int16(exactly: Double(-1 << 15))
)
XCTAssertEqual(
_UInt16(Double(1 << 16 - 1)),
_UInt16(exactly: Double(1 << 16 - 1))
)
XCTAssertEqual(
_UInt16(Double(0)),
_UInt16(exactly: Double(0))
)
XCTAssertNil(_Int16(exactly: Double(1 << 15 - 1) + 0.9))
XCTAssertNil(_Int16(exactly: Double(-1 << 15) - 0.9))
XCTAssertNil(_UInt16(exactly: Double(1 << 16 - 1) + 0.9))
XCTAssertNil(_UInt16(exactly: Double(0) - 0.9))
XCTAssertNil(_Int16(exactly: Double(1 << 15)))
XCTAssertNil(_Int16(exactly: Double(-1 << 15) - 1))
XCTAssertNil(_UInt16(exactly: Double(1 << 16)))
XCTAssertNil(_UInt16(exactly: Double(-1)))
XCTAssertNil(_Int16(exactly: 0.00001))
XCTAssertNil(_UInt16(exactly: 0.00001))
XCTAssertNil(_UInt16(exactly: Double.nan))
XCTAssertNil(_UInt16(exactly: Float.nan))
XCTAssertNil(_UInt16(exactly: Double.infinity))
XCTAssertNil(_UInt16(exactly: Float.infinity))
}
func testConversions_SignedMax() {
// TODO: expectCrashLater()
// _ = _Int16(1 << 15)
}
func testConversions_SignedMin() {
// TODO: expectCrashLater()
// _ = _Int16(-1 << 15 - 1)
}
func testConversions_UnsignedMax() {
// TODO: expectCrashLater()
// _ = _UInt16(1 << 16)
}
func testConversions_UnsignedMin() {
// TODO: expectCrashLater()
// _ = _UInt16(-1)
}
func testConversions_ToAndFromString<Number: FixedWidthInteger>(
_ expectedNumber: Number,
_ expectedString: String,
radix: Int,
file: StaticString = #filePath,
line: UInt = #line
) {
let actualString = String(expectedNumber, radix: radix)
XCTAssertEqual(expectedString, actualString, file: file, line: line)
let actualNumber = Number(expectedString, radix: radix)
XCTAssertEqual(expectedNumber, actualNumber, file: file, line: line)
}
func testConversions_ToAndFromString_Binary() {
testConversions_ToAndFromString(
_Int128.max,
"""
111111111111111111111111111111111111111111111111111111111111111\
1111111111111111111111111111111111111111111111111111111111111111
""",
radix: 2
)
testConversions_ToAndFromString(
_Int128.min,
"""
-1000000000000000000000000000000000000000000000000000000000000000\
0000000000000000000000000000000000000000000000000000000000000000
""",
radix: 2
)
}
func testConversions_ToAndFromString_Decimal() {
testConversions_ToAndFromString(
_Int256.max,
"""
5789604461865809771178549250434395392663\
4992332820282019728792003956564819967
""",
radix: 10
)
testConversions_ToAndFromString(
_Int256.min,
"""
-5789604461865809771178549250434395392663\
4992332820282019728792003956564819968
""",
radix: 10
)
}
func testConversions_ToAndFromString_Hexadecimal() {
testConversions_ToAndFromString(
_Int512.max,
"""
7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\
ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
""",
radix: 16
)
testConversions_ToAndFromString(
_Int512.min,
"""
-8000000000000000000000000000000000000000000000000000000000000000\
0000000000000000000000000000000000000000000000000000000000000000
""",
radix: 16
)
}
func testWords() {
XCTAssertTrue(_Int16(0).words.elementsEqual([0]))
XCTAssertTrue(_Int16(1).words.elementsEqual([1]))
XCTAssertTrue(_Int16(-1).words.elementsEqual([UInt.max]))
XCTAssertTrue(_Int16(256).words.elementsEqual([256]))
XCTAssertTrue(_Int16(-256).words.elementsEqual([UInt.max - 255]))
XCTAssertTrue(_Int16.max.words.elementsEqual([32767]))
XCTAssertTrue(_Int16.min.words.elementsEqual([UInt.max - 32767]))
XCTAssertTrue(
(0 as _Int1024).words.elementsEqual(
repeatElement(0 as UInt, count: 1024 / UInt.bitWidth)
)
)
XCTAssertTrue(
(-1 as _Int1024).words.elementsEqual(
repeatElement(UInt.max, count: 1024 / UInt.bitWidth)
)
)
XCTAssertTrue(
(1 as _Int1024).words.elementsEqual(
[1] + Array(repeating: 0, count: 1024 / UInt.bitWidth - 1)
)
)
}
func testConditionalConformance() {
func checkSignedIntegerConformance<T: SignedInteger>(_: T) {}
func checkUnsignedIntegerConformance<T: UnsignedInteger>(_: T) {}
checkSignedIntegerConformance(0 as _Int128)
checkSignedIntegerConformance(0 as _Int1024)
checkUnsignedIntegerConformance(0 as _UInt128)
checkUnsignedIntegerConformance(0 as _UInt1024)
}
func testMultiplyOverflow() {
XCTAssertFalse(_Int128(-1).multipliedReportingOverflow(by: 0).overflow)
}
}
@@ -1,44 +0,0 @@
//===--- GCDTests.swift ---------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2021 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
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import IntegerUtilities
import XCTest
final class IntegerUtilitiesGCDTests: XCTestCase {
func testGCDInt() {
XCTAssertEqual(gcd(0, 0), 0)
XCTAssertEqual(gcd(0, 1), 1)
XCTAssertEqual(gcd(1, 0), 1)
XCTAssertEqual(gcd(0, -1), 1)
XCTAssertEqual(gcd(1, 1), 1)
XCTAssertEqual(gcd(1, 2), 1)
XCTAssertEqual(gcd(2, 2), 2)
XCTAssertEqual(gcd(4, 2), 2)
XCTAssertEqual(gcd(6, 8), 2)
XCTAssertEqual(gcd(77, 91), 7)
XCTAssertEqual(gcd(24, -36), 12)
XCTAssertEqual(gcd(-24, -36), 12)
XCTAssertEqual(gcd(51, 34), 17)
XCTAssertEqual(gcd(64, 96), 32)
XCTAssertEqual(gcd(-64, 96), 32)
XCTAssertEqual(gcd(4*7*19, 27*25), 1)
XCTAssertEqual(gcd(16*315, 11*315), 315)
XCTAssertEqual(gcd(97*67*53*27*8, 83*67*53*9*32), 67*53*9*8)
XCTAssertEqual(gcd(Int.min, 2), 2)
// TODO: Enable these when version compatibility allows.
//
// XCTExpectFailure{ gcd(0, Int.min) }
// XCTExpectFailure{ gcd(Int.min, 0) }
// XCTExpectFailure{ gcd(Int.min, Int.min) }
}
}
@@ -1,74 +0,0 @@
//===--- RotateTests.swift ------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2021 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
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import IntegerUtilities
import XCTest
final class IntegerUtilitiesRotateTests: XCTestCase {
func testRotateUInt8() {
let x: UInt8 = 0b10011100
XCTAssertEqual(0b01001110, x.rotated(right:-7))
XCTAssertEqual(0b00100111, x.rotated(right:-6))
XCTAssertEqual(0b10010011, x.rotated(right:-5))
XCTAssertEqual(0b11001001, x.rotated(right:-4))
XCTAssertEqual(0b11100100, x.rotated(right:-3))
XCTAssertEqual(0b01110010, x.rotated(right:-2))
XCTAssertEqual(0b00111001, x.rotated(right:-1))
XCTAssertEqual(0b10011100, x.rotated(right: 0))
XCTAssertEqual(0b01001110, x.rotated(right: 1))
XCTAssertEqual(0b00100111, x.rotated(right: 2))
XCTAssertEqual(0b10010011, x.rotated(right: 3))
XCTAssertEqual(0b11001001, x.rotated(right: 4))
XCTAssertEqual(0b11100100, x.rotated(right: 5))
XCTAssertEqual(0b01110010, x.rotated(right: 6))
XCTAssertEqual(0b00111001, x.rotated(right: 7))
XCTAssertEqual(0b10011100, x.rotated(right: 8))
}
func testRotateInt16() {
let x = Int16(bitPattern: 0b1001110000111110)
XCTAssertEqual(Int16(bitPattern: 0b1001110000111110), x.rotated(left:-16))
XCTAssertEqual(Int16(bitPattern: 0b0011100001111101), x.rotated(left:-15))
XCTAssertEqual(Int16(bitPattern: 0b0111000011111010), x.rotated(left:-14))
XCTAssertEqual(Int16(bitPattern: 0b1110000111110100), x.rotated(left:-13))
XCTAssertEqual(Int16(bitPattern: 0b1100001111101001), x.rotated(left:-12))
XCTAssertEqual(Int16(bitPattern: 0b1000011111010011), x.rotated(left:-11))
XCTAssertEqual(Int16(bitPattern: 0b0000111110100111), x.rotated(left:-10))
XCTAssertEqual(Int16(bitPattern: 0b0001111101001110), x.rotated(left:-9))
XCTAssertEqual(Int16(bitPattern: 0b0011111010011100), x.rotated(left:-8))
XCTAssertEqual(Int16(bitPattern: 0b0111110100111000), x.rotated(left:-7))
XCTAssertEqual(Int16(bitPattern: 0b1111101001110000), x.rotated(left:-6))
XCTAssertEqual(Int16(bitPattern: 0b1111010011100001), x.rotated(left:-5))
XCTAssertEqual(Int16(bitPattern: 0b1110100111000011), x.rotated(left:-4))
XCTAssertEqual(Int16(bitPattern: 0b1101001110000111), x.rotated(left:-3))
XCTAssertEqual(Int16(bitPattern: 0b1010011100001111), x.rotated(left:-2))
XCTAssertEqual(Int16(bitPattern: 0b0100111000011111), x.rotated(left:-1))
XCTAssertEqual(Int16(bitPattern: 0b1001110000111110), x.rotated(left: 0))
XCTAssertEqual(Int16(bitPattern: 0b0011100001111101), x.rotated(left: 1))
XCTAssertEqual(Int16(bitPattern: 0b0111000011111010), x.rotated(left: 2))
XCTAssertEqual(Int16(bitPattern: 0b1110000111110100), x.rotated(left: 3))
XCTAssertEqual(Int16(bitPattern: 0b1100001111101001), x.rotated(left: 4))
XCTAssertEqual(Int16(bitPattern: 0b1000011111010011), x.rotated(left: 5))
XCTAssertEqual(Int16(bitPattern: 0b0000111110100111), x.rotated(left: 6))
XCTAssertEqual(Int16(bitPattern: 0b0001111101001110), x.rotated(left: 7))
XCTAssertEqual(Int16(bitPattern: 0b0011111010011100), x.rotated(left: 8))
XCTAssertEqual(Int16(bitPattern: 0b0111110100111000), x.rotated(left: 9))
XCTAssertEqual(Int16(bitPattern: 0b1111101001110000), x.rotated(left: 10))
XCTAssertEqual(Int16(bitPattern: 0b1111010011100001), x.rotated(left: 11))
XCTAssertEqual(Int16(bitPattern: 0b1110100111000011), x.rotated(left: 12))
XCTAssertEqual(Int16(bitPattern: 0b1101001110000111), x.rotated(left: 13))
XCTAssertEqual(Int16(bitPattern: 0b1010011100001111), x.rotated(left: 14))
XCTAssertEqual(Int16(bitPattern: 0b0100111000011111), x.rotated(left: 15))
XCTAssertEqual(Int16(bitPattern: 0b1001110000111110), x.rotated(left: 16))
}
}
@@ -1,243 +0,0 @@
//===--- RoundingTests.swift ----------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2024 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
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import IntegerUtilities
import _TestSupport
import XCTest
final class IntegerUtilitiesRoundingTests: XCTestCase {
func testRoundingDirected<T: BinaryFloatingPoint>(_ type: T.Type) {
let inf = T.infinity
let gfm = T.greatestFiniteMagnitude
let big: T = 1 / .ulpOfOne
let two: T = 2
let threeHalves: T = 1.5
let one: T = 1
let half: T = 0.5
let nrm = T.leastNormalMagnitude
let lnm = T.leastNonzeroMagnitude
let vectors: [(input: T, down: T, up: T, zero: T, away: T)] = [
(-inf, -inf, -inf, -inf, -inf),
(-gfm, -gfm, -gfm, -gfm, -gfm),
(-big.nextUp, -big-1, -big-1, -big-1, -big-1),
(-big, -big, -big, -big, -big),
(-big.nextDown, -big, -big+1, -big+1, -big),
(-two, -two, -two, -two, -two),
(-two.nextDown, -two, -one, -one, -two),
(-threeHalves.nextUp, -two, -one, -one, -two),
(-threeHalves, -two, -one, -one, -two),
(-threeHalves.nextDown, -two, -one, -one, -two),
(-one.nextUp, -two, -one, -one, -two),
(-one, -one, -one, -one, -one),
(-one.nextDown, -one, 0, 0, -one),
(-half.nextUp, -one, 0, 0, -one),
(-half, -one, 0, 0, -one),
(-half.nextDown, -one, 0, 0, -one),
(-nrm, -one, 0, 0, -one),
(-lnm, -one, 0, 0, -one),
(-.zero, 0, 0, 0, 0),
( .zero, 0, 0, 0, 0),
( lnm, 0, one, 0, one),
( nrm, 0, one, 0, one),
( half.nextDown, 0, one, 0, one),
( half, 0, one, 0, one),
( half.nextUp, 0, one, 0, one),
( one.nextDown, 0, one, 0, one),
( one, one, one, one, one),
( one.nextUp, one, two, one, two),
( threeHalves.nextDown, one, two, one, two),
( threeHalves, one, two, one, two),
( threeHalves.nextUp, one, two, one, two),
( two.nextDown, one, two, one, two),
( two, two, two, two, two),
( big.nextDown, big-1, big, big-1, big),
( big, big, big, big, big),
( big.nextUp, big+1, big+1, big+1, big+1),
( gfm, gfm, gfm, gfm, gfm),
( inf, inf, inf, inf, inf),
]
for vector in vectors {
XCTAssertEqual(vector.input.rounding(.down), vector.down)
if vector.down == 0 {
XCTAssertEqual(vector.input.rounding(.down).sign, vector.input.sign)
}
XCTAssertEqual(vector.input.rounding(.up), vector.up)
if vector.up == 0 {
XCTAssertEqual(vector.input.rounding(.up).sign, vector.input.sign)
}
XCTAssertEqual(vector.input.rounding(.towardZero), vector.zero)
if vector.zero == 0 {
XCTAssertEqual(vector.input.rounding(.towardZero).sign, vector.input.sign)
}
XCTAssertEqual(vector.input.rounding(.awayFromZero), vector.away)
if vector.away == 0 {
XCTAssertEqual(vector.input.rounding(.awayFromZero).sign, vector.input.sign)
}
}
}
func testRoundingDirected() {
testRoundingDirected(Float.self)
testRoundingDirected(Double.self)
}
func testRoundingNearest<T: BinaryFloatingPoint>(_ type: T.Type) {
let inf = T.infinity
let gfm = T.greatestFiniteMagnitude
let big: T = 1 / .ulpOfOne
let two: T = 2
let threeHalves: T = 1.5
let one: T = 1
let half: T = 0.5
let nrm = T.leastNormalMagnitude
let lnm = T.leastNonzeroMagnitude
let vectors: [(input: T, down: T, up: T, zero: T, away: T, even: T)] = [
(-inf, -inf, -inf, -inf, -inf, -inf),
(-gfm, -gfm, -gfm, -gfm, -gfm, -gfm),
(-big.nextUp, -big-1, -big-1, -big-1, -big-1, -big-1),
(-big, -big, -big, -big, -big, -big),
(-big.nextDown, -big, -big+1, -big+1, -big, -big),
(-two, -two, -two, -two, -two, -two),
(-two.nextDown, -two, -two, -two, -two, -two),
(-threeHalves.nextUp, -two, -two, -two, -two, -two),
(-threeHalves, -two, -one, -one, -two, -two),
(-threeHalves.nextDown, -one, -one, -one, -one, -one),
(-one.nextUp, -one, -one, -one, -one, -one),
(-one, -one, -one, -one, -one, -one),
(-one.nextDown, -one, -one, -one, -one, -one),
(-half.nextUp, -one, -one, -one, -one, -one),
(-half, -one, 0, 0, -one, 0),
(-half.nextDown, 0, 0, 0, 0, 0),
(-nrm, 0, 0, 0, 0, 0),
(-lnm, 0, 0, 0, 0, 0),
(-.zero, 0, 0, 0, 0, 0),
( .zero, 0, 0, 0, 0, 0),
( lnm, 0, 0, 0, 0, 0),
( nrm, 0, 0, 0, 0, 0),
( half.nextDown, 0, 0, 0, 0, 0),
( half, 0, one, 0, one, 0),
( half.nextUp, one, one, one, one, one),
( one.nextDown, one, one, one, one, one),
( one, one, one, one, one, one),
( one.nextUp, one, one, one, one, one),
( threeHalves.nextDown, one, one, one, one, one),
( threeHalves, one, two, one, two, two),
( threeHalves.nextUp, two, two, two, two, two),
( two.nextDown, two, two, two, two, two),
( two, two, two, two, two, two),
( big.nextDown, big-1, big, big-1, big, big),
( big, big, big, big, big, big),
( big.nextUp, big+1, big+1, big+1, big+1, big+1),
( gfm, gfm, gfm, gfm, gfm, gfm),
( inf, inf, inf, inf, inf, inf),
]
for vector in vectors {
XCTAssertEqual(vector.input.rounding(.toNearestOrDown), vector.down, "\(vector.input).rounding(.toNearestOrDown)")
if vector.down == 0 {
XCTAssertEqual(vector.input.rounding(.toNearestOrDown).sign, vector.input.sign, "\(vector.input).rounding(.toNearestOrDown)")
}
XCTAssertEqual(vector.input.rounding(.toNearestOrUp), vector.up, "\(vector.input).rounding(.toNearestOrUp)")
if vector.up == 0 {
XCTAssertEqual(vector.input.rounding(.toNearestOrUp).sign, vector.input.sign, "\(vector.input).rounding(.toNearestOrUp)")
}
XCTAssertEqual(vector.input.rounding(.toNearestOrZero), vector.zero, "\(vector.input).rounding(.toNearestOrZero)")
if vector.zero == 0 {
XCTAssertEqual(vector.input.rounding(.toNearestOrZero).sign, vector.input.sign, "\(vector.input).rounding(.toNearestOrZero)")
}
XCTAssertEqual(vector.input.rounding(.toNearestOrAway), vector.away, "\(vector.input).rounding(.toNearestOrAway)")
if vector.away == 0 {
XCTAssertEqual(vector.input.rounding(.toNearestOrAway).sign, vector.input.sign, "\(vector.input).rounding(.toNearestOrAway)")
}
XCTAssertEqual(vector.input.rounding(.toNearestOrEven), vector.even, "\(vector.input).rounding(.toNearestOrEven)")
if vector.even == 0 {
XCTAssertEqual(vector.input.rounding(.toNearestOrEven).sign, vector.input.sign, "\(vector.input).rounding(.toNearestOrEven)")
}
}
}
func testRoundingNearest() {
testRoundingNearest(Float.self)
testRoundingNearest(Double.self)
}
func testRoundingOdd<T: BinaryFloatingPoint>(_ type: T.Type) {
let inf = T.infinity
let gfm = T.greatestFiniteMagnitude
let big: T = 1 / .ulpOfOne
let two: T = 2
let threeHalves: T = 1.5
let one: T = 1
let half: T = 0.5
let nrm = T.leastNormalMagnitude
let lnm = T.leastNonzeroMagnitude
let vectors: [(input: T, odd: T)] = [
(-inf, -inf),
(-gfm, -gfm),
(-big.nextUp, -big-1),
(-big, -big),
(-big.nextDown, -big+1),
(-two, -two),
(-two.nextDown, -one),
(-threeHalves.nextUp, -one),
(-threeHalves, -one),
(-threeHalves.nextDown, -one),
(-one.nextUp, -one),
(-one, -one),
(-one.nextDown, -one),
(-half.nextUp, -one),
(-half, -one),
(-half.nextDown, -one),
(-nrm, -one),
(-lnm, -one),
(-.zero, 0),
( .zero, 0),
( lnm, one),
( nrm, one),
( half.nextDown, one),
( half, one),
( half.nextUp, one),
( one.nextDown, one),
( one, one),
( one.nextUp, one),
( threeHalves.nextDown, one),
( threeHalves, one),
( threeHalves.nextUp, one),
( two.nextDown, one),
( two, two),
( big.nextDown, big-1),
( big, big),
( big.nextUp, big+1),
( gfm, gfm),
( inf, inf)
]
for vector in vectors {
XCTAssertEqual(vector.input.rounding(.toOdd), vector.odd, "\(vector.input).rounding(.toOdd)")
if vector.odd == 0 {
XCTAssertEqual(vector.input.rounding(.toOdd).sign, vector.input.sign, "\(vector.input).rounding(.toOdd)")
}
}
}
func testRoundingOdd() {
testRoundingOdd(Float.self)
testRoundingOdd(Double.self)
}
}
@@ -1,192 +0,0 @@
//===--- SaturatingArithmeticTests.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
// 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)
}
}
@@ -1,155 +0,0 @@
//===--- ShiftTests.swift -------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2021-2024 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
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import IntegerUtilities
import XCTest
import _TestSupport
final class IntegerUtilitiesShiftTests: XCTestCase {
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
let ceiling = exact ? floor : floor &+ 1
let expected: T
if exact { expected = floor }
else {
switch rule {
case .down:
expected = floor
case .up:
expected = ceiling
case .towardZero:
expected = value < 0 ? ceiling : floor
case .awayFromZero:
expected = value > 0 ? ceiling : floor
case .toOdd:
expected = floor | (exact ? 0 : 1)
case .toNearestOrDown:
let step = value.shifted(rightBy: count - 2, rounding: .toOdd)
switch step & 0b11 {
case 0b01: expected = floor
case 0b10: expected = floor
case 0b11: expected = ceiling
default: preconditionFailure()
}
case .toNearestOrUp:
let step = value.shifted(rightBy: count - 2, rounding: .toOdd)
switch step & 0b11 {
case 0b01: expected = floor
case 0b10: expected = ceiling
case 0b11: expected = ceiling
default: preconditionFailure()
}
case .toNearestOrZero:
let step = value.shifted(rightBy: count - 2, rounding: .toOdd)
switch step & 0b11 {
case 0b01: expected = floor
case 0b10: expected = value > 0 ? floor : ceiling
case 0b11: expected = ceiling
default: preconditionFailure()
}
case .toNearestOrAway:
let step = value.shifted(rightBy: count - 2, rounding: .toOdd)
switch step & 0b11 {
case 0b01: expected = floor
case 0b10: expected = value > 0 ? ceiling : floor
case 0b11: expected = ceiling
default: preconditionFailure()
}
case .toNearestOrEven:
let step = value.shifted(rightBy: count - 2, rounding: .toOdd)
switch step & 0b11 {
case 0b01: expected = floor
case 0b10: expected = floor & 1 == 0 ? floor : ceiling
case 0b11: expected = ceiling
default: preconditionFailure()
}
case .requireExact:
preconditionFailure()
}
let observed = value.shifted(rightBy: count, rounding: rule)
if observed != expected {
print("Error found in \(T.self).shifted(rightBy: \(count), rounding: \(rule)).")
print(" Value: \(String(value, radix: 2))")
print("Expected: \(String(expected, radix: 2))")
print("Observed: \(String(observed, radix: 2))")
XCTFail()
}
}
}
func testRoundingShift<T: FixedWidthInteger>(
_ type: T.Type, rounding rule: RoundingRule
) {
for count in -2*T.bitWidth ... 2*T.bitWidth {
// zero shifted by anything is always zero
XCTAssertEqual(0, (0 as T).shifted(rightBy: count, rounding: rule))
for _ in 0 ..< 100 {
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() {
testRoundingShift(Int8.self, rounding: .down)
testRoundingShift(Int8.self, rounding: .up)
testRoundingShift(Int8.self, rounding: .towardZero)
testRoundingShift(Int8.self, rounding: .awayFromZero)
testRoundingShift(Int8.self, rounding: .toNearestOrUp)
testRoundingShift(Int8.self, rounding: .toNearestOrDown)
testRoundingShift(Int8.self, rounding: .toNearestOrZero)
testRoundingShift(Int8.self, rounding: .toNearestOrAway)
testRoundingShift(Int8.self, rounding: .toNearestOrEven)
testRoundingShift(Int8.self, rounding: .toOdd)
testRoundingShift(UInt8.self, rounding: .down)
testRoundingShift(UInt8.self, rounding: .up)
testRoundingShift(UInt8.self, rounding: .towardZero)
testRoundingShift(UInt8.self, rounding: .awayFromZero)
testRoundingShift(UInt8.self, rounding: .toNearestOrUp)
testRoundingShift(UInt8.self, rounding: .toNearestOrDown)
testRoundingShift(UInt8.self, rounding: .toNearestOrZero)
testRoundingShift(UInt8.self, rounding: .toNearestOrAway)
testRoundingShift(UInt8.self, rounding: .toNearestOrEven)
testRoundingShift(UInt8.self, rounding: .toOdd)
testRoundingShift(Int.self, rounding: .down)
testRoundingShift(Int.self, rounding: .up)
testRoundingShift(Int.self, rounding: .towardZero)
testRoundingShift(Int.self, rounding: .awayFromZero)
testRoundingShift(Int.self, rounding: .toNearestOrUp)
testRoundingShift(Int.self, rounding: .toNearestOrDown)
testRoundingShift(Int.self, rounding: .toNearestOrZero)
testRoundingShift(Int.self, rounding: .toNearestOrAway)
testRoundingShift(Int.self, rounding: .toNearestOrEven)
testRoundingShift(Int.self, rounding: .toOdd)
testRoundingShift(UInt.self, rounding: .down)
testRoundingShift(UInt.self, rounding: .up)
testRoundingShift(UInt.self, rounding: .towardZero)
testRoundingShift(UInt.self, rounding: .awayFromZero)
testRoundingShift(UInt.self, rounding: .toNearestOrUp)
testRoundingShift(UInt.self, rounding: .toNearestOrDown)
testRoundingShift(UInt.self, rounding: .toNearestOrZero)
testRoundingShift(UInt.self, rounding: .toNearestOrAway)
testRoundingShift(UInt.self, rounding: .toNearestOrEven)
testRoundingShift(UInt.self, rounding: .toOdd)
}
}
@@ -31,11 +31,6 @@ internal extension Real where Self: FixedWidthFloatingPoint {
XCTAssertEqual(Self.pow(-1, Int.max), -1)
XCTAssertEqual(Self.pow(-1, -Int.max), -1)
XCTAssertEqual(Self.pow(-1, Int.min), 1)
}
static func testIntegerExponentOverflowAndUnderflow() {
// TODO: replace with seedable generator, print seed.
var g = SystemRandomNumberGenerator()
// Generate some random test values that definitely overflow or
// underflow; we want to be sure that we get the right ±0 or ±∞
// result.
@@ -87,7 +82,6 @@ internal extension Real where Self: FixedWidthFloatingPoint {
extension Float16 {
static func testIntegerExponent() {
testIntegerExponentCommon()
testIntegerExponentOverflowAndUnderflow()
testIntegerExponentDoubleAndSmaller()
let u = Float16(1).nextUp
let d = Float16(1).nextDown
@@ -115,7 +109,6 @@ extension Float16 {
extension Float {
static func testIntegerExponent() {
testIntegerExponentCommon()
testIntegerExponentOverflowAndUnderflow()
testIntegerExponentDoubleAndSmaller()
let u = Float(1).nextUp
let d = Float(1).nextDown
@@ -142,7 +135,6 @@ extension Float {
extension Double {
static func testIntegerExponent() {
testIntegerExponentCommon()
testIntegerExponentOverflowAndUnderflow()
// Following tests only make sense (and are only necessary) on 64b platforms.
#if arch(arm64) || arch(x86_64)
testIntegerExponentDoubleAndSmaller()
@@ -201,10 +193,6 @@ final class IntegerExponentTests: XCTestCase {
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
func testFloat80() {
Float80.testIntegerExponentCommon()
// FreeBSD's powl(3) has a bug where a minus sign is not perserved on overflow/underflow.
#if !os(FreeBSD)
Float80.testIntegerExponentOverflowAndUnderflow()
#endif
}
#endif
}