Skip to content

Commit 1639c1e

Browse files
[tests] Ensure correct implementation of hash for ChunkedByCount (#123)
1 parent a61c3db commit 1639c1e

File tree

3 files changed

+28
-2
lines changed

3 files changed

+28
-2
lines changed

Sources/Algorithms/Chunked.swift

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -515,12 +515,13 @@ extension ChunkedByCount: Equatable where Base: Equatable {}
515515
// Since we have another stored property of type `Index` on the
516516
// collection, synthesis of `Hashble` conformace would require
517517
// a `Base.Index: Hashable` constraint, so we implement the hasher
518-
// only in terms of `base`. Since the computed index is based on it,
519-
// it should not make a difference here.
518+
// only in terms of `base` and `chunkCount`. Since the computed
519+
// index is based on it, it should not make a difference here.
520520
extension ChunkedByCount: Hashable where Base: Hashable {
521521
@inlinable
522522
public func hash(into hasher: inout Hasher) {
523523
hasher.combine(base)
524+
hasher.combine(chunkCount)
524525
}
525526
}
526527
extension ChunkedByCount.Index: Hashable where Base.Index: Hashable {}

Tests/SwiftAlgorithmsTests/ChunkedTests.swift

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,4 +145,16 @@ final class ChunkedTests: XCTestCase {
145145
validateIndexTraversals(chunks)
146146
}
147147
}
148+
149+
func testChunksOfCountHash() {
150+
let collection1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
151+
let collection2 = [1, 2, 3, 4, 5]
152+
153+
XCTAssertEqualHashValue(
154+
collection1.chunks(ofCount: 1), collection1.chunks(ofCount: 1))
155+
XCTAssertNotEqualHashValue(
156+
collection1.chunks(ofCount: 1), collection2.chunks(ofCount: 1))
157+
XCTAssertNotEqualHashValue(
158+
collection1.chunks(ofCount: 2), collection2.chunks(ofCount: 4))
159+
}
148160
}

Tests/SwiftAlgorithmsTests/TestUtilities.swift

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,19 @@ func XCTAssertEqualHashValue<T: Hashable, U: Hashable>(
203203
)
204204
}
205205

206+
/// Asserts that two hashable instances don't produce the same hash value.
207+
func XCTAssertNotEqualHashValue<T: Hashable, U: Hashable>(
208+
_ expression1: @autoclosure () throws -> T,
209+
_ expression2: @autoclosure () throws -> U,
210+
_ message: @autoclosure () -> String = "",
211+
file: StaticString = #file, line: UInt = #line
212+
) {
213+
XCTAssertNotEqual(
214+
hash(try expression1()), hash(try expression2()),
215+
message(), file: file, line: line
216+
)
217+
}
218+
206219
/// Tests that all index traversal methods behave as expected.
207220
///
208221
/// Verifies the correctness of the implementations of `startIndex`, `endIndex`,

0 commit comments

Comments
 (0)