Skip to content

Commit 68b260e

Browse files
authored
Merge pull request #2881 from readdle/nsindexset-hash
Hash implementation for NSIndexSet
2 parents 7cc937e + 27a734d commit 68b260e

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

Sources/Foundation/NSIndexSet.swift

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,15 @@ open class NSIndexSet : NSObject, NSCopying, NSMutableCopying, NSSecureCoding {
187187
return isEqual(to: indexSet._swiftObject)
188188
}
189189

190+
open override var hash: Int {
191+
var hasher = Hasher()
192+
hasher.combine(_count)
193+
hasher.combine(_ranges.count)
194+
hasher.combine(firstIndex)
195+
hasher.combine(lastIndex)
196+
return hasher.finalize()
197+
}
198+
190199
open var count: Int {
191200
return _count
192201
}

Tests/Foundation/Tests/TestIndexSet.swift

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1240,6 +1240,36 @@ class TestIndexSet : XCTestCase {
12401240
}
12411241
}
12421242

1243+
func testHashValue() throws {
1244+
var sample1 = IndexSet()
1245+
sample1.insert(integersIn: 1..<2)
1246+
sample1.insert(integersIn: 100..<200)
1247+
sample1.insert(integersIn: 1000..<2000)
1248+
1249+
var sample2 = IndexSet()
1250+
sample2.insert(integersIn: 1..<2)
1251+
sample2.insert(integersIn: 100..<200)
1252+
sample2.insert(integersIn: 1000..<2000)
1253+
1254+
XCTAssertEqual(sample1.hashValue, sample2.hashValue)
1255+
1256+
let sample3 = IndexSet([3, 5, 6, 7, 9])
1257+
let sample4 = IndexSet([3, 5, 6, 7, 9])
1258+
XCTAssertEqual(sample3.hashValue, sample4.hashValue)
1259+
1260+
let sample5 = IndexSet([100, NSNotFound - 1, 200])
1261+
let sample6 = IndexSet([100, NSNotFound - 1, 200])
1262+
XCTAssertEqual(sample5.hashValue, sample6.hashValue)
1263+
1264+
let sample7 = IndexSet(integer: NSNotFound - 1)
1265+
let sample8 = IndexSet(integer: NSNotFound - 1)
1266+
XCTAssertEqual(sample7.hashValue, sample8.hashValue)
1267+
1268+
let sample9 = IndexSet()
1269+
let sample10 = IndexSet()
1270+
XCTAssertEqual(sample9.hashValue, sample10.hashValue)
1271+
}
1272+
12431273
static var allTests: [(String, (TestIndexSet) -> () throws -> Void)] {
12441274
return [
12451275
("test_BasicConstruction", test_BasicConstruction),
@@ -1288,6 +1318,7 @@ class TestIndexSet : XCTestCase {
12881318
("testRemoveSplitting", testRemoveSplitting),
12891319
("testCodingRoundtrip", testCodingRoundtrip),
12901320
("testLoadedValuesMatch", testLoadedValuesMatch),
1321+
("testHashValue", testHashValue),
12911322
]
12921323
}
12931324

0 commit comments

Comments
 (0)