Skip to content

Use absolute value of hash as bucket #12

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 18, 2022
Merged

Conversation

jrisc
Copy link
Contributor

@jrisc jrisc commented Apr 29, 2022

On 32 bits architechtures, string hashes tend to have negative values.
Such values cannot be used as bucket identifiers for hashtables:

github.com/timtadh/data-structures/hashtable
--- FAIL: TestPutHasGetRemove (0.00s)
panic: runtime error: index out of range [-9] [recovered]
        panic: runtime error: index out of range [-9]

Using absolute value in case of negative hash solves this issue.

@@ -57,7 +65,7 @@ func NewHashTable(initial_size int) *Hash {
}

func (self *Hash) bucket(key Hashable) int {
return key.Hash() % len(self.table)
return abs(key.Hash() % len(self.table))
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
return abs(key.Hash() % len(self.table))
return abs(key.Hash()) % len(self.table)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It makes more sense this way indeed.

On 32 bits architechtures, string hashes tend to have negative values.
Such values cannot be used as bucket identifiers for hashtables. Using
absolute value in case of negative hash solves this issue.

Signed-off-by: Julien Rische <[email protected]>
@timtadh timtadh merged commit 0753935 into timtadh:master Jul 18, 2022
@timtadh
Copy link
Owner

timtadh commented Jul 18, 2022

  1. Thank you so much for your bug fixes
  2. I pushed a tag for this fix at v0.6.2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants