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) + } }