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:
Robert Thompson committed 2020-01-14 15:00:38 -05:00
1 parent 3a4cc1c623
commit 7c6e2ce0d8
2 files changed
+21 -1

No files matched your search

+10 -1
View File
@@ -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 {
+11
View File
@@ -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)
}
}