Skip to content
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

futher simplify remove and shift_back operations in hashmap #491

Merged
merged 3 commits into from
Jun 3, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 10 additions & 12 deletions hashmap/hashmap.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -135,9 +135,7 @@ pub fn contains[K : Hash + Eq, V](self : HashMap[K, V], key : K) -> Bool {
/// Remove a key-value pair from hash map.
pub fn remove[K : Hash + Eq, V](self : HashMap[K, V], key : K) -> Unit {
let hash = key.hash()
for i = 0, idx = hash.land(self.capacity - 1)
i < self.capacity
Copy link
Contributor Author

Choose a reason for hiding this comment

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

i < self.capacity check is not needed?

i = i + 1, idx = (idx + 1).land(self.capacity - 1) {
for i = 0, idx = hash.land(self.capacity - 1) {
match self.entries[idx] {
Some(entry) => {
if entry.hash == hash && entry.key == key {
Expand All @@ -147,37 +145,37 @@ pub fn remove[K : Hash + Eq, V](self : HashMap[K, V], key : K) -> Unit {
break
}
if i > entry.psl {
return
break
}
continue i + 1, (idx + 1).land(self.capacity - 1)
}
None => ()
None => break
}
}
}

fn shift_back[K : Hash, V](self : HashMap[K, V], start_index : Int) -> Unit {
for i = 0, prev = start_index, curr = (start_index + 1).land(
self.capacity - 1,
Copy link
Contributor Author

Choose a reason for hiding this comment

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

the loop state variable i is not needed

)
i < self.entries.length()
i = i + 1, prev = curr, curr = (curr + 1).land(self.capacity - 1) {
for prev = start_index, curr = (start_index + 1).land(self.capacity - 1) {
match self.entries[curr] {
Some({ psl, hash, key, value, .. }) => {
if psl == 0 {
break
}
self.entries[prev] = Some({ psl: psl - 1, hash, key, value })
self.entries[curr] = None
continue curr, (curr + 1).land(self.capacity - 1)
}
None => break
}
}
}

// TODO: this could be further optimized
fn grow[K : Hash + Eq, V](self : HashMap[K, V]) -> Unit {
let old_entries = self.entries
self.entries = FixedArray::make(self.capacity.lsl(1), None)
self.capacity = self.capacity * 2
let new_capacity = self.capacity.lsl(1)
self.entries = FixedArray::make(new_capacity, None)
self.capacity = new_capacity
self.size = 0
for i = 0; i < old_entries.length(); i = i + 1 {
match old_entries[i] {
Expand Down