From f6a3d2d4e4d65bdd0289b0663395d24ad515055c Mon Sep 17 00:00:00 2001 From: Ben Rimmington Date: Wed, 15 Jan 2020 00:17:17 +0000 Subject: [PATCH 1/8] [BigIntTests] Add testMinMaxDescriptions() method This currently fails for: BigInt(Int64.min) - 2 BigInt(Int64.min) - 1 BigInt(Int64.max) + 1 BigInt(Int64.max) + 2 --- Tests/BigIntTests/BigIntTests.swift | 45 +++++++++++++++++++++++++++-- 1 file changed, 43 insertions(+), 2 deletions(-) diff --git a/Tests/BigIntTests/BigIntTests.swift b/Tests/BigIntTests/BigIntTests.swift index 7f0afc7..fd7619d 100644 --- a/Tests/BigIntTests/BigIntTests.swift +++ b/Tests/BigIntTests/BigIntTests.swift @@ -1,8 +1,8 @@ -//===--- BigIntTests.swift -----------------------*- swift -*-===// +//===--- BigIntTests.swift ------------------------------------*- swift -*-===// // // This source file is part of the Swift Numerics open source project // -// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors +// Copyright (c) 2019 - 2020 Apple Inc. and the Swift Numerics project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information @@ -24,6 +24,7 @@ func fac(_ n: BigInt) -> BigInt { } final class BigIntTests: XCTestCase { + func testExample() throws { let bar = BigInt(exactly: -100) XCTAssertNotNil(bar) @@ -123,4 +124,44 @@ final class BigIntTests: XCTestCase { XCTAssertEqual(foo, bar) } + + func testMinMaxDescriptions() { + let keyValuePairs: KeyValuePairs = [ + BigInt(UInt64.min): [ + "-2", + "-1", + "0", + "1", + "2" + ], + BigInt(UInt64.max): [ + "18446744073709551613", + "18446744073709551614", + "18446744073709551615", + "18446744073709551616", + "18446744073709551617", + ], + BigInt(Int64.min): [ + "-9223372036854775810", + "-9223372036854775809", + "-9223372036854775808", + "-9223372036854775807", + "-9223372036854775806", + ], + BigInt(Int64.max): [ + "9223372036854775805", + "9223372036854775806", + "9223372036854775807", + "9223372036854775808", + "9223372036854775809", + ], + ] + for (expectedNumber, expectedStrings) in keyValuePairs { + let expectedNumbers: [BigInt] = (-2 ... 2).map({ expectedNumber + $0 }) + let actualNumbers: [BigInt] = expectedStrings.compactMap({ BigInt($0) }) + let actualStrings: [String] = actualNumbers.map({ $0.description }) + XCTAssertEqual(actualNumbers, expectedNumbers, "Numbers: actual, expected") + XCTAssertEqual(actualStrings, expectedStrings, "Strings: actual, expected") + } + } } From 3cf0b0cf7400744ffb6f62b8876dbd361d557977 Mon Sep 17 00:00:00 2001 From: Ben Rimmington Date: Wed, 15 Jan 2020 00:47:04 +0000 Subject: [PATCH 2/8] [BigInt] Update the LosslessStringConvertible init This performs 6x faster (measured with a 1000-digit string). But it doesn't fix the testMinMaxDescriptions() failures. --- Sources/BigInt/BigInt.swift | 48 +++++++++++++++++++---------- Tests/BigIntTests/BigIntTests.swift | 23 ++++++++++++++ 2 files changed, 54 insertions(+), 17 deletions(-) diff --git a/Sources/BigInt/BigInt.swift b/Sources/BigInt/BigInt.swift index 3821ad5..9eff36d 100644 --- a/Sources/BigInt/BigInt.swift +++ b/Sources/BigInt/BigInt.swift @@ -29,9 +29,9 @@ public struct BigInt: SignedInteger { words[words.endIndex - 1] > Int.max } - private static let _digits = { - (0 ... 10).map { BigInt(words: [UInt(bitPattern: $0)]) } - }() + private static let _digits: [BigInt] = (0 ... 36).map { + BigInt(words: [UInt(bitPattern: $0)]) + } } // MARK: - Basic Behaviors @@ -109,26 +109,40 @@ extension BigInt: CustomStringConvertible { extension BigInt: LosslessStringConvertible { public init?(_ description: String) { + self.init(description, radix: 10) + } + + public init?(_ description: T, radix: Int = 10) where T: StringProtocol { + precondition(2 ... 36 ~= radix, "Radix not in range 2 ... 36") + + self = 0 + let isNegative = description.hasPrefix("-") - let hasPrefixOperator = isNegative || description.hasPrefix("+") + let hasPrefix = isNegative || description.hasPrefix("+") + let utf8 = description.utf8.dropFirst(hasPrefix ? 1 : 0) + guard !utf8.isEmpty else { return nil } - let unprefixedDescription = hasPrefixOperator ? description.dropFirst() : description[...] - guard !unprefixedDescription.isEmpty else { return nil } - - let digits = Set("0123456789") - guard unprefixedDescription.allSatisfy({ digits.contains($0) }) else { return nil } - - var result: BigInt = 0 - for (i, char) in unprefixedDescription.drop(while: { $0 == "0" }).reversed().enumerated() { - // We're ok to force unwrap here because of the guard above. - result += BigInt(char.wholeNumberValue!) * pow(10, BigInt(i)) + for var byte in utf8 { + switch byte { + case UInt8(ascii: "0") ... UInt8(ascii: "9"): + byte -= UInt8(ascii: "0") + case UInt8(ascii: "A") ... UInt8(ascii: "Z"): + byte -= UInt8(ascii: "A") + byte += 10 + case UInt8(ascii: "a") ... UInt8(ascii: "z"): + byte -= UInt8(ascii: "a") + byte += 10 + default: + return nil + } + guard byte < radix else { return nil } + self *= BigInt._digits[radix] + self += BigInt._digits[Int(byte)] } if isNegative { - result = -result + self.negate() } - - words = result.words } } diff --git a/Tests/BigIntTests/BigIntTests.swift b/Tests/BigIntTests/BigIntTests.swift index fd7619d..e37be27 100644 --- a/Tests/BigIntTests/BigIntTests.swift +++ b/Tests/BigIntTests/BigIntTests.swift @@ -164,4 +164,27 @@ final class BigIntTests: XCTestCase { XCTAssertEqual(actualStrings, expectedStrings, "Strings: actual, expected") } } + + func testRandomDescriptions() { + for _ in 0 ..< 100 { + let expectedNumber = BigInt(Int.random(in: .min ... .max)) + for radix in 2 ... 36 { + for uppercase in [false, true] { + let expectedString = String(expectedNumber, + radix: radix, + uppercase: uppercase) + let actualNumber = BigInt(expectedString, radix: radix) + XCTAssertNotNil(actualNumber) + if let actualNumber = actualNumber { + XCTAssertEqual(actualNumber, expectedNumber, + "Numbers: actual, expected") + if radix == 10 { + XCTAssertEqual(actualNumber.description, expectedString, + "Strings: actual, expected") + } + } + } + } + } + } } From 8c378528de4e3c86fe7823d7fa298bf9b922e075 Mon Sep 17 00:00:00 2001 From: Ben Rimmington Date: Wed, 15 Jan 2020 00:59:46 +0000 Subject: [PATCH 3/8] [BigInt] Update the Codable conformance --- Sources/BigInt/BigInt.swift | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/Sources/BigInt/BigInt.swift b/Sources/BigInt/BigInt.swift index 9eff36d..ba9eacc 100644 --- a/Sources/BigInt/BigInt.swift +++ b/Sources/BigInt/BigInt.swift @@ -36,8 +36,6 @@ public struct BigInt: SignedInteger { // MARK: - Basic Behaviors -extension BigInt: Codable { } - extension BigInt: Equatable { @inlinable @@ -146,6 +144,28 @@ extension BigInt: LosslessStringConvertible { } } +extension BigInt: Decodable { + + public init(from decoder: Decoder) throws { + let singleValueContainer = try decoder.singleValueContainer() + let description = try singleValueContainer.decode(String.self) + guard let result = BigInt(description) else { + throw DecodingError.dataCorruptedError( + in: singleValueContainer, + debugDescription: "BigInt(\(description.debugDescription)) failed") + } + self = result + } +} + +extension BigInt: Encodable { + + public func encode(to encoder: Encoder) throws { + var singleValueContainer = encoder.singleValueContainer() + try singleValueContainer.encode(description) + } +} + // MARK: - Numeric Protocols extension BigInt: ExpressibleByIntegerLiteral { From 4ec520a7262ff3700888c2c242bc16ae6fc4ec5d Mon Sep 17 00:00:00 2001 From: Ben Rimmington Date: Wed, 15 Jan 2020 03:30:50 +0000 Subject: [PATCH 4/8] [BigIntTests] Update the testCodable() method Top-level JSON fragments might fail on Linux, so encode Range instead. --- Tests/BigIntTests/BigIntTests.swift | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/Tests/BigIntTests/BigIntTests.swift b/Tests/BigIntTests/BigIntTests.swift index e37be27..19cb9e9 100644 --- a/Tests/BigIntTests/BigIntTests.swift +++ b/Tests/BigIntTests/BigIntTests.swift @@ -111,18 +111,17 @@ final class BigIntTests: XCTestCase { XCTAssertEqual(baz, bar) } - func testCodable() { - let foo = BigInt("1234567890123456789012345678901234567890")! - guard let fooData = try? JSONEncoder().encode(foo) else { - XCTFail("Failed to encode \(foo)") - return - } - guard let bar = try? JSONDecoder().decode(BigInt.self, from: fooData) else { - XCTFail("Failed to decode \(String(data: fooData, encoding: .utf8) ?? "")") - return - } - - XCTAssertEqual(foo, bar) + func testCodable() throws { + let lowerBound = BigInt("-1234567890123456789012345678901234567890")! + let upperBound = BigInt("+1234567890123456789012345678901234567890")! + let expectedRange: Range = lowerBound ..< upperBound + + let encoder = JSONEncoder() + let decoder = JSONDecoder() + let data = try encoder.encode(expectedRange) + let actualRange = try decoder.decode(Range.self, from: data) + + XCTAssertEqual(actualRange, expectedRange) } func testMinMaxDescriptions() { From c9d72fc3ae727fe6c5750080981c067b41ccc4d9 Mon Sep 17 00:00:00 2001 From: Ben Rimmington Date: Wed, 15 Jan 2020 03:34:14 +0000 Subject: [PATCH 5/8] [BigIntTests] Trim trailing whitespace --- Tests/BigIntTests/BigIntTests.swift | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/Tests/BigIntTests/BigIntTests.swift b/Tests/BigIntTests/BigIntTests.swift index 19cb9e9..25fa11a 100644 --- a/Tests/BigIntTests/BigIntTests.swift +++ b/Tests/BigIntTests/BigIntTests.swift @@ -85,32 +85,32 @@ final class BigIntTests: XCTestCase { let barz = BigInt(1) << 64 XCTAssertEqual(barz, BigInt(UInt.max) + 1) } - - func testHashable(){ + + func testHashable() { let foo = BigInt("1234567890123456789012345678901234567890")! let bar = BigInt("1234567890123456789112345678901234567890")! let baz: BigInt = 153 - + let dict = [ foo: "Hello", bar: "World", baz: "!" ] - + let hash = foo.hashValue print(hash) - + 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) } - + func testCodable() throws { let lowerBound = BigInt("-1234567890123456789012345678901234567890")! let upperBound = BigInt("+1234567890123456789012345678901234567890")! From 1cb69383a5dbe71f10cf0e02fdb8950f81bb314a Mon Sep 17 00:00:00 2001 From: Ben Rimmington Date: Wed, 15 Jan 2020 03:53:16 +0000 Subject: [PATCH 6/8] [BigIntTests] Wrap to 80 characters --- Tests/BigIntTests/BigIntTests.swift | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Tests/BigIntTests/BigIntTests.swift b/Tests/BigIntTests/BigIntTests.swift index 25fa11a..4533cb4 100644 --- a/Tests/BigIntTests/BigIntTests.swift +++ b/Tests/BigIntTests/BigIntTests.swift @@ -33,7 +33,8 @@ final class BigIntTests: XCTestCase { XCTAssert(-(bar!) > 0) XCTAssertEqual(-(bar!), BigInt(100)) - XCTAssertEqual(-BigInt("-1234567890123456789012345678901234567890")!, BigInt("1234567890123456789012345678901234567890")!) + XCTAssertEqual(-BigInt("-1234567890123456789012345678901234567890")!, + BigInt("1234567890123456789012345678901234567890")!) } func testFloatingConversion() { From b39dd05db31c37db6f8cc4ede786330fd66f94de Mon Sep 17 00:00:00 2001 From: Ben Rimmington Date: Wed, 15 Jan 2020 06:44:41 +0000 Subject: [PATCH 7/8] [BigIntTests] Update the testExample() method --- Tests/BigIntTests/BigIntTests.swift | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Tests/BigIntTests/BigIntTests.swift b/Tests/BigIntTests/BigIntTests.swift index 4533cb4..ab3dde1 100644 --- a/Tests/BigIntTests/BigIntTests.swift +++ b/Tests/BigIntTests/BigIntTests.swift @@ -25,16 +25,16 @@ func fac(_ n: BigInt) -> BigInt { final class BigIntTests: XCTestCase { - func testExample() throws { + func testExample() { let bar = BigInt(exactly: -100) XCTAssertNotNil(bar) - XCTAssert(bar! < 0) - - XCTAssert(-(bar!) > 0) - XCTAssertEqual(-(bar!), BigInt(100)) - + if let bar = bar { + XCTAssertLessThan(bar, 0) + XCTAssertGreaterThan(-bar, 0) + XCTAssertEqual(-bar, BigInt(100)) + } XCTAssertEqual(-BigInt("-1234567890123456789012345678901234567890")!, - BigInt("1234567890123456789012345678901234567890")!) + +BigInt("+1234567890123456789012345678901234567890")!) } func testFloatingConversion() { From 9ddc664ef17c552005062e017e88909b0a5975b8 Mon Sep 17 00:00:00 2001 From: Ben Rimmington Date: Wed, 15 Jan 2020 06:51:21 +0000 Subject: [PATCH 8/8] [BigIntTests] Remove messages from XCTAssert calls --- Tests/BigIntTests/BigIntTests.swift | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/Tests/BigIntTests/BigIntTests.swift b/Tests/BigIntTests/BigIntTests.swift index ab3dde1..ae43cfc 100644 --- a/Tests/BigIntTests/BigIntTests.swift +++ b/Tests/BigIntTests/BigIntTests.swift @@ -160,8 +160,8 @@ final class BigIntTests: XCTestCase { let expectedNumbers: [BigInt] = (-2 ... 2).map({ expectedNumber + $0 }) let actualNumbers: [BigInt] = expectedStrings.compactMap({ BigInt($0) }) let actualStrings: [String] = actualNumbers.map({ $0.description }) - XCTAssertEqual(actualNumbers, expectedNumbers, "Numbers: actual, expected") - XCTAssertEqual(actualStrings, expectedStrings, "Strings: actual, expected") + XCTAssertEqual(actualNumbers, expectedNumbers) + XCTAssertEqual(actualStrings, expectedStrings) } } @@ -176,11 +176,9 @@ final class BigIntTests: XCTestCase { let actualNumber = BigInt(expectedString, radix: radix) XCTAssertNotNil(actualNumber) if let actualNumber = actualNumber { - XCTAssertEqual(actualNumber, expectedNumber, - "Numbers: actual, expected") + XCTAssertEqual(actualNumber, expectedNumber) if radix == 10 { - XCTAssertEqual(actualNumber.description, expectedString, - "Strings: actual, expected") + XCTAssertEqual(actualNumber.description, expectedString) } } }