From fac716fdb2b34ecdb04fc995a8af8698a36a07e6 Mon Sep 17 00:00:00 2001 From: Robert Thompson Date: Thu, 16 Jan 2020 15:15:37 -0500 Subject: [PATCH] Fix implementation of `<` Previously, all BigInts were less than themselves. This is no longer true. Discovered thanks to @lorentey and @benrimmington re: discussion on explicit implementation of `!=`. --- Sources/BigInt/BigInt.swift | 8 ++++++-- Tests/BigIntTests/BigIntTests.swift | 18 ++++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/Sources/BigInt/BigInt.swift b/Sources/BigInt/BigInt.swift index 8d330d1..b24ba70 100644 --- a/Sources/BigInt/BigInt.swift +++ b/Sources/BigInt/BigInt.swift @@ -77,11 +77,15 @@ extension BigInt: Comparable { } for i in stride(from: lhs.words.count - 1, through: 0, by: -1) { - if lhs.words[i] > rhs.words[i] { return false } + if lhs.words[i] > rhs.words[i] { + return false + } else if lhs.words[i] < rhs.words[i] { + return true + } } } - return true + return false } } diff --git a/Tests/BigIntTests/BigIntTests.swift b/Tests/BigIntTests/BigIntTests.swift index 62e341d..e860f67 100644 --- a/Tests/BigIntTests/BigIntTests.swift +++ b/Tests/BigIntTests/BigIntTests.swift @@ -111,6 +111,24 @@ final class BigIntTests: XCTestCase { baz.negate() XCTAssertEqual(baz, bar) } + + func testComparable() { + let foo = BigInt("1234567890123456789012345678901234567890")! + let bar = foo * foo + + XCTAssertLessThan(foo, bar) + XCTAssertFalse(foo < foo) + XCTAssertFalse(bar < bar) + XCTAssertFalse(foo > foo) + XCTAssertFalse(bar > bar) + XCTAssertGreaterThan(bar, foo) + + let baz = bar * -1 + + XCTAssertLessThan(baz, foo) + XCTAssertNotEqual(bar, baz) + XCTAssertFalse(baz < baz) + } func testCodable() throws { let lowerBound = BigInt("-1234567890123456789012345678901234567890")!