mirror of
https://github.com/apple/swift-numerics
synced 2026-11-29 05:24:24 +00:00
Explicitly implement public mutating func negate()
As per the TODO put in by @benrimmington. I'm not 100% sure this is actually better than the default implementation provided by `SignedNumeric`, but there's a chance it is.
This commit is contained in:
1 parent
3a4cc1c623
commit
7c6e2ce0d8
2 files changed
+21
-1
No files matched your search
@@ -288,7 +288,16 @@ extension BigInt: Numeric {
|
||||
|
||||
extension BigInt: SignedNumeric {
|
||||
|
||||
// TODO: public mutating func negate()
|
||||
public mutating func negate() {
|
||||
var isOverflow = true
|
||||
for i in 0 ..< words.count {
|
||||
if isOverflow {
|
||||
(words[i], isOverflow) = (~words[i]).addingReportingOverflow(1)
|
||||
} else {
|
||||
words[i] = ~words[i]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static prefix func - (x: BigInt) -> BigInt {
|
||||
|
||||
@@ -98,4 +98,15 @@ final class BigIntTests: XCTestCase {
|
||||
XCTAssertEqual(dict[foo]!, "Hello")
|
||||
XCTAssertEqual(dict[bar]!, "World")
|
||||
}
|
||||
|
||||
func testNegation() {
|
||||
let foo = BigInt("1234567890123456789012345678901234567890")!
|
||||
let bar = BigInt(0) - foo
|
||||
|
||||
XCTAssertEqual(-foo, bar)
|
||||
|
||||
var baz = foo
|
||||
baz.negate()
|
||||
XCTAssertEqual(baz, bar)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user