diff --git a/Sources/Algorithms/Split.swift b/Sources/Algorithms/Split.swift index ffab53d..a1e941a 100644 --- a/Sources/Algorithms/Split.swift +++ b/Sources/Algorithms/Split.swift @@ -12,6 +12,7 @@ //===----------------------------------------------------------------------===// // SplitSequence //===----------------------------------------------------------------------===// + /// A sequence that lazily splits a base sequence into subsequences separated by /// elements that satisfy the given `whereSeparator` predicate. /// @@ -335,6 +336,7 @@ extension LazySequenceProtocol where Element: Equatable { //===----------------------------------------------------------------------===// // SplitCollection //===----------------------------------------------------------------------===// + /// A collection that lazily splits a base collection into subsequences /// separated by elements that satisfy the given `whereSeparator` predicate. /// diff --git a/Tests/SwiftAlgorithmsTests/AdjacentPairsTests.swift b/Tests/SwiftAlgorithmsTests/AdjacentPairsTests.swift index 98396aa..f07fe52 100644 --- a/Tests/SwiftAlgorithmsTests/AdjacentPairsTests.swift +++ b/Tests/SwiftAlgorithmsTests/AdjacentPairsTests.swift @@ -70,11 +70,11 @@ final class AdjacentPairsTests: XCTestCase { } func testIndexTraversals() { - validateIndexTraversals( - (0..<0).adjacentPairs(), - (0..<1).adjacentPairs(), - (0..<2).adjacentPairs(), - (0..<5).adjacentPairs()) + let validator = IndexValidator>>() + validator.validate((0..<0).adjacentPairs(), expectedCount: 0) + validator.validate((0..<1).adjacentPairs(), expectedCount: 0) + validator.validate((0..<2).adjacentPairs(), expectedCount: 1) + validator.validate((0..<5).adjacentPairs(), expectedCount: 4) } func testLaziness() { diff --git a/Tests/SwiftAlgorithmsTests/ChainTests.swift b/Tests/SwiftAlgorithmsTests/ChainTests.swift index 104a6a2..6183cf3 100644 --- a/Tests/SwiftAlgorithmsTests/ChainTests.swift +++ b/Tests/SwiftAlgorithmsTests/ChainTests.swift @@ -36,16 +36,17 @@ final class ChainTests: XCTestCase { } func testChainIndexTraversals() { - validateIndexTraversals( - chain("abcd", "XYZ"), - chain("abcd", ""), - chain("", "XYZ"), - chain("", ""), - indices: { chain in + let validator = IndexValidator>( + indicesIncludingEnd: { chain in chain.base1.indices.map { .init(first: $0) } + chain.base2.indices.map { .init(second: $0) } + [.init(second: chain.base2.endIndex)] }) + + validator.validate(chain("abcd", "XYZ"), expectedCount: 4 + 3) + validator.validate(chain("abcd", ""), expectedCount: 4 + 0) + validator.validate(chain("", "XYZ"), expectedCount: 0 + 3) + validator.validate(chain("", ""), expectedCount: 0 + 0) } func testChainIndexOffsetAcrossBoundary() { diff --git a/Tests/SwiftAlgorithmsTests/ChunkedTests.swift b/Tests/SwiftAlgorithmsTests/ChunkedTests.swift index 56a7a6f..811f787 100644 --- a/Tests/SwiftAlgorithmsTests/ChunkedTests.swift +++ b/Tests/SwiftAlgorithmsTests/ChunkedTests.swift @@ -67,7 +67,7 @@ final class ChunkedTests: XCTestCase { let lazyChunks = fruits.lazy.chunked(on: { $0.first }) validateFruitChunks(lazyChunks.map { $1 }) - validateIndexTraversals(lazyChunks) + IndexValidator().validate(lazyChunks) } func testChunkedBy() { @@ -75,7 +75,7 @@ final class ChunkedTests: XCTestCase { let lazyChunks = fruits.lazy.chunked(by: { $0.first == $1.first }) validateFruitChunks(lazyChunks) - validateIndexTraversals(lazyChunks) + IndexValidator().validate(lazyChunks) } func testChunkedByComparesConsecutiveElements() { @@ -94,7 +94,7 @@ final class ChunkedTests: XCTestCase { [1, 2, 3, 4, 6, 7, 8, 9].lazy.chunked(by: { $1 - $0 == 1 }).reversed(), [[6, 7, 8, 9], [1, 2, 3, 4]]) - validateIndexTraversals([1, 2, 3].lazy.chunked(by: { $1 - $0 == 1 })) + IndexValidator().validate([1, 2, 3].lazy.chunked(by: { $1 - $0 == 1 })) } func testChunkedLazy() { @@ -159,15 +159,18 @@ final class ChunkedTests: XCTestCase { func testEmptyChunksOfCountTraversal() { let emptyChunks = [Int]().chunks(ofCount: 1) - validateIndexTraversals(emptyChunks) + IndexValidator().validate(emptyChunks, expectedCount: 0) } func testChunksOfCountTraversal() { - for i in 1..<10 { - let collection = (1...50).map { $0 } - let chunks = collection.chunks(ofCount: i) - - validateIndexTraversals(chunks) + let validator = IndexValidator>>() + + for i in 1...10 { + let range = 1...50 + let chunks = range.chunks(ofCount: i) + validator.validate( + chunks, + expectedCount: range.count / i + (range.count % i).signum()) } } } diff --git a/Tests/SwiftAlgorithmsTests/CompactedTests.swift b/Tests/SwiftAlgorithmsTests/CompactedTests.swift index dbff888..a23d015 100644 --- a/Tests/SwiftAlgorithmsTests/CompactedTests.swift +++ b/Tests/SwiftAlgorithmsTests/CompactedTests.swift @@ -37,8 +37,9 @@ final class CompactedTests: XCTestCase { } func testCollectionTraversals() { + let validator = IndexValidator>() for array in self.tests { - validateIndexTraversals(array.compacted()) + validator.validate(array.compacted()) } } } diff --git a/Tests/SwiftAlgorithmsTests/IntersperseTests.swift b/Tests/SwiftAlgorithmsTests/IntersperseTests.swift index 50baa69..49c1376 100644 --- a/Tests/SwiftAlgorithmsTests/IntersperseTests.swift +++ b/Tests/SwiftAlgorithmsTests/IntersperseTests.swift @@ -26,25 +26,21 @@ final class IntersperseTests: XCTestCase { func testString() { let interspersed = "ABCDE".interspersed(with: "-") XCTAssertEqualSequences(interspersed, "A-B-C-D-E") - validateIndexTraversals(interspersed) } func testStringEmpty() { let interspersed = "".interspersed(with: "-") XCTAssertEqualSequences(interspersed, "") - validateIndexTraversals(interspersed) } func testArray() { let interspersed = [1,2,3,4].interspersed(with: 0) XCTAssertEqualSequences(interspersed, [1,0,2,0,3,0,4]) - validateIndexTraversals(interspersed) } func testArrayEmpty() { let interspersed = [].interspersed(with: 0) XCTAssertEqualSequences(interspersed, []) - validateIndexTraversals(interspersed) } func testCollection() { @@ -55,7 +51,14 @@ final class IntersperseTests: XCTestCase { func testBidirectionalCollection() { let reversed = "ABCDE".interspersed(with: "-").reversed() XCTAssertEqualSequences(reversed, "E-D-C-B-A") - validateIndexTraversals(reversed) + } + + func testIndexTraversals() { + let validator = IndexValidator>() + validator.validate("".interspersed(with: "-"), expectedCount: 0) + validator.validate("A".interspersed(with: "-"), expectedCount: 1) + validator.validate("AB".interspersed(with: "-"), expectedCount: 3) + validator.validate("ABCDE".interspersed(with: "-"), expectedCount: 9) } func testIntersperseLazy() { @@ -83,10 +86,18 @@ final class IntersperseTests: XCTestCase { } func testInterspersedMapIndexTraversals() { - validateIndexTraversals( - (0..<0).lazy.interspersedMap({ $0 }, with: { _, _ in 100 }), - (0..<1).lazy.interspersedMap({ $0 }, with: { _, _ in 100 }), - (0..<2).lazy.interspersedMap({ $0 }, with: { _, _ in 100 }), - (0..<5).lazy.interspersedMap({ $0 }, with: { _, _ in 100 })) + let validator = IndexValidator, Int>>() + validator.validate( + (0..<0).lazy.interspersedMap({ $0 }, with: {_, _ in 100 }), + expectedCount: 0) + validator.validate( + (0..<1).lazy.interspersedMap({ $0 }, with: {_, _ in 100 }), + expectedCount: 1) + validator.validate( + (0..<2).lazy.interspersedMap({ $0 }, with: {_, _ in 100 }), + expectedCount: 3) + validator.validate( + (0..<5).lazy.interspersedMap({ $0 }, with: {_, _ in 100 }), + expectedCount: 9) } } diff --git a/Tests/SwiftAlgorithmsTests/JoinedTests.swift b/Tests/SwiftAlgorithmsTests/JoinedTests.swift index cb70558..690659e 100644 --- a/Tests/SwiftAlgorithmsTests/JoinedTests.swift +++ b/Tests/SwiftAlgorithmsTests/JoinedTests.swift @@ -111,15 +111,22 @@ final class JoinedTests: XCTestCase { } func testJoinedIndexTraversals() { + let validator = IndexValidator>() + // the last test case takes too long to run for strings in stringArrays.dropLast() { - validateIndexTraversals(strings.joined() as FlattenCollection) - validateIndexTraversals(strings.joined(by: ", ")) + validator.validate(strings.joined() as FlattenCollection) } + } + + func testJoinedByIndexTraversals() { + let validator1 = IndexValidator>() + let validator2 = IndexValidator>() + // the last test case takes too long to run for (strings, separator) in product(stringArrays.dropLast(), ["", " ", ", "]) { - validateIndexTraversals(strings.joined(by: separator)) - validateIndexTraversals(strings.lazy.joined(by: { _, _ in separator })) + validator1.validate(strings.joined(by: separator)) + validator2.validate(strings.lazy.joined(by: { _, _ in separator })) } } } diff --git a/Tests/SwiftAlgorithmsTests/ProductTests.swift b/Tests/SwiftAlgorithmsTests/ProductTests.swift index 37b434f..b04932e 100644 --- a/Tests/SwiftAlgorithmsTests/ProductTests.swift +++ b/Tests/SwiftAlgorithmsTests/ProductTests.swift @@ -39,17 +39,18 @@ final class ProductTests: XCTestCase { } func testProductIndexTraversals() { - validateIndexTraversals( - product([1, 2, 3, 4], "abc"), - product([1, 2, 3, 4], ""), - product([], "abc"), - product([], ""), - indices: { product in + let validator = IndexValidator>( + indicesIncludingEnd: { product in product.base1.indices.flatMap { i1 in product.base2.indices.map { i2 in .init(i1: i1, i2: i2) } } + [.init(i1: product.base1.endIndex, i2: product.base2.startIndex)] }) + + validator.validate(product([1, 2, 3, 4], "abc"), expectedCount: 4 * 3) + validator.validate(product([1, 2, 3, 4], ""), expectedCount: 4 * 0) + validator.validate(product([], "abc"), expectedCount: 0 * 3) + validator.validate(product([], ""), expectedCount: 0 * 0) } } diff --git a/Tests/SwiftAlgorithmsTests/ReductionsTests.swift b/Tests/SwiftAlgorithmsTests/ReductionsTests.swift index 2b5b379..76322d3 100644 --- a/Tests/SwiftAlgorithmsTests/ReductionsTests.swift +++ b/Tests/SwiftAlgorithmsTests/ReductionsTests.swift @@ -51,6 +51,13 @@ final class ReductionsTests: XCTestCase { XCTAssertNoThrow(try [].reductions(0) { _, _ in throw TestError() }) XCTAssertThrowsError(try [1].reductions(0) { _, _ in throw TestError() }) } + + func testExclusiveIndexTraversals() { + let validator = IndexValidator, Int>>() + validator.validate((0..<0).lazy.reductions(0, +), expectedCount: 1) + validator.validate((0..<1).lazy.reductions(0, +), expectedCount: 2) + validator.validate((0..<4).lazy.reductions(0, +), expectedCount: 5) + } // MARK: - Inclusive Reductions @@ -77,4 +84,11 @@ final class ReductionsTests: XCTestCase { XCTAssertNoThrow(try [1].reductions { _, _ in throw TestError() }) XCTAssertThrowsError(try [1, 1].reductions { _, _ in throw TestError() }) } + + func testInclusiveIndexTraversals() { + let validator = IndexValidator>>() + validator.validate((0..<0).lazy.reductions(+), expectedCount: 0) + validator.validate((0..<1).lazy.reductions(+), expectedCount: 1) + validator.validate((0..<4).lazy.reductions(+), expectedCount: 4) + } } diff --git a/Tests/SwiftAlgorithmsTests/StrideTests.swift b/Tests/SwiftAlgorithmsTests/StrideTests.swift index 6143a46..3306c7f 100644 --- a/Tests/SwiftAlgorithmsTests/StrideTests.swift +++ b/Tests/SwiftAlgorithmsTests/StrideTests.swift @@ -88,29 +88,36 @@ final class StridingTests: XCTestCase { } func testIndexTraversals() { - let empty = [Int]() - validateIndexTraversals( - empty.striding(by: 1), - empty.striding(by: 2) - ) - let zero_to_one_hundered_range = 0...100 - validateIndexTraversals( - zero_to_one_hundered_range.striding(by: 10), - zero_to_one_hundered_range.striding(by: 11), - zero_to_one_hundered_range.striding(by: 101) - ) - let zero_to_one_hundered_array = Array(zero_to_one_hundered_range) - validateIndexTraversals( - zero_to_one_hundered_array.striding(by: 10), - zero_to_one_hundered_array.striding(by: 11), - zero_to_one_hundered_array.striding(by: 101) - ) - let string = "swift rocks".map(String.init) - validateIndexTraversals( - string.striding(by: 1), - string.striding(by: 2), - string.striding(by: 10) - ) + do { + let empty = [Int]() + let validator = IndexValidator>() + validator.validate(empty.striding(by: 1)) + validator.validate(empty.striding(by: 2)) + } + + do { + let range = 0...100 + let validator = IndexValidator>>() + validator.validate(range.striding(by: 10)) + validator.validate(range.striding(by: 11)) + validator.validate(range.striding(by: 101)) + } + + do { + let array = Array(0...100) + let validator = IndexValidator>() + validator.validate(array.striding(by: 10)) + validator.validate(array.striding(by: 11)) + validator.validate(array.striding(by: 101)) + } + + do { + let string = "swift rocks" + let validator = IndexValidator>() + validator.validate(string.striding(by: 1)) + validator.validate(string.striding(by: 2)) + validator.validate(string.striding(by: 10)) + } } diff --git a/Tests/SwiftAlgorithmsTests/TestUtilities.swift b/Tests/SwiftAlgorithmsTests/TestUtilities.swift index 9acc458..2c24aed 100644 --- a/Tests/SwiftAlgorithmsTests/TestUtilities.swift +++ b/Tests/SwiftAlgorithmsTests/TestUtilities.swift @@ -163,94 +163,162 @@ func XCTAssertEqualCollections( } } -/// Tests that all index traversal methods behave as expected. -/// -/// Verifies the correctness of the implementations of `startIndex`, `endIndex`, -/// `indices`, `count`, `isEmpty`, `index(before:)`, `index(after:)`, -/// `index(_:offsetBy:)`, `index(_:offsetBy:limitedBy:)`, and -/// `distance(from:to:)` by calling them with just about all possible input -/// combinations. When provided, the `indices` function is used to to test the -/// collection methods against. -/// -/// - Parameters: -/// - collections: The collections to be validated. -/// - indices: A closure that returns the expected indices of the given -/// collection, including its `endIndex`, in ascending order. Only use this -/// parameter if you are able to compute the indices of the collection -/// independently of the `Collection` conformance, e.g. by using the -/// contents of the collection directly. -/// -/// - Complexity: O(*n*^3) where *n* is the length of the collection per -/// collection if the collection conforms to `RandomAccesCollection`, -/// otherwise O(*n*^4). -func validateIndexTraversals( - _ collections: C..., - indices: ((C) -> [C.Index])? = nil, - file: StaticString = #file, line: UInt = #line -) where C: BidirectionalCollection { - for c in collections { - let indicesIncludingEnd = indices?(c) ?? (c.indices + [c.endIndex]) +struct IndexValidator { + let testRandomAccess = true + let indicesIncludingEnd: (C) -> [C.Index] + + /// Creates a new instance of an index validator that can verify that indices + /// of a collection behave correctly and consistently. + /// + /// Usage: + /// + /// let validator = IndexValidator>() + /// validator.validate("abc".reversed()) + /// validator.validate("xyz".reversed(), expectedCount: 3) + /// + /// - Parameters: + /// - testRandomAccess: If `true`, also tests the correctness of the methods + /// `index(_:offsetBy:)`, `index(_:offsetBy:limitedBy:)`, and + /// `distance(from:to:)`. Only useful if the collection overrides these + /// methods. Defaults to `true`. + /// - indicesIncludingEnd: A closure that returns the expected indices of + /// the given collection, including its `endIndex`, in ascending order. + /// Only use this parameter if you are able to compute the indices of the + /// collection independently of the `Collection` conformance, e.g. by + /// using the contents of the collection directly. + init( + testRandomAccess: Bool = true, + indicesIncludingEnd: @escaping (C) -> [C.Index] = { $0.indices + [$0.endIndex] } + ) { + self.indicesIncludingEnd = indicesIncludingEnd + } +} + +extension IndexValidator { + fileprivate struct Validator { + let collection: C + let count: Int + let indicesIncludingEnd: [C.Index] + let file: StaticString + let line: UInt + } + + /// Verifies that all index traversal methods behave as expected. + /// + /// Verifies the correctness of the implementations of `startIndex`, + /// `endIndex`, `indices`, `count`, `isEmpty`, `index(before:)`, + /// `index(after:)`, `index(_:offsetBy:)`, `index(_:offsetBy:limitedBy:)`, and + /// `distance(from:to:)` by calling them with just about all possible input + /// combinations. + /// + /// - Parameters: + /// - collection: The collection to be validated. + /// - expectedCount: + /// + /// - Complexity: O(*n*^3) where *n* is the length of the collection if the + /// collection conforms to `RandomAccesCollection`, otherwise O(*n*^4). + func validate( + _ collection: C, + expectedCount: Int? = nil, + file: StaticString = #file, line: UInt = #line + ) { + let indicesIncludingEnd = indicesIncludingEnd(collection) let count = indicesIncludingEnd.count - 1 + let validator = Validator( + collection: collection, + count: count, + indicesIncludingEnd: indicesIncludingEnd, + file: file, line: line) + + validator.validateForward( + testRandomAccess: testRandomAccess, + expectedCount: expectedCount) + } +} + +extension IndexValidator where C: BidirectionalCollection { + func validate( + _ collection: C, expectedCount: Int? = nil, + file: StaticString = #file, line: UInt = #line + ) { + let indicesIncludingEnd = indicesIncludingEnd(collection) + let count = indicesIncludingEnd.count - 1 + + let validator = Validator( + collection: collection, + count: count, + indicesIncludingEnd: indicesIncludingEnd, + file: file, line: line) + + validator.validateForward( + testRandomAccess: testRandomAccess, + expectedCount: expectedCount) + validator.validateBackward(testRandomAccess: testRandomAccess) + } +} + +extension IndexValidator.Validator { + func validateForward(testRandomAccess: Bool, expectedCount: Int?) { + if let expectedCount = expectedCount { + XCTAssertEqual( + expectedCount, count, "Count mismatch", file: file, line: line) + } + XCTAssertEqual( - c.count, count, + collection.count, count, "Count mismatch", file: file, line: line) XCTAssertEqual( - c.isEmpty, count == 0, + collection.isEmpty, count == 0, "Emptiness mismatch", file: file, line: line) XCTAssertEqual( - c.startIndex, indicesIncludingEnd.first, + collection.startIndex, indicesIncludingEnd.first, "`startIndex` does not equal the first index", file: file, line: line) XCTAssertEqual( - c.endIndex, indicesIncludingEnd.last, + collection.endIndex, indicesIncludingEnd.last, "`endIndex` does not equal the last index", file: file, line: line) - // `index(after:)` - do { - var index = c.startIndex - - for (offset, expected) in indicesIncludingEnd.enumerated().dropFirst() { - c.formIndex(after: &index) - XCTAssertEqual( - index, expected, - """ - `startIndex` incremented \(offset) times does not equal index at \ - offset \(offset) - """, - file: file, line: line) - } - } + validateIndexAfter() + validateIndices() + validateIndexComparisons() - // `index(before:)` - do { - var index = c.endIndex - - for (offset, expected) in indicesIncludingEnd.enumerated().dropLast().reversed() { - c.formIndex(before: &index) - XCTAssertEqual( - index, expected, - """ - `endIndex` decremented \(count - offset) times does not equal index \ - at offset \(offset) - """, - file: file, line: line) - } + if testRandomAccess { + validateDistanceFromTo() + validateIndexOffsetBy() + validateIndexOffsetByLimitedBy() } + } + + func validateIndexAfter() { + var index = collection.startIndex - // `indices` - XCTAssertEqual(c.indices.count, count) - for (offset, index) in c.indices.enumerated() { + for (offset, expected) in indicesIncludingEnd.enumerated().dropFirst() { + collection.formIndex(after: &index) + XCTAssertEqual( + index, expected, + """ + `startIndex` incremented \(offset) times does not equal index at \ + offset \(offset) + """, + file: file, line: line) + } + } + + func validateIndices() { + XCTAssertEqual(collection.indices.count, count) + for (offset, index) in collection.indices.enumerated() { XCTAssertEqual( index, indicesIncludingEnd[offset], "Index mismatch at offset \(offset) in `indices`", file: file, line: line) } - - // index comparison + } + + func validateIndexComparisons() { for (offsetA, a) in indicesIncludingEnd.enumerated() { XCTAssertEqual( a, a, @@ -274,21 +342,14 @@ func validateIndexTraversals( file: file, line: line) } } - - // `index(_:offsetBy:)` and `distance(from:to:)` + } + + func validateDistanceFromTo() { for (startOffset, start) in indicesIncludingEnd.enumerated() { - for (endOffset, end) in indicesIncludingEnd.enumerated() { + for (endOffset, end) in indicesIncludingEnd.enumerated().dropFirst(startOffset) { let distance = endOffset - startOffset - XCTAssertEqual( - c.index(start, offsetBy: distance), end, - """ - Index at offset \(startOffset) offset by \(distance) does not equal \ - index at offset \(endOffset) - """, - file: file, line: line) - XCTAssertEqual( - c.distance(from: start, to: end), distance, + collection.distance(from: start, to: end), distance, """ Distance from index at offset \(startOffset) to index at offset \ \(endOffset) does not equal \(distance) @@ -296,18 +357,34 @@ func validateIndexTraversals( file: file, line: line) } } - - // `index(_:offsetBy:limitedBy:)` + } + + func validateIndexOffsetBy() { + for (startOffset, start) in indicesIncludingEnd.enumerated() { + for (endOffset, end) in indicesIncludingEnd.enumerated().dropFirst(startOffset) { + let distance = endOffset - startOffset + XCTAssertEqual( + collection.index(start, offsetBy: distance), end, + """ + Index at offset \(startOffset) offset by \(distance) does not \ + equal index at offset \(endOffset) + """, + file: file, line: line) + } + } + } + + func validateIndexOffsetByLimitedBy() { for (startOffset, start) in indicesIncludingEnd.enumerated() { for (limitOffset, limit) in indicesIncludingEnd.enumerated() { // verifies that the target index corresponding to each offset in // `range` can or cannot be reached from `start` using - // `chain.index(start, offsetBy: _, limitedBy: limit)`, depending on the - // value of `pastLimit` + // `chain.index(start, offsetBy: _, limitedBy: limit)`, depending on + // the value of `pastLimit` func checkTargetRange(_ range: ClosedRange, pastLimit: Bool) { for targetOffset in range { let distance = targetOffset - startOffset - let end = c.index(start, offsetBy: distance, limitedBy: limit) + let end = collection.index(start, offsetBy: distance, limitedBy: limit) if pastLimit { XCTAssertNil( @@ -330,7 +407,6 @@ func validateIndexTraversals( } } - // forward offsets if limit >= start { // the limit has an effect checkTargetRange(startOffset...limitOffset, pastLimit: false) @@ -339,8 +415,100 @@ func validateIndexTraversals( // the limit has no effect checkTargetRange(startOffset...count, pastLimit: false) } + } + } + } +} + +extension IndexValidator.Validator where C: BidirectionalCollection { + func validateBackward(testRandomAccess: Bool) { + validateIndexBefore() + + if testRandomAccess { + validateDistanceFromTo() + validateIndexOffsetBy() + validateIndexOffsetByLimitedBy() + } + } + + func validateIndexBefore() { + var index = collection.endIndex + + for (offset, expected) in indicesIncludingEnd.enumerated().dropLast().reversed() { + collection.formIndex(before: &index) + XCTAssertEqual( + index, expected, + """ + `endIndex` decremented \(count - offset) times does not equal index \ + at offset \(offset) + """, + file: file, line: line) + } + } + + func validateDistanceFromTo() { + for (startOffset, start) in indicesIncludingEnd.enumerated() { + for (endOffset, end) in indicesIncludingEnd.enumerated().prefix(startOffset) { + let distance = endOffset - startOffset + XCTAssertEqual( + collection.distance(from: start, to: end), distance, + """ + Distance from index at offset \(startOffset) to index at offset \ + \(endOffset) does not equal \(distance) + """, + file: file, line: line) + } + } + } + + func validateIndexOffsetBy() { + for (startOffset, start) in indicesIncludingEnd.enumerated() { + for (endOffset, end) in indicesIncludingEnd.enumerated().prefix(startOffset) { + let distance = endOffset - startOffset + XCTAssertEqual( + collection.index(start, offsetBy: distance), end, + """ + Index at offset \(startOffset) offset by \(distance) does not \ + equal index at offset \(endOffset) + """, + file: file, line: line) + } + } + } + + func validateIndexOffsetByLimitedBy() { + for (startOffset, start) in indicesIncludingEnd.enumerated() { + for (limitOffset, limit) in indicesIncludingEnd.enumerated() { + // verifies that the target index corresponding to each offset in + // `range` can or cannot be reached from `start` using + // `chain.index(start, offsetBy: _, limitedBy: limit)`, depending on + // the value of `pastLimit` + func checkTargetRange(_ range: ClosedRange, pastLimit: Bool) { + for targetOffset in range { + let distance = targetOffset - startOffset + let end = collection.index(start, offsetBy: distance, limitedBy: limit) + + if pastLimit { + XCTAssertNil( + end, + """ + Index at offset \(startOffset) offset by \(distance) limited \ + by index at offset \(limitOffset) does not equal `nil` + """, + file: file, line: line) + } else { + XCTAssertEqual( + end, indicesIncludingEnd[targetOffset], + """ + Index at offset \(startOffset) offset by \(distance) limited \ + by index at offset \(limitOffset) does not equal index at \ + offset \(targetOffset) + """, + file: file, line: line) + } + } + } - // backward offsets if limit <= start { // the limit has an effect checkTargetRange(limitOffset...startOffset, pastLimit: false) diff --git a/Tests/SwiftAlgorithmsTests/WindowsTests.swift b/Tests/SwiftAlgorithmsTests/WindowsTests.swift index ae422f5..ce602c3 100644 --- a/Tests/SwiftAlgorithmsTests/WindowsTests.swift +++ b/Tests/SwiftAlgorithmsTests/WindowsTests.swift @@ -12,8 +12,7 @@ import XCTest @testable import Algorithms -final class windowsTests: XCTestCase { - +final class WindowsTests: XCTestCase { func testWindowsOfString() { let s = "swift" let w = s.windows(ofCount: 2) @@ -87,22 +86,23 @@ final class windowsTests: XCTestCase { } func testWindowsIndexTraversals() { - validateIndexTraversals( - "".windows(ofCount: 1), - "a".windows(ofCount: 1), - "ab".windows(ofCount: 1), - "abc".windows(ofCount: 1), - "".windows(ofCount: 3), - "a".windows(ofCount: 3), - "abc".windows(ofCount: 3), - "abcdefgh".windows(ofCount: 3), - indices: { windows in + let validator = IndexValidator>( + indicesIncludingEnd: { windows in let endIndex = windows.base.endIndex let indices = windows.base.indices + [endIndex] return zip(indices, indices.dropFirst(windows.windowSize)) .map { .init(lowerBound: $0, upperBound: $1) } - + [.init(lowerBound: endIndex, upperBound: endIndex)] + + [.init(lowerBound: endIndex, upperBound: endIndex)] }) + + validator.validate("".windows(ofCount: 1), expectedCount: 0) + validator.validate("a".windows(ofCount: 1), expectedCount: 1) + validator.validate("ab".windows(ofCount: 1), expectedCount: 2) + validator.validate("abc".windows(ofCount: 1), expectedCount: 3) + validator.validate("".windows(ofCount: 3), expectedCount: 0) + validator.validate("a".windows(ofCount: 3), expectedCount: 0) + validator.validate("abc".windows(ofCount: 3), expectedCount: 1) + validator.validate("abcdefgh".windows(ofCount: 3), expectedCount: 6) } func testWindowsLazy() {