Skip to content

Commit

Permalink
Add .Clear() to linked.Hashmap (#2917)
Browse files Browse the repository at this point in the history
  • Loading branch information
StephenButtolph authored Apr 5, 2024
1 parent 0eea0bd commit 88d304c
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 6 deletions.
4 changes: 3 additions & 1 deletion cache/lru_cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,9 @@ func (c *LRU[K, _]) evict(key K) {
}

func (c *LRU[K, V]) flush() {
c.elements = linked.NewHashmap[K, V]()
if c.elements != nil {
c.elements.Clear()
}
}

func (c *LRU[_, _]) len() int {
Expand Down
2 changes: 1 addition & 1 deletion cache/lru_sized_cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ func (c *sizedLRU[K, _]) evict(key K) {
}

func (c *sizedLRU[K, V]) flush() {
c.elements = linked.NewHashmap[K, V]()
c.elements.Clear()
c.currentSize = 0
}

Expand Down
19 changes: 15 additions & 4 deletions utils/linked/hashmap.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,14 +63,25 @@ func (lh *Hashmap[K, V]) Get(key K) (V, bool) {
func (lh *Hashmap[K, V]) Delete(key K) bool {
e, ok := lh.entryMap[key]
if ok {
lh.entryList.Remove(e)
delete(lh.entryMap, key)
e.Value = keyValue[K, V]{} // Free the key value pair
lh.freeList = append(lh.freeList, e)
lh.remove(e)
}
return ok
}

func (lh *Hashmap[K, V]) Clear() {
for _, e := range lh.entryMap {
lh.remove(e)
}
}

// remove assumes that [e] is currently in the Hashmap.
func (lh *Hashmap[K, V]) remove(e *ListElement[keyValue[K, V]]) {
delete(lh.entryMap, e.Value.key)
lh.entryList.Remove(e)
e.Value = keyValue[K, V]{} // Free the key value pair
lh.freeList = append(lh.freeList, e)
}

func (lh *Hashmap[K, V]) Len() int {
return len(lh.entryMap)
}
Expand Down
17 changes: 17 additions & 0 deletions utils/linked/hashmap_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,23 @@ func TestHashmap(t *testing.T) {
require.Equal(1, val1, "wrong value")
}

func TestHashmapClear(t *testing.T) {
require := require.New(t)

lh := NewHashmap[int, int]()
lh.Put(1, 1)
lh.Put(2, 2)

lh.Clear()

require.Empty(lh.entryMap)
require.Zero(lh.entryList.Len())
require.Len(lh.freeList, 2)
for _, e := range lh.freeList {
require.Zero(e.Value) // Make sure the value is cleared
}
}

func TestIterator(t *testing.T) {
require := require.New(t)
id1, id2, id3 := ids.GenerateTestID(), ids.GenerateTestID(), ids.GenerateTestID()
Expand Down

0 comments on commit 88d304c

Please sign in to comment.