From c46b1873d4de1f280f2ed47b19f8227a72b90752 Mon Sep 17 00:00:00 2001 From: Anish Mukherjee Date: Wed, 14 Sep 2022 20:26:07 +0530 Subject: [PATCH] fix infinite for loop bug in Set() operation --- map.go | 37 +++++++++++++++++-------------------- 1 file changed, 17 insertions(+), 20 deletions(-) diff --git a/map.go b/map.go index a3cc9e8..756d8cb 100644 --- a/map.go +++ b/map.go @@ -142,25 +142,24 @@ func (m *HashMap[K, V]) Set(key K, value V) { alloc *element[K, V] created = false ) - for { - data := m.Datamap.Load() - if data == nil { - m.Grow(defaultSize) - continue // read mapdata and slice item again - } - existing := data.indexElement(h) - if existing == nil { - existing = m.listHead - } - if alloc, created = existing.inject(h, key, valPtr); created { - m.numItems.Add(1) - } - count := data.addItemToIndex(alloc) - if resizeNeeded(uintptr(len(data.index)), count) && m.resizing.CompareAndSwap(notResizing, resizingInProgress) { - m.grow(0, true) - } - return +start: + data := m.Datamap.Load() + if data == nil { + m.Grow(defaultSize) + goto start // read mapdata and slice item again + } + existing := data.indexElement(h) + if existing == nil || existing.keyHash > h { + existing = m.listHead + } + if alloc, created = existing.inject(h, key, valPtr); created { + m.numItems.Add(1) + } + + count := data.addItemToIndex(alloc) + if resizeNeeded(uintptr(len(data.index)), count) && m.resizing.CompareAndSwap(notResizing, resizingInProgress) { + m.grow(0, true) } } @@ -273,8 +272,6 @@ func (m *HashMap[K, V]) grow(newSize uintptr, loop bool) { m.Datamap.Store(newdata) - m.fillIndexItems(newdata) // re-index once again just to be safe - if !loop { return }