Insert sets the value under the specified key to the map if it does not exist yet. If a resizing operation is happening concurrently while calling Insert, the item might show up in the map after the resize operation is finished. Returns true if the item was inserted or false if it existed.
(key Key, value Value)
| 125 | // after the resize operation is finished. |
| 126 | // Returns true if the item was inserted or false if it existed. |
| 127 | func (m *Map[Key, Value]) Insert(key Key, value Value) bool { |
| 128 | hash := m.hasher(key) |
| 129 | var ( |
| 130 | existed, inserted bool |
| 131 | element *ListElement[Key, Value] |
| 132 | ) |
| 133 | |
| 134 | for { |
| 135 | store := m.store.Load() |
| 136 | searchStart := store.item(hash) |
| 137 | |
| 138 | if !inserted { // if retrying after insert during grow, do not add to list again |
| 139 | element, existed, inserted = m.linkedList.Add(searchStart, hash, key, value) |
| 140 | if existed { |
| 141 | return false |
| 142 | } |
| 143 | if !inserted { |
| 144 | continue // a concurrent add did interfere, try again |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | count := store.addItem(element) |
| 149 | currentStore := m.store.Load() |
| 150 | if store != currentStore { // retry insert in case of insert during grow |
| 151 | continue |
| 152 | } |
| 153 | |
| 154 | if m.isResizeNeeded(store, count) && m.resizing.CompareAndSwap(0, 1) { |
| 155 | go m.grow(0, true) |
| 156 | } |
| 157 | return true |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | // Set sets the value under the specified key to the map. An existing item for this key will be overwritten. |
| 162 | // If a resizing operation is happening concurrently while calling Set, the item might show up in the map |