From 7c6e2ce0d8a20435946d99e989b4584a589f06d6 Mon Sep 17 00:00:00 2001 From: Robert Thompson Date: Tue, 14 Jan 2020 15:00:38 -0500 Subject: [PATCH] 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. --- Sources/BigInt/BigInt.swift | 11 ++++++++++- Tests/BigIntTests/BigIntTests.swift | 11 +++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/Sources/BigInt/BigInt.swift b/Sources/BigInt/BigInt.swift index 9c3c419..fdd6137 100644 --- a/Sources/BigInt/BigInt.swift +++ b/Sources/BigInt/BigInt.swift @@ -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 { diff --git a/Tests/BigIntTests/BigIntTests.swift b/Tests/BigIntTests/BigIntTests.swift index d79da0f..5635795 100644 --- a/Tests/BigIntTests/BigIntTests.swift +++ b/Tests/BigIntTests/BigIntTests.swift @@ -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) + } }