Fixed broken linear probe sequence in our hashmap

This commit is contained in:
nocturn9x 2021-10-03 12:23:20 +02:00
parent 408d8cbeaa
commit b66cd7bf4e
2 changed files with 22 additions and 8 deletions

View File

@ -87,13 +87,24 @@ proc findEntry[K, V](self: ptr UncheckedArray[ptr Entry[K, V]], key: K, capacity
var idx = uint64(key.hash()) mod capacity var idx = uint64(key.hash()) mod capacity
while true: while true:
result = self[idx] result = self[idx]
if result.key.isNone() or result.tombstone: if result.key.isNone():
# If we got here, we either found an # We found an empty bucket
# empty bucket or a tombstone. In both cases,
# we're done so we just make sure to reset
# the tombstone field of the entry and just
# exit the loop
break break
elif result.tombstone:
# We found a previously deleted
# entry. In this case, we need
# to make sure the tombstone
# will get overwritten when the
# user wants to add a new value
# that would replace it BUT also
# for it to not stop our linear
# probe sequence. Hence, if the
# key of the tombstone isn't
# the same as the one we're looking
# for, we break out of the loop, otherwise
# we keep probing
if result.key == key:
break
elif result.key.get() == key: elif result.key.get() == key:
# This if will never error out because if # This if will never error out because if
# an entry is a tombstone, its values are # an entry is a tombstone, its values are

View File

@ -58,8 +58,11 @@ proc findEntry(self: ptr UncheckedArray[ptr SimpleEntry], key: ptr Obj, capacity
var idx = uint64(key.hash()) mod capacity var idx = uint64(key.hash()) mod capacity
while true: while true:
result = self[idx] result = self[idx]
if system.`==`(result.key, nil) or result.tombstone: if system.`==`(result.key, nil):
break break
elif result.tombstone:
if result.key == key:
break
elif result.key == key: elif result.key == key:
break break
idx = (idx + 1) mod capacity idx = (idx + 1) mod capacity
@ -166,4 +169,4 @@ proc `$`*(self: ptr SimpleHashMap): string =
if i < self.len() - 1: if i < self.len() - 1:
result &= ", " result &= ", "
i += 1 i += 1
result &= "}" result &= "}"