Skip to content

Commit 721af5d

Browse files
committed
This fixes the unlikely event that the generated hashValue happens to be the equal to Int.min, in which case the abs value of it would be Int.max + 1 causing overflow.
1 parent 114becb commit 721af5d

File tree

2 files changed

+2
-2
lines changed

2 files changed

+2
-2
lines changed

Hash Table/HashTable.playground/Sources/HashTable.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ public struct HashTable<Key: Hashable, Value> {
131131
Returns the given key's array index.
132132
*/
133133
private func index(forKey key: Key) -> Int {
134-
return abs(key.hashValue) % buckets.count
134+
return abs(key.hashValue % buckets.count)
135135
}
136136
}
137137

Hash Table/README.markdown

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,7 @@ The hash table does not do anything yet, so let's add the remaining functionalit
141141

142142
```swift
143143
private func index(forKey key: Key) -> Int {
144-
return abs(key.hashValue) % buckets.count
144+
return abs(key.hashValue % buckets.count)
145145
}
146146
```
147147

0 commit comments

Comments
 (0)