diff --git a/common/xsync/map.go b/common/xsync/map.go index fd8faa8b1..4892ba277 100644 --- a/common/xsync/map.go +++ b/common/xsync/map.go @@ -1,6 +1,6 @@ package xsync -// copy and modified from https://github.com/puzpuzpuz/xsync/blob/v4.2.0/map.go +// copy and modified from https://github.com/puzpuzpuz/xsync/blob/v4.5.0/map.go // which is licensed under Apache v2. // // mihomo modified: @@ -37,11 +37,10 @@ const ( // minimum counter stripes to use minMapCounterLen = 8 // maximum counter stripes to use; stands for around 4KB of memory - maxMapCounterLen = 32 - defaultMeta uint64 = 0x8080808080808080 - metaMask uint64 = 0xffffffffff - defaultMetaMasked uint64 = defaultMeta & metaMask - emptyMetaSlot uint8 = 0x80 + maxMapCounterLen = 32 + metaMask = 0xffffffffff + occupiedMeta = 0x8080808080808080 + occupiedMetaMasked = occupiedMeta & metaMask // minimal number of buckets to transfer when participating in cooperative // resize; should be at least defaultMinMapTableLen minResizeTransferStride = 64 @@ -136,6 +135,7 @@ type Map[K comparable, V any] struct { resizeIdx atomic.Int64 minTableLen int growOnly bool + intKey bool } type mapTable[K comparable, V any] struct { @@ -145,6 +145,8 @@ type mapTable[K comparable, V any] struct { // occupies min(buckets_memory/1024, 64KB) of memory size []counterStripe seed maphash.Seed + // intSeed is derived from seed for fast integer hashing + intSeed uint64 } type counterStripe struct { @@ -212,7 +214,7 @@ func NewMap[K comparable, V any](options ...func(*MapConfig)) *Map[K, V] { m := &Map[K, V]{} if c.sizeHint > defaultMinMapTableLen*entriesPerMapBucket { - tableLen := nextPowOf2(uint32((float64(c.sizeHint) / entriesPerMapBucket) / mapLoadFactor)) + tableLen := nextPowOf2(uint64((float64(c.sizeHint) / entriesPerMapBucket) / mapLoadFactor)) m.minTableLen = int(tableLen) } m.growOnly = c.growOnly @@ -224,16 +226,51 @@ func (m *Map[K, V]) init() { m.minTableLen = defaultMinMapTableLen } m.resizeCond = *sync.NewCond(&m.resizeMu) + m.intKey = detectIntKey[K]() table := newMapTable[K, V](m.minTableLen, maphash.MakeSeed()) m.minTableLen = len(table.buckets) m.table.Store(table) } +// detectIntKey returns true if the key type is an integer type. +func detectIntKey[K comparable]() bool { + var zero K + switch any(zero).(type) { + case int, uint, uintptr, int64, uint64, int32, uint32, int16, uint16, int8, uint8: + return true + default: + return false + } +} + +// hashUint64 computes a hash for integer keys using two rounds of +// multiply-xorshift mixing (wyhash-style). +// This is significantly faster than maphash.Comparable for integer types. +func hashUint64(seed, v uint64) uint64 { + hi, lo := bits.Mul64(v^seed, 0x2d358dccaa6c78a5) + hi2, lo2 := bits.Mul64(hi^lo, 0x8bb84b93962eacc9) + return hi2 ^ lo2 +} + +// toUint64 reinterprets integer-like keys as uint64 for hashUint64. +// The size switch is folded per instantiated K by the compiler. +func toUint64[K any](k K) uint64 { + switch unsafe.Sizeof(k) { + case 8: + return *(*uint64)(unsafe.Pointer(&k)) + case 4: + return uint64(*(*uint32)(unsafe.Pointer(&k))) + case 2: + return uint64(*(*uint16)(unsafe.Pointer(&k))) + case 1: + return uint64(*(*uint8)(unsafe.Pointer(&k))) + default: + panic("unreachable") + } +} + func newMapTable[K comparable, V any](minTableLen int, seed maphash.Seed) *mapTable[K, V] { buckets := make([]bucketPadded, minTableLen) - for i := range buckets { - buckets[i].meta = defaultMeta - } counterLen := minTableLen >> 10 if counterLen < minMapCounterLen { counterLen = minMapCounterLen @@ -241,10 +278,16 @@ func newMapTable[K comparable, V any](minTableLen int, seed maphash.Seed) *mapTa counterLen = maxMapCounterLen } counter := make([]counterStripe, counterLen) + // Derive intSeed from maphash.Seed for fast integer hashing + var h maphash.Hash + h.SetSeed(seed) + h.WriteByte(0) + intSeed := h.Sum64() t := &mapTable[K, V]{ buckets: buckets, size: counter, seed: seed, + intSeed: intSeed, } return t } @@ -270,17 +313,33 @@ func ToPlainMap[K comparable, V any](m *Map[K, V]) map[K]V { func (m *Map[K, V]) Load(key K) (value V, ok bool) { m.initOnce.Do(m.init) table := m.table.Load() - hash := maphash.Comparable(table.seed, key) + var hash uint64 + if m.intKey { + hash = hashUint64(table.intSeed, toUint64(key)) + } else { + hash = maphash.Comparable(table.seed, key) + } h1 := h1(hash) h2w := broadcast(h2(hash)) bidx := uint64(len(table.buckets)-1) & h1 - b := &table.buckets[bidx] + // Same as: b := &table.buckets[bidx] + // Inline bounds check elimination via unsafe pointer arithmetic. + // Safety: bidx is always < len(table.buckets) since it's masked with (len-1). + b := (*bucketPadded)(unsafe.Add(unsafe.Pointer(&table.buckets[0]), + uintptr(bidx)*unsafe.Sizeof(bucketPadded{}))) for { metaw := atomic.LoadUint64(&b.meta) markedw := markZeroBytes(metaw^h2w) & metaMask for markedw != 0 { idx := firstMarkedByteIndex(markedw) - eptr := atomic.LoadPointer(&b.entries[idx]) + // Same as: eptr := atomic.LoadPointer(&b.entries[idx]) + // Inline bounds check elimination via unsafe pointer arithmetic. + // Safety: idx is always < entriesPerMapBucket (5) since it comes from + // firstMarkedByteIndex which returns index of a marked byte in the + // 5-byte metadata mask (metaMask). + eptr := atomic.LoadPointer((*unsafe.Pointer)(unsafe.Add( + unsafe.Pointer(&b.entries[0]), + uintptr(idx)*unsafe.Sizeof(b.entries[0])))) if eptr != nil { e := (*entry[K, V])(eptr) if e.key == key { @@ -299,14 +358,109 @@ func (m *Map[K, V]) Load(key K) (value V, ok bool) { // Store sets the value for a key. func (m *Map[K, V]) Store(key K, value V) { - m.doCompute( - key, - func(V, bool) (V, ComputeOp) { - return value, UpdateOp - }, - noLoadOp, - false, - ) + m.initOnce.Do(m.init) + // Store is a popular operation, hence instead of using doCompute, + // it uses a simplified and slightly faster version of it. + for { + store_attempt: + var ( + emptyb *bucketPadded + emptyidx int + ) + table := m.table.Load() + tableLen := len(table.buckets) + var hash uint64 + if m.intKey { + hash = hashUint64(table.intSeed, toUint64(key)) + } else { + hash = maphash.Comparable(table.seed, key) + } + h1 := h1(hash) + h2 := h2(hash) + h2w := broadcast(h2) + bidx := uint64(len(table.buckets)-1) & h1 + rootb := &table.buckets[bidx] + + rootb.mu.Lock() + // The following two checks must go in reverse to what's + // in the resize method. + if seq := resizeSeq(m.resizeCtl.Load()); seq&1 == 1 { + // Resize is in progress. Help with the transfer, then go for another attempt. + rootb.mu.Unlock() + m.helpResize(seq) + goto store_attempt + } + if m.newerTableExists(table) { + // Someone resized the table. Go for another attempt. + rootb.mu.Unlock() + goto store_attempt + } + b := rootb + for { + metaw := b.meta + markedw := markZeroBytes(metaw^h2w) & metaMask + for markedw != 0 { + idx := firstMarkedByteIndex(markedw) + eptr := b.entries[idx] + if eptr != nil { + e := (*entry[K, V])(eptr) + if e.key == key { + // In-place update. + newe := new(entry[K, V]) + newe.key = key + newe.value = value + atomic.StorePointer(&b.entries[idx], unsafe.Pointer(newe)) + rootb.mu.Unlock() + return + } + } + markedw &= markedw - 1 + } + if emptyb == nil { + // Search for empty entries (up to 5 per bucket). + emptyw := ^metaw & occupiedMetaMasked + if emptyw != 0 { + idx := firstMarkedByteIndex(emptyw) + emptyb = b + emptyidx = idx + } + } + if b.next == nil { + if emptyb != nil { + // Insertion into an existing bucket. + newe := new(entry[K, V]) + newe.key = key + newe.value = value + // First we update meta, then the entry. + atomic.StoreUint64(&emptyb.meta, setByte(emptyb.meta, h2, emptyidx)) + atomic.StorePointer(&emptyb.entries[emptyidx], unsafe.Pointer(newe)) + rootb.mu.Unlock() + table.addSize(bidx, 1) + return + } + growThreshold := float64(tableLen) * entriesPerMapBucket * mapLoadFactor + if table.sumSize() > int64(growThreshold) { + // Need to grow the table. Then go for another attempt. + rootb.mu.Unlock() + m.resize(table, mapGrowHint) + goto store_attempt + } + // Insertion into a new bucket. + // Create and append a bucket. + newb := new(bucketPadded) + newb.meta = setByte(0, h2, 0) + newe := new(entry[K, V]) + newe.key = key + newe.value = value + newb.entries[0] = unsafe.Pointer(newe) + atomic.StorePointer(&b.next, unsafe.Pointer(newb)) + rootb.mu.Unlock() + table.addSize(bidx, 1) + return + } + b = (*bucketPadded)(b.next) + } + } } // LoadOrStore returns the existing value for the key if present. @@ -436,7 +590,12 @@ func (m *Map[K, V]) doCompute( ) table := m.table.Load() tableLen := len(table.buckets) - hash := maphash.Comparable(table.seed, key) + var hash uint64 + if m.intKey { + hash = hashUint64(table.intSeed, toUint64(key)) + } else { + hash = maphash.Comparable(table.seed, key) + } h1 := h1(hash) h2 := h2(hash) h2w := broadcast(h2) @@ -509,13 +668,13 @@ func (m *Map[K, V]) doCompute( case DeleteOp: // Deletion. // First we update the hash, then the entry. - newmetaw := setByte(metaw, emptyMetaSlot, idx) + newmetaw := setByte(metaw, 0, idx) atomic.StoreUint64(&b.meta, newmetaw) atomic.StorePointer(&b.entries[idx], nil) rootb.mu.Unlock() table.addSize(bidx, -1) // Might need to shrink the table if we left bucket empty. - if newmetaw == defaultMeta { + if newmetaw == 0 { m.resize(table, mapShrinkHint) } return oldv, !computeOnly @@ -540,7 +699,7 @@ func (m *Map[K, V]) doCompute( } if emptyb == nil { // Search for empty entries (up to 5 per bucket). - emptyw := metaw & defaultMetaMasked + emptyw := ^metaw & occupiedMetaMasked if emptyw != 0 { idx := firstMarkedByteIndex(emptyw) emptyb = b @@ -581,11 +740,11 @@ func (m *Map[K, V]) doCompute( switch op { case DeleteOp, CancelOp: rootb.mu.Unlock() - return newValue, false + return zeroV, false default: // Create and append a bucket. newb := new(bucketPadded) - newb.meta = setByte(defaultMeta, h2, 0) + newb.meta = setByte(0, h2, 0) newe := new(entry[K, V]) newe.key = key newe.value = newValue @@ -655,10 +814,10 @@ func (m *Map[K, V]) resize(knownTable *mapTable[K, V], hint mapResizeHint) { shrinkThreshold := int64((tableLen * entriesPerMapBucket) / mapShrinkFraction) if tableLen > m.minTableLen && table.sumSize() <= shrinkThreshold { // Shrink the table with factor of 2. - // It's fine to generate a new seed since full locking - // is required anyway. + // Analogous to growth, we must preserve the seed to ensure stable + // hash mapping, enabling lock-free writes to destination buckets. m.totalShrinks.Add(1) - newTable = newMapTable[K, V](tableLen>>1, maphash.MakeSeed()) + newTable = newMapTable[K, V](tableLen>>1, table.seed) } else { // No need to shrink. Wake up all waiters and give up. m.resizeMu.Lock() @@ -740,6 +899,20 @@ func (m *Map[K, V]) helpResize(seq uint64) { func (m *Map[K, V]) transfer(table, newTable *mapTable[K, V]) { tableLen := len(table.buckets) newTableLen := len(newTable.buckets) + // Determines the concurrent task range for destination buckets. + // We iterate based on these properties to avoid locking destination + // buckets: + // - Grow (Pow2): baseLen == tableLen + // Entries from source bucket i move to dest buckets i and i+baseLen + // - Shrink (Pow2): baseLen == newTableLen + // Entries from source buckets i and i+baseLen move to dest bucket i + // By iterating 0..baseLen and processing all possible source buckets + // (srcIdx += baseLen) in the inner loop, a single goroutine exclusively + // owns the write operations for its assigned destination buckets. + baseLen := tableLen + if baseLen > newTableLen { + baseLen = newTableLen + } stride := (tableLen >> 3) / int(maxResizeHelpers) if stride < minResizeTransferStride { stride = minResizeTransferStride @@ -751,27 +924,20 @@ func (m *Map[K, V]) transfer(table, newTable *mapTable[K, V]) { if start < 0 { start = 0 } - if start > tableLen { + if start >= baseLen { break } end := int(nextIdx) - if end > tableLen { - end = tableLen + if end > baseLen { + end = baseLen } // Transfer buckets in this range. total := 0 - if newTableLen > tableLen { - // We're growing the table with 2x multiplier, so entries from a N bucket can - // only be transferred to N and 2*N buckets in the new table. Thus, destination - // buckets written by the resize helpers don't intersect, so we don't need to - // acquire locks in the destination buckets. - for i := start; i < end; i++ { - total += transferBucketUnsafe(&table.buckets[i], newTable) - } - } else { - // We're shrinking the table, so all locks must be acquired. - for i := start; i < end; i++ { - total += transferBucket(&table.buckets[i], newTable) + for i := start; i < end; i++ { + // Visit all source buckets that map to this destination bucket. + // When growing, runs once. When shrinking, runs twice. + for srcIdx := i; srcIdx < tableLen; srcIdx += baseLen { + total += transferBucketUnsafe(&table.buckets[srcIdx], newTable, m.intKey) } } // The exact counter stripe doesn't matter here, so pick up the one @@ -784,6 +950,7 @@ func (m *Map[K, V]) transfer(table, newTable *mapTable[K, V]) { func transferBucketUnsafe[K comparable, V any]( b *bucketPadded, destTable *mapTable[K, V], + intKey bool, ) (copied int) { rootb := b rootb.mu.Lock() @@ -791,7 +958,12 @@ func transferBucketUnsafe[K comparable, V any]( for i := 0; i < entriesPerMapBucket; i++ { if eptr := b.entries[i]; eptr != nil { e := (*entry[K, V])(eptr) - hash := maphash.Comparable(destTable.seed, e.key) + var hash uint64 + if intKey { + hash = hashUint64(destTable.intSeed, toUint64(e.key)) + } else { + hash = maphash.Comparable(destTable.seed, e.key) + } bidx := uint64(len(destTable.buckets)-1) & h1(hash) destb := &destTable.buckets[bidx] appendToBucket(h2(hash), e, destb) @@ -806,33 +978,6 @@ func transferBucketUnsafe[K comparable, V any]( } } -func transferBucket[K comparable, V any]( - b *bucketPadded, - destTable *mapTable[K, V], -) (copied int) { - rootb := b - rootb.mu.Lock() - for { - for i := 0; i < entriesPerMapBucket; i++ { - if eptr := b.entries[i]; eptr != nil { - e := (*entry[K, V])(eptr) - hash := maphash.Comparable(destTable.seed, e.key) - bidx := uint64(len(destTable.buckets)-1) & h1(hash) - destb := &destTable.buckets[bidx] - destb.mu.Lock() - appendToBucket(h2(hash), e, destb) - destb.mu.Unlock() - copied++ - } - } - if b.next == nil { - rootb.mu.Unlock() - return - } - b = (*bucketPadded)(b.next) - } -} - // Range calls f sequentially for each key and value present in the // map. If f returns false, range stops the iteration. // @@ -846,6 +991,9 @@ func transferBucket[K comparable, V any]( // creation, modification and deletion. However, the concurrent // modification rule apply, i.e. the changes may be not reflected // in the subsequently iterated entries. +// +// For a faster, lock-free alternative with relaxed consistency +// guarantees, see [RangeRelaxed]. func (m *Map[K, V]) Range(f func(key K, value V) bool) { m.initOnce.Do(m.init) // Pre-allocate array big enough to fit entries for most hash tables. @@ -882,6 +1030,167 @@ func (m *Map[K, V]) Range(f func(key K, value V) bool) { } } +// All is similar to [Range], but returns an [iter.Seq2], so is compatible with +// Go 1.23+ iterators. All of the same caveats and behaviour from [Range] apply +// to All. +// +// For a faster, lock-free alternative with relaxed consistency +// guarantees, see [AllRelaxed]. +func (m *Map[K, V]) All() func(func(key K, value V) bool) { + return m.Range +} + +// RangeRelaxed calls f sequentially for each key and value present +// in the map. If f returns false, range stops the iteration. +// +// RangeRelaxed is a faster, lock-free alternative to [Range]. Unlike +// Range, it does not acquire bucket locks and does not allocate memory +// for entry snapshots. Instead, it reads entries directly using atomic +// loads. +// +// RangeRelaxed does not necessarily correspond to any consistent +// snapshot of the Map's contents: if the value for any key is stored +// or deleted concurrently, RangeRelaxed may reflect any mapping for +// that key from any point during the RangeRelaxed call. Unlike [Range], +// the same key may be visited more than once if it is concurrently +// deleted and re-inserted during the iteration. +// +// It is safe to modify the map while iterating it, including entry +// creation, modification and deletion. However, the concurrent +// modification rule apply, i.e. the changes may be not reflected +// in the subsequently iterated entries. +// +// For stronger consistency guarantees where each key is visited at +// most once, see [Range]. +func (m *Map[K, V]) RangeRelaxed(f func(key K, value V) bool) { + m.initOnce.Do(m.init) + table := m.table.Load() + for i := range table.buckets { + b := &table.buckets[i] + for { + metaw := atomic.LoadUint64(&b.meta) + markedw := metaw & occupiedMeta + for markedw != 0 { + idx := firstMarkedByteIndex(markedw) + eptr := atomic.LoadPointer(&b.entries[idx]) + if eptr != nil { + e := (*entry[K, V])(eptr) + if !f(e.key, e.value) { + return + } + } + markedw &= markedw - 1 + } + bptr := atomic.LoadPointer(&b.next) + if bptr == nil { + break + } + b = (*bucketPadded)(bptr) + } + } +} + +// AllRelaxed is similar to [RangeRelaxed], but returns an [iter.Seq2], +// so is compatible with Go 1.23+ iterators. All of the same caveats +// and behaviour from [RangeRelaxed] apply to AllRelaxed. +// +// For stronger consistency guarantees where each key is visited at +// most once, see [All]. +func (m *Map[K, V]) AllRelaxed() func(func(key K, value V) bool) { + return m.RangeRelaxed +} + +// DeleteMatching deletes all entries for which the delete return +// value of f is true. If the stop return value is true, the +// iteration stops immediately. The function returns the number +// of deleted entries. +// +// DeleteMatching does not necessarily correspond to any consistent +// snapshot of the Map's contents: if the value for any key is stored +// or deleted concurrently (including by a concurrent DeleteMatching +// call), DeleteMatching may reflect any mapping for that key from +// any point during the call. In particular, if the map is resized +// during the call (for example, due to concurrent modifications), +// the iteration restarts internally with the new table, which may +// result in calling f with the same key more than once. +// +// This call locks a hash table bucket for the duration of +// evaluating f for all entries in the bucket and performing +// deletions. It means that modifications on other entries in +// the bucket will be blocked until f executes. Consider this when +// the function includes long-running operations. +func (m *Map[K, V]) DeleteMatching(f func(key K, value V) (delete, stop bool)) int { + m.initOnce.Do(m.init) + var totalDeleted int + var anyBucketEmptied bool +delete_loop_attempt: + table := m.table.Load() + for bidx := range table.buckets { + rootb := &table.buckets[bidx] + rootb.mu.Lock() + // The following two checks must go in reverse to what's + // in the resize method. + if seq := resizeSeq(m.resizeCtl.Load()); seq&1 == 1 { + // Resize is in progress. Help with the transfer, then go for another attempt. + rootb.mu.Unlock() + m.helpResize(seq) + goto delete_loop_attempt + } + if m.newerTableExists(table) { + // Someone resized the table. Go for another attempt. + rootb.mu.Unlock() + goto delete_loop_attempt + } + + var bucketDeleted int + b := rootb + for { + for i := 0; i < entriesPerMapBucket; i++ { + eptr := b.entries[i] + if eptr != nil { + e := (*entry[K, V])(eptr) + del, stop := f(e.key, e.value) + if del { + // Deletion. + // First we update the meta, then the entry. + newmetaw := setByte(b.meta, 0, i) + atomic.StoreUint64(&b.meta, newmetaw) + atomic.StorePointer(&b.entries[i], nil) + bucketDeleted++ + if newmetaw == 0 { + anyBucketEmptied = true + } + } + if stop { + rootb.mu.Unlock() + totalDeleted += bucketDeleted + if bucketDeleted > 0 { + table.addSize(uint64(bidx), -bucketDeleted) + } + if anyBucketEmptied { + m.resize(table, mapShrinkHint) + } + return totalDeleted + } + } + } + if b.next == nil { + break + } + b = (*bucketPadded)(b.next) + } + rootb.mu.Unlock() + if bucketDeleted > 0 { + totalDeleted += bucketDeleted + table.addSize(uint64(bidx), -bucketDeleted) + } + } + if anyBucketEmptied { + m.resize(table, mapShrinkHint) + } + return totalDeleted +} + // Clear deletes all keys and values currently stored in the map. func (m *Map[K, V]) Clear() { m.initOnce.Do(m.init) @@ -907,7 +1216,7 @@ func appendToBucket[K comparable, V any](h2 uint8, e *entry[K, V], b *bucketPadd } if b.next == nil { newb := new(bucketPadded) - newb.meta = setByte(defaultMeta, h2, 0) + newb.meta = setByte(0, h2, 0) newb.entries[0] = unsafe.Pointer(e) b.next = unsafe.Pointer(newb) return @@ -917,7 +1226,7 @@ func appendToBucket[K comparable, V any](h2 uint8, e *entry[K, V], b *bucketPadd } func (table *mapTable[K, V]) addSize(bucketIdx uint64, delta int) { - cidx := uint64(len(table.size)-1) & bucketIdx + cidx := bucketIdx & uint64(len(table.size)-1) atomic.AddInt64(&table.size[cidx].c, int64(delta)) } @@ -934,7 +1243,7 @@ func h1(h uint64) uint64 { } func h2(h uint64) uint8 { - return uint8(h & 0x7f) + return 0x80 | uint8(h&0x7f) } // MapStats is Map statistics. @@ -1052,20 +1361,12 @@ const ( cacheLineSize = 64 ) -// nextPowOf2 computes the next highest power of 2 of 32-bit v. -// Source: https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2 -func nextPowOf2(v uint32) uint32 { - if v == 0 { +// nextPowOf2 computes the next highest power of 2 of 64-bit v. +func nextPowOf2(v uint64) uint64 { + if v <= 1 { return 1 } - v-- - v |= v >> 1 - v |= v >> 2 - v |= v >> 4 - v |= v >> 8 - v |= v >> 16 - v++ - return v + return 1 << bits.Len64(v-1) } func parallelism() uint32 { diff --git a/common/xsync/map_test.go b/common/xsync/map_test.go index 72ebfaea9..b5184e194 100644 --- a/common/xsync/map_test.go +++ b/common/xsync/map_test.go @@ -26,6 +26,11 @@ type point struct { y int32 } +type integerKey interface { + int | int8 | int16 | int32 | int64 | + uint | uint8 | uint16 | uint32 | uint64 | uintptr +} + var benchmarkCases = []struct { name string readPercentage int @@ -90,6 +95,72 @@ func TestMap_EmptyStringKey(t *testing.T) { } } +// TestMapHashUint64_NoDifferentialBias verifies that hashUint64 does +// not exhibit seed-independent differential bias for XOR deltas +// (see https://github.com/puzpuzpuz/xsync/issues/192). +func TestMapHashUint64_NoDifferentialBias(t *testing.T) { + const ( + nBuckets = 256 + mask = nBuckets - 1 + nTrials = 100_000 + threshold = 3.0 + ) + expected := float64(nTrials) / float64(nBuckets) + + // Deltas from the issue report. + issueDeltas := []uint64{ + 0x0000015000000000, + 0x0000004F00000000, + 0x000000A300000000, + 0x00000D0000000000, + } + // Structured deltas across various shift amounts. + var shiftedDeltas []uint64 + for _, shift := range []uint{0, 8, 16, 24, 32, 40, 48} { + for k := uint64(1); k <= 64; k++ { + shiftedDeltas = append(shiftedDeltas, k< threshold { + t.Errorf("seed=0x%x delta=0x%x: got %.2fx expected collision rate (threshold=%.1fx)", + seed, delta, ratio, threshold) + } + } + } +} + func TestMapStore_NilValue(t *testing.T) { m := NewMap[string, *struct{}]() m.Store("foo", nil) @@ -181,6 +252,79 @@ func TestMapLoadAndStore_NonNilValue(t *testing.T) { } } +func TestMapAll(t *testing.T) { + m := NewMap[string, int]() + m.All()(func(key string, value int) bool { + t.Fatal("got an iteration on empty map") + return true + }) + + for i := 0; i < 1000; i++ { + m.Store(strconv.Itoa(i), i) + } + + iters := 0 + met := make(map[string]int) + m.All()(func(key string, value int) bool { + if key != strconv.Itoa(value) { + t.Fatalf("got unexpected key/value for iteration %d: %v/%v", iters, key, value) + return false + } + met[key] += 1 + iters++ + return true + }) + + if iters != 1000 { + t.Fatalf("got unexpected number of iterations: %d", iters) + } + for i := 0; i < 1000; i++ { + if c := met[strconv.Itoa(i)]; c != 1 { + t.Fatalf("range did not iterate correctly over %d: %d", i, c) + } + } +} + +func TestMapAll_Break(t *testing.T) { + m := NewMap[string, int]() + for i := 0; i < 100; i++ { + m.Store(strconv.Itoa(i), i) + } + + iters := 0 + m.All()(func(key string, value int) bool { + iters++ + + if iters == 50 { + return false + } + return true + }) + + if iters != 50 { + t.Fatalf("got unexpected number of iterations: %d", iters) + } +} + +func TestMapAll_NestedDelete(t *testing.T) { + const numEntries = 256 + m := NewMap[string, int]() + for i := 0; i < numEntries; i++ { + m.Store(strconv.Itoa(i), i) + } + + m.All()(func(key string, value int) bool { + m.Delete(key) + return true + }) + + for i := 0; i < numEntries; i++ { + if _, ok := m.Load(strconv.Itoa(i)); ok { + t.Fatalf("value found for %d", i) + } + } +} + func TestMapRange(t *testing.T) { const numEntries = 1000 m := NewMap[string, int]() @@ -215,6 +359,9 @@ func TestMapRange_FalseReturned(t *testing.T) { } iters := 0 m.Range(func(key string, value int) bool { + if key != strconv.Itoa(value) { + t.Fatalf("got unexpected key/value for iteration %d: %v/%v", iters, key, value) + } iters++ return iters != 13 }) @@ -229,7 +376,77 @@ func TestMapRange_NestedDelete(t *testing.T) { for i := 0; i < numEntries; i++ { m.Store(strconv.Itoa(i), i) } + iters := 0 m.Range(func(key string, value int) bool { + if key != strconv.Itoa(value) { + t.Fatalf("got unexpected key/value for iteration %d: %v/%v", iters, key, value) + } + m.Delete(key) + iters++ + return true + }) + for i := 0; i < numEntries; i++ { + if _, ok := m.Load(strconv.Itoa(i)); ok { + t.Fatalf("value found for %d", i) + } + } +} + +func TestMapRangeRelaxed(t *testing.T) { + const numEntries = 1000 + m := NewMap[string, int]() + for i := 0; i < numEntries; i++ { + m.Store(strconv.Itoa(i), i) + } + iters := 0 + met := make(map[string]int) + m.RangeRelaxed(func(key string, value int) bool { + if key != strconv.Itoa(value) { + t.Fatalf("got unexpected key/value for iteration %d: %v/%v", iters, key, value) + return false + } + met[key] += 1 + iters++ + return true + }) + if iters != numEntries { + t.Fatalf("got unexpected number of iterations: %d", iters) + } + for i := 0; i < numEntries; i++ { + if c := met[strconv.Itoa(i)]; c != 1 { + t.Fatalf("range did not iterate correctly over %d: %d", i, c) + } + } +} + +func TestMapRangeRelaxed_FalseReturned(t *testing.T) { + m := NewMap[string, int]() + for i := 0; i < 100; i++ { + m.Store(strconv.Itoa(i), i) + } + iters := 0 + m.RangeRelaxed(func(key string, value int) bool { + if key != strconv.Itoa(value) { + t.Fatalf("got unexpected key/value for iteration %d: %v/%v", iters, key, value) + } + iters++ + return iters != 13 + }) + if iters != 13 { + t.Fatalf("got unexpected number of iterations: %d", iters) + } +} + +func TestMapRangeRelaxed_NestedDelete(t *testing.T) { + const numEntries = 256 + m := NewMap[string, int]() + for i := 0; i < numEntries; i++ { + m.Store(strconv.Itoa(i), i) + } + m.RangeRelaxed(func(key string, value int) bool { + if key != strconv.Itoa(value) { + t.Fatalf("got unexpected key/value: %v/%v", key, value) + } m.Delete(key) return true }) @@ -240,75 +457,403 @@ func TestMapRange_NestedDelete(t *testing.T) { } } -func TestMapStringStore(t *testing.T) { - const numEntries = 128 +func TestMapAllRelaxed(t *testing.T) { + const numEntries = 1000 m := NewMap[string, int]() for i := 0; i < numEntries; i++ { m.Store(strconv.Itoa(i), i) } - for i := 0; i < numEntries; i++ { - v, ok := m.Load(strconv.Itoa(i)) - if !ok { - t.Fatalf("value not found for %d", i) + iters := 0 + met := make(map[string]int) + m.AllRelaxed()(func(key string, value int) bool { + if key != strconv.Itoa(value) { + t.Fatalf("got unexpected key/value for iteration %d: %v/%v", iters, key, value) } - if v != i { - t.Fatalf("values do not match for %d: %v", i, v) + met[key] += 1 + iters++ + return true + }) + if iters != numEntries { + t.Fatalf("got unexpected number of iterations: %d", iters) + } + for i := 0; i < numEntries; i++ { + if c := met[strconv.Itoa(i)]; c != 1 { + t.Fatalf("all did not iterate correctly over %d: %d", i, c) } } } -func TestMapIntStore(t *testing.T) { - const numEntries = 128 +func TestMapDeleteMatching(t *testing.T) { + const numEntries = 1000 + m := NewMap[string, int]() + for i := 0; i < numEntries; i++ { + m.Store(strconv.Itoa(i), i) + } + // Delete even values. + deleted := m.DeleteMatching(func(key string, value int) (del, stop bool) { + return value%2 == 0, false + }) + if deleted != numEntries/2 { + t.Fatalf("expected %d deleted, got %d", numEntries/2, deleted) + } + if m.Size() != numEntries/2 { + t.Fatalf("expected size %d, got %d", numEntries/2, m.Size()) + } + // Verify only odd values remain. + for i := 0; i < numEntries; i++ { + _, ok := m.Load(strconv.Itoa(i)) + if i%2 == 0 && ok { + t.Fatalf("even value %d should have been deleted", i) + } + if i%2 != 0 && !ok { + t.Fatalf("odd value %d should not have been deleted", i) + } + } +} + +func TestMapDeleteMatching_Cancel(t *testing.T) { + const numEntries = 100 + m := NewMap[string, int]() + for i := 0; i < numEntries; i++ { + m.Store(strconv.Itoa(i), i) + } + // Delete entries and cancel after 10 deletions. + callCount := 0 + deleted := m.DeleteMatching(func(key string, value int) (del, stop bool) { + callCount++ + if callCount == 10 { + return true, true // delete this one and cancel + } + return true, false + }) + if deleted != 10 { + t.Fatalf("expected 10 deleted, got %d", deleted) + } + if callCount != 10 { + t.Fatalf("expected f to be called 10 times, got %d", callCount) + } + if m.Size() != numEntries-10 { + t.Fatalf("expected size %d, got %d", numEntries-10, m.Size()) + } +} + +func TestMapDeleteMatching_EmptyMap(t *testing.T) { + m := NewMap[string, int]() + callCount := 0 + deleted := m.DeleteMatching(func(key string, value int) (del, stop bool) { + callCount++ + return false, false + }) + if deleted != 0 { + t.Fatalf("expected 0 deleted on empty map, got %d", deleted) + } + if callCount != 0 { + t.Fatalf("expected f to be called 0 times, got %d", callCount) + } +} + +func TestMapDeleteMatching_NoDeletions(t *testing.T) { + const numEntries = 100 + m := NewMap[string, int]() + for i := 0; i < numEntries; i++ { + m.Store(strconv.Itoa(i), i) + } + callCount := 0 + deleted := m.DeleteMatching(func(key string, value int) (del, stop bool) { + callCount++ + return false, false // never delete + }) + if deleted != 0 { + t.Fatalf("expected 0 deleted, got %d", deleted) + } + if callCount != numEntries { + t.Fatalf("expected f to be called %d times, got %d", numEntries, callCount) + } + if m.Size() != numEntries { + t.Fatalf("expected size %d, got %d", numEntries, m.Size()) + } +} + +func TestMapDeleteMatching_AllDeleted(t *testing.T) { + const numEntries = 256 + m := NewMap[string, int]() + for i := 0; i < numEntries; i++ { + m.Store(strconv.Itoa(i), i) + } + deleted := m.DeleteMatching(func(key string, value int) (del, stop bool) { + return true, false // delete all + }) + if deleted != numEntries { + t.Fatalf("expected %d deleted, got %d", numEntries, deleted) + } + if m.Size() != 0 { + t.Fatalf("expected size 0, got %d", m.Size()) + } +} + +func testParallelRangeRelaxed(t *testing.T, numGoroutines int) { + const numEntries = 10000 + const numIterations = 50 + m := NewMap[int, int]() for i := 0; i < numEntries; i++ { m.Store(i, i) } + + var wg sync.WaitGroup + var totalIterations atomic.Int64 + + // Launch goroutines that iterate using RangeRelaxed. + for i := 0; i < numGoroutines/2; i++ { + wg.Add(1) + go func() { + defer wg.Done() + for i := 0; i < numIterations; i++ { + m.RangeRelaxed(func(key int, value int) bool { + if key != value { + t.Errorf("key %d != value %d", key, value) + } + totalIterations.Add(1) + return true + }) + } + }() + } + + // Launch goroutines that modify the map. + for i := 0; i < numGoroutines/2; i++ { + wg.Add(1) + go func() { + defer wg.Done() + for i := 0; i < numIterations; i++ { + for i := 0; i < numEntries; i++ { + m.Store(i, i) + if i%10 == 0 { + m.Delete(i) + m.Store(i, i) + } + } + } + }() + } + + wg.Wait() + + if totalIterations.Load() == 0 { + t.Error("expected some iterations to occur") + } +} + +func TestMapParallelRangeRelaxed(t *testing.T) { + testParallelRangeRelaxed(t, 2) + testParallelRangeRelaxed(t, runtime.GOMAXPROCS(0)) + testParallelRangeRelaxed(t, 100) +} + +func testParallelDeleteMatching(t *testing.T, numGoroutines int) { + const numEntries = 10000 + const numIterations = 50 + + m := NewMap[int, int]() for i := 0; i < numEntries; i++ { - v, ok := m.Load(i) + m.Store(i, i) + } + + var wg sync.WaitGroup + var totalDeleted atomic.Int64 + + // Launch goroutines that delete even numbers. + for i := 0; i < numGoroutines/2; i++ { + wg.Add(1) + go func() { + defer wg.Done() + for i := 0; i < numIterations; i++ { + deleted := m.DeleteMatching(func(key int, value int) (del, stop bool) { + return key%2 == 0, false + }) + totalDeleted.Add(int64(deleted)) + } + }() + } + + // Launch goroutines that re-add entries. + for i := 0; i < numGoroutines/2; i++ { + wg.Add(1) + go func() { + defer wg.Done() + for i := 0; i < numIterations; i++ { + for i := 0; i < numEntries; i++ { + m.Store(i, i) + } + } + }() + } + + wg.Wait() + + // Verify map is in consistent state. + size := m.Size() + rangeCount := 0 + m.Range(func(key int, value int) bool { + if key != value { + t.Errorf("key %d != value %d", key, value) + } + rangeCount++ + return true + }) + if size != rangeCount { + t.Errorf("size %d != range count %d", size, rangeCount) + } + if totalDeleted.Load() == 0 { + t.Error("expected some deletions to occur") + } +} + +func TestMapParallelDeleteMatching(t *testing.T) { + testParallelDeleteMatching(t, 2) + testParallelDeleteMatching(t, runtime.GOMAXPROCS(0)) + testParallelDeleteMatching(t, 100) +} + +func TestMapDeleteMatching_ConcurrentResize(t *testing.T) { + // This test attempts to cover the resize paths in DeleteMatching: + // 1. Resize in progress during DeleteMatching iteration + // 2. Table changed (resize completed) during DeleteMatching iteration + const numIterations = 1000 + const numEntries = 100 + + for iter := 0; iter < numIterations; iter++ { + // Start with minimal size to maximize resize frequency + m := NewMap[int, int]() + // Pre-fill just enough to have entries + for i := 0; i < numEntries; i++ { + m.Store(i, i) + } + + var wg sync.WaitGroup + start := make(chan struct{}) + + // Goroutines that trigger resize by adding many new entries + for i := 0; i < 8; i++ { + wg.Add(1) + go func() { + defer wg.Done() + <-start + for i := numEntries; i < numEntries*10; i++ { + m.Store(i, i) + } + }() + } + + // Goroutines that call DeleteMatching repeatedly during resize + for i := 0; i < 8; i++ { + wg.Add(1) + go func() { + defer wg.Done() + <-start + for i := 0; i < 10; i++ { + m.DeleteMatching(func(key int, value int) (del, stop bool) { + return key%5 == 0, false + }) + } + }() + } + + // Start all goroutines simultaneously + close(start) + wg.Wait() + + // Verify map consistency + size := m.Size() + rangeCount := 0 + m.Range(func(key int, value int) bool { + rangeCount++ + return true + }) + if size != rangeCount { + t.Errorf("iteration %d: size %d != range count %d", iter, size, rangeCount) + } + } +} + +func testMapStoreKeys[K integerKey](t *testing.T, numEntries int) { + t.Helper() + m := NewMap[K, K]() + for i := 0; i < numEntries; i++ { + m.Store(K(i), K(i)) + } + for i := 0; i < numEntries; i++ { + v, ok := m.Load(K(i)) if !ok { t.Fatalf("value not found for %d", i) } - if v != i { + if v != K(i) { t.Fatalf("values do not match for %d: %v", i, v) } } } -func TestMapStore_StructKeys_IntValues(t *testing.T) { - const numEntries = 128 - m := NewMap[point, int]() - for i := 0; i < numEntries; i++ { - m.Store(point{int32(i), -int32(i)}, i) - } - for i := 0; i < numEntries; i++ { - v, ok := m.Load(point{int32(i), -int32(i)}) - if !ok { - t.Fatalf("value not found for %d", i) +func TestMapStore_TypedKeys(t *testing.T) { + const n = 128 + t.Run("int", func(t *testing.T) { testMapStoreKeys[int](t, n) }) + t.Run("uint", func(t *testing.T) { testMapStoreKeys[uint](t, n) }) + t.Run("int8", func(t *testing.T) { testMapStoreKeys[int8](t, n) }) + t.Run("uint8", func(t *testing.T) { testMapStoreKeys[uint8](t, n) }) + t.Run("int16", func(t *testing.T) { testMapStoreKeys[int16](t, n) }) + t.Run("uint16", func(t *testing.T) { testMapStoreKeys[uint16](t, n) }) + t.Run("int32", func(t *testing.T) { testMapStoreKeys[int32](t, n) }) + t.Run("uint32", func(t *testing.T) { testMapStoreKeys[uint32](t, n) }) + t.Run("int64", func(t *testing.T) { testMapStoreKeys[int64](t, n) }) + t.Run("uint64", func(t *testing.T) { testMapStoreKeys[uint64](t, n) }) + t.Run("uintptr", func(t *testing.T) { testMapStoreKeys[uintptr](t, n) }) + t.Run("string", func(t *testing.T) { + m := NewMap[string, int]() + for i := 0; i < n; i++ { + m.Store(strconv.Itoa(i), i) } - if v != i { - t.Fatalf("values do not match for %d: %v", i, v) + for i := 0; i < n; i++ { + v, ok := m.Load(strconv.Itoa(i)) + if !ok { + t.Fatalf("value not found for %d", i) + } + if v != i { + t.Fatalf("values do not match for %d: %v", i, v) + } } - } -} - -func TestMapStore_StructKeys_StructValues(t *testing.T) { - const numEntries = 128 - m := NewMap[point, point]() - for i := 0; i < numEntries; i++ { - m.Store(point{int32(i), -int32(i)}, point{-int32(i), int32(i)}) - } - for i := 0; i < numEntries; i++ { - v, ok := m.Load(point{int32(i), -int32(i)}) - if !ok { - t.Fatalf("value not found for %d", i) + }) + t.Run("struct_intValues", func(t *testing.T) { + m := NewMap[point, int]() + for i := 0; i < n; i++ { + m.Store(point{int32(i), -int32(i)}, i) } - if v.x != -int32(i) { - t.Fatalf("x value does not match for %d: %v", i, v) + for i := 0; i < n; i++ { + v, ok := m.Load(point{int32(i), -int32(i)}) + if !ok { + t.Fatalf("value not found for %d", i) + } + if v != i { + t.Fatalf("values do not match for %d: %v", i, v) + } } - if v.y != int32(i) { - t.Fatalf("y value does not match for %d: %v", i, v) + }) + t.Run("struct_structValues", func(t *testing.T) { + m := NewMap[point, point]() + for i := 0; i < n; i++ { + m.Store(point{int32(i), -int32(i)}, point{-int32(i), int32(i)}) } - } + for i := 0; i < n; i++ { + v, ok := m.Load(point{int32(i), -int32(i)}) + if !ok { + t.Fatalf("value not found for %d", i) + } + if v.x != -int32(i) { + t.Fatalf("x value does not match for %d: %v", i, v) + } + if v.y != int32(i) { + t.Fatalf("y value does not match for %d: %v", i, v) + } + } + }) } func TestMapLoadOrStore(t *testing.T) { @@ -382,6 +927,52 @@ func TestMapLoadOrCompute_FunctionCalledOnce(t *testing.T) { }) } +func TestMapLoadOrCompute_ExistingKey(t *testing.T) { + m := NewMap[string, int]() + m.Store("key", 42) + v, loaded := m.LoadOrCompute("key", func() (int, bool) { + t.Fatal("value func should not be called for existing key") + return 100, false + }) + if !loaded { + t.Fatal("expected loaded to be true") + } + if v != 42 { + t.Fatalf("expected value 42, got %d", v) + } +} + +func TestMapLoadOrCompute_ConcurrentExistingKey(t *testing.T) { + // This test attempts to cover the race condition where: + // 1. LoadOrCompute's fast path doesn't find the key + // 2. Another goroutine inserts the key + // 3. LoadOrCompute acquires the lock and finds the key + const numIters = 10000 + for i := 0; i < numIters; i++ { + m := NewMap[int, int]() + var wg sync.WaitGroup + wg.Add(2) + go func() { + defer wg.Done() + m.Store(1, 42) + }() + go func() { + defer wg.Done() + m.LoadOrCompute(1, func() (int, bool) { + return 100, false + }) + }() + wg.Wait() + v, ok := m.Load(1) + if !ok { + t.Fatal("key should exist") + } + if v != 42 && v != 100 { + t.Fatalf("unexpected value: %d", v) + } + } +} + func TestMapOfCompute(t *testing.T) { m := NewMap[string, int]() // Store a new value. @@ -487,94 +1078,159 @@ func TestMapOfCompute(t *testing.T) { } } -func TestMapStringStoreThenDelete(t *testing.T) { - const numEntries = 1000 - m := NewMap[string, int]() +func TestMapCompute_CancelOpOnOverflowBucket(t *testing.T) { + // This test covers the CancelOp path when inserting into a new overflow bucket. + // We need to fill buckets completely so that a new key requires creating + // an overflow bucket, then return CancelOp to abort the insertion. + const numAttempts = 1000 + const sentinel = 999 + + for attempt := 0; attempt < numAttempts; attempt++ { + m := NewMap[int, int]() + // Fill the map to create conditions where some bucket chains are full. + // Insert entries - some will hash to the same bucket creating overflow. + numEntries := 100 + (attempt % 100) // Vary the fill level + for i := 0; i < numEntries; i++ { + m.Store(i, i) + } + + // Try Compute with CancelOp for new keys. + baseKey := 10000 + attempt*1000 + for i := 0; i < 50; i++ { + key := baseKey + i + v, ok := m.Compute(key, func(oldValue int, loaded bool) (newValue int, op ComputeOp) { + if loaded { + t.Fatal("key should not exist") + } + return sentinel, CancelOp + }) + if ok { + t.Fatalf("ok should be false when CancelOp is returned for new key") + } + // Both code paths should return zero value for CancelOp + if v != 0 { + t.Fatalf("expected zero value for CancelOp, got: %d", v) + } + // Verify the key was not inserted + if _, exists := m.Load(key); exists { + t.Fatalf("key %d should not exist after CancelOp", key) + } + } + } +} + +func testMapStoreThenDeleteKeys[K integerKey](t *testing.T, numEntries int) { + t.Helper() + m := NewMap[K, K]() for i := 0; i < numEntries; i++ { - m.Store(strconv.Itoa(i), i) + m.Store(K(i), K(i)) } for i := 0; i < numEntries; i++ { - m.Delete(strconv.Itoa(i)) - if _, ok := m.Load(strconv.Itoa(i)); ok { + m.Delete(K(i)) + if _, ok := m.Load(K(i)); ok { t.Fatalf("value was not expected for %d", i) } } } -func TestMapIntStoreThenDelete(t *testing.T) { - const numEntries = 1000 - m := NewMap[int32, int32]() - for i := 0; i < numEntries; i++ { - m.Store(int32(i), int32(i)) - } - for i := 0; i < numEntries; i++ { - m.Delete(int32(i)) - if _, ok := m.Load(int32(i)); ok { - t.Fatalf("value was not expected for %d", i) +func TestMapStoreThenDelete_TypedKeys(t *testing.T) { + const n = 1000 + const nByte = 200 + t.Run("int", func(t *testing.T) { testMapStoreThenDeleteKeys[int](t, n) }) + t.Run("uint", func(t *testing.T) { testMapStoreThenDeleteKeys[uint](t, n) }) + t.Run("int8", func(t *testing.T) { testMapStoreThenDeleteKeys[int8](t, nByte) }) + t.Run("uint8", func(t *testing.T) { testMapStoreThenDeleteKeys[uint8](t, nByte) }) + t.Run("int16", func(t *testing.T) { testMapStoreThenDeleteKeys[int16](t, n) }) + t.Run("uint16", func(t *testing.T) { testMapStoreThenDeleteKeys[uint16](t, n) }) + t.Run("int32", func(t *testing.T) { testMapStoreThenDeleteKeys[int32](t, n) }) + t.Run("uint32", func(t *testing.T) { testMapStoreThenDeleteKeys[uint32](t, n) }) + t.Run("int64", func(t *testing.T) { testMapStoreThenDeleteKeys[int64](t, n) }) + t.Run("uint64", func(t *testing.T) { testMapStoreThenDeleteKeys[uint64](t, n) }) + t.Run("uintptr", func(t *testing.T) { testMapStoreThenDeleteKeys[uintptr](t, n) }) + t.Run("string", func(t *testing.T) { + m := NewMap[string, int]() + for i := 0; i < n; i++ { + m.Store(strconv.Itoa(i), i) } - } + for i := 0; i < n; i++ { + m.Delete(strconv.Itoa(i)) + if _, ok := m.Load(strconv.Itoa(i)); ok { + t.Fatalf("value was not expected for %d", i) + } + } + }) + t.Run("struct", func(t *testing.T) { + m := NewMap[point, string]() + for i := 0; i < n; i++ { + m.Store(point{int32(i), 42}, strconv.Itoa(i)) + } + for i := 0; i < n; i++ { + m.Delete(point{int32(i), 42}) + if _, ok := m.Load(point{int32(i), 42}); ok { + t.Fatalf("value was not expected for %d", i) + } + } + }) } -func TestMapStructStoreThenDelete(t *testing.T) { - const numEntries = 1000 - m := NewMap[point, string]() +func testMapStoreThenLoadAndDeleteKeys[K integerKey](t *testing.T, numEntries int) { + t.Helper() + m := NewMap[K, K]() for i := 0; i < numEntries; i++ { - m.Store(point{int32(i), 42}, strconv.Itoa(i)) + m.Store(K(i), K(i)) } for i := 0; i < numEntries; i++ { - m.Delete(point{int32(i), 42}) - if _, ok := m.Load(point{int32(i), 42}); ok { - t.Fatalf("value was not expected for %d", i) - } - } -} - -func TestMapStringStoreThenLoadAndDelete(t *testing.T) { - const numEntries = 1000 - m := NewMap[string, int]() - for i := 0; i < numEntries; i++ { - m.Store(strconv.Itoa(i), i) - } - for i := 0; i < numEntries; i++ { - if v, loaded := m.LoadAndDelete(strconv.Itoa(i)); !loaded || v != i { - t.Fatalf("value was not found or different for %d: %v", i, v) - } - if _, ok := m.Load(strconv.Itoa(i)); ok { - t.Fatalf("value was not expected for %d", i) - } - } -} - -func TestMapIntStoreThenLoadAndDelete(t *testing.T) { - const numEntries = 1000 - m := NewMap[int, int]() - for i := 0; i < numEntries; i++ { - m.Store(i, i) - } - for i := 0; i < numEntries; i++ { - if _, loaded := m.LoadAndDelete(i); !loaded { + if _, loaded := m.LoadAndDelete(K(i)); !loaded { t.Fatalf("value was not found for %d", i) } - if _, ok := m.Load(i); ok { + if _, ok := m.Load(K(i)); ok { t.Fatalf("value was not expected for %d", i) } } } -func TestMapStructStoreThenLoadAndDelete(t *testing.T) { - const numEntries = 1000 - m := NewMap[point, int]() - for i := 0; i < numEntries; i++ { - m.Store(point{42, int32(i)}, i) - } - for i := 0; i < numEntries; i++ { - if _, loaded := m.LoadAndDelete(point{42, int32(i)}); !loaded { - t.Fatalf("value was not found for %d", i) +func TestMapStoreThenLoadAndDelete_TypedKeys(t *testing.T) { + const n = 1000 + const nByte = 200 + t.Run("int", func(t *testing.T) { testMapStoreThenLoadAndDeleteKeys[int](t, n) }) + t.Run("uint", func(t *testing.T) { testMapStoreThenLoadAndDeleteKeys[uint](t, n) }) + t.Run("int8", func(t *testing.T) { testMapStoreThenLoadAndDeleteKeys[int8](t, nByte) }) + t.Run("uint8", func(t *testing.T) { testMapStoreThenLoadAndDeleteKeys[uint8](t, nByte) }) + t.Run("int16", func(t *testing.T) { testMapStoreThenLoadAndDeleteKeys[int16](t, n) }) + t.Run("uint16", func(t *testing.T) { testMapStoreThenLoadAndDeleteKeys[uint16](t, n) }) + t.Run("int32", func(t *testing.T) { testMapStoreThenLoadAndDeleteKeys[int32](t, n) }) + t.Run("uint32", func(t *testing.T) { testMapStoreThenLoadAndDeleteKeys[uint32](t, n) }) + t.Run("int64", func(t *testing.T) { testMapStoreThenLoadAndDeleteKeys[int64](t, n) }) + t.Run("uint64", func(t *testing.T) { testMapStoreThenLoadAndDeleteKeys[uint64](t, n) }) + t.Run("uintptr", func(t *testing.T) { testMapStoreThenLoadAndDeleteKeys[uintptr](t, n) }) + t.Run("string", func(t *testing.T) { + m := NewMap[string, int]() + for i := 0; i < n; i++ { + m.Store(strconv.Itoa(i), i) } - if _, ok := m.Load(point{42, int32(i)}); ok { - t.Fatalf("value was not expected for %d", i) + for i := 0; i < n; i++ { + if v, loaded := m.LoadAndDelete(strconv.Itoa(i)); !loaded || v != i { + t.Fatalf("value was not found or different for %d: %v", i, v) + } + if _, ok := m.Load(strconv.Itoa(i)); ok { + t.Fatalf("value was not expected for %d", i) + } } - } + }) + t.Run("struct", func(t *testing.T) { + m := NewMap[point, int]() + for i := 0; i < n; i++ { + m.Store(point{42, int32(i)}, i) + } + for i := 0; i < n; i++ { + if _, loaded := m.LoadAndDelete(point{42, int32(i)}); !loaded { + t.Fatalf("value was not found for %d", i) + } + if _, ok := m.Load(point{42, int32(i)}); ok { + t.Fatalf("value was not expected for %d", i) + } + } + }) } func TestMapStoreThenParallelDelete_DoesNotShrinkBelowMinTableLen(t *testing.T) { @@ -680,9 +1336,10 @@ func assertMapCapacity[K comparable, V any](t *testing.T, m *Map[K, V], expected } func TestNewMapWithPresize(t *testing.T) { - assertMapCapacity(t, NewMap[string, string](), defaultMinMapTableLen*entriesPerMapBucket) - assertMapCapacity(t, NewMap[string, string](WithPresize(0)), defaultMinMapTableLen*entriesPerMapBucket) - assertMapCapacity(t, NewMap[string, string](WithPresize(-100)), defaultMinMapTableLen*entriesPerMapBucket) + const defaultMinMapTableCap = defaultMinMapTableLen * entriesPerMapBucket + assertMapCapacity(t, NewMap[string, string](), defaultMinMapTableCap) + assertMapCapacity(t, NewMap[string, string](WithPresize(0)), defaultMinMapTableCap) + assertMapCapacity(t, NewMap[string, string](WithPresize(-100)), defaultMinMapTableCap) assertMapCapacity(t, NewMap[string, string](WithPresize(500)), 1280) assertMapCapacity(t, NewMap[int, int](WithPresize(1_000_000)), 2621440) assertMapCapacity(t, NewMap[point, point](WithPresize(100)), 160) @@ -1295,7 +1952,7 @@ func parallelMapShrinker(t *testing.T, m *Map[uint64, *point], numIters, numEntr func parallelMapUpdater(t *testing.T, m *Map[uint64, *point], idx int, stopFlag *int64, cdone chan bool) { for atomic.LoadInt64(stopFlag) != 1 { - sleepUs := int(randv2.Uint64() % 10) + sleepUs := randv2.Uint64() % 10 if p, loaded := m.LoadOrStore(uint64(idx), &point{int32(idx), int32(idx)}); loaded { t.Errorf("value was present for %d: %v", idx, p) } @@ -1597,6 +2254,24 @@ func BenchmarkMapRange(b *testing.B) { }) } +func BenchmarkMapRangeRelaxed(b *testing.B) { + m := NewMap[string, int](WithPresize(benchmarkNumEntries)) + for i := 0; i < benchmarkNumEntries; i++ { + m.Store(benchmarkKeys[i], i) + } + b.ResetTimer() + runParallel(b, func(pb *testing.PB) { + foo := 0 + for pb.Next() { + m.RangeRelaxed(func(key string, value int) bool { + foo++ + return true + }) + _ = foo + } + }) +} + // Benchmarks noop performance of Compute func BenchmarkMapCompute(b *testing.B) { tests := []struct { @@ -1638,6 +2313,7 @@ func BenchmarkMapParallelRehashing(b *testing.B) { } for _, test := range tests { b.Run(test.name, func(b *testing.B) { + b.ResetTimer() for i := 0; i < b.N; i++ { m := NewMap[int, int]() @@ -1677,245 +2353,70 @@ func BenchmarkMapParallelRehashing(b *testing.B) { } } -func TestNextPowOf2(t *testing.T) { - if nextPowOf2(0) != 1 { - t.Error("nextPowOf2 failed") - } - if nextPowOf2(1) != 1 { - t.Error("nextPowOf2 failed") - } - if nextPowOf2(2) != 2 { - t.Error("nextPowOf2 failed") - } - if nextPowOf2(3) != 4 { - t.Error("nextPowOf2 failed") - } -} - -func TestBroadcast(t *testing.T) { - testCases := []struct { - input uint8 - expected uint64 +func BenchmarkMapDeleteMatching(b *testing.B) { + tests := []struct { + name string + numEntries int + deletePercent int }{ - { - input: 0, - expected: 0, - }, - { - input: 1, - expected: 0x0101010101010101, - }, - { - input: 2, - expected: 0x0202020202020202, - }, - { - input: 42, - expected: 0x2a2a2a2a2a2a2a2a, - }, - { - input: 127, - expected: 0x7f7f7f7f7f7f7f7f, - }, - { - input: 255, - expected: 0xffffffffffffffff, - }, + {"entries=1000_delete=10%", 1000, 10}, + {"entries=1000_delete=50%", 1000, 50}, + {"entries=1000_delete=100%", 1000, 100}, + {"entries=100000_delete=10%", 100000, 10}, + {"entries=100000_delete=50%", 100000, 50}, + {"entries=100000_delete=100%", 100000, 100}, + {"entries=1000000_delete=10%", 1000000, 10}, + {"entries=1000000_delete=50%", 1000000, 50}, + {"entries=1000000_delete=100%", 1000000, 100}, } - - for _, tc := range testCases { - t.Run(strconv.Itoa(int(tc.input)), func(t *testing.T) { - if broadcast(tc.input) != tc.expected { - t.Errorf("unexpected result: %x", broadcast(tc.input)) + for _, test := range tests { + b.Run(test.name, func(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + m := NewMap[int, int](WithPresize(test.numEntries)) + for i := 0; i < test.numEntries; i++ { + m.Store(i, i) + } + threshold := test.numEntries * test.deletePercent / 100 + m.DeleteMatching(func(key int, value int) (del, stop bool) { + return key < threshold, false + }) } }) } } -func TestFirstMarkedByteIndex(t *testing.T) { - testCases := []struct { - input uint64 - expected int +func BenchmarkMapRangeDelete(b *testing.B) { + tests := []struct { + name string + numEntries int + deletePercent int }{ - { - input: 0, - expected: 8, - }, - { - input: 0x8080808080808080, - expected: 0, - }, - { - input: 0x0000000000000080, - expected: 0, - }, - { - input: 0x0000000000008000, - expected: 1, - }, - { - input: 0x0000000000800000, - expected: 2, - }, - { - input: 0x0000000080000000, - expected: 3, - }, - { - input: 0x0000008000000000, - expected: 4, - }, - { - input: 0x0000800000000000, - expected: 5, - }, - { - input: 0x0080000000000000, - expected: 6, - }, - { - input: 0x8000000000000000, - expected: 7, - }, + {"entries=1000_delete=10%", 1000, 10}, + {"entries=1000_delete=50%", 1000, 50}, + {"entries=1000_delete=100%", 1000, 100}, + {"entries=100000_delete=10%", 100000, 10}, + {"entries=100000_delete=50%", 100000, 50}, + {"entries=100000_delete=100%", 100000, 100}, + {"entries=1000000_delete=10%", 1000000, 10}, + {"entries=1000000_delete=50%", 1000000, 50}, + {"entries=1000000_delete=100%", 1000000, 100}, } - - for _, tc := range testCases { - t.Run(strconv.Itoa(int(tc.input)), func(t *testing.T) { - if firstMarkedByteIndex(tc.input) != tc.expected { - t.Errorf("unexpected result: %x", firstMarkedByteIndex(tc.input)) - } - }) - } -} - -func TestMarkZeroBytes(t *testing.T) { - testCases := []struct { - input uint64 - expected uint64 - }{ - { - input: 0xffffffffffffffff, - expected: 0, - }, - { - input: 0, - expected: 0x8080808080808080, - }, - { - input: 1, - expected: 0x8080808080808000, - }, - { - input: 1 << 9, - expected: 0x8080808080800080, - }, - { - input: 1 << 17, - expected: 0x8080808080008080, - }, - { - input: 1 << 25, - expected: 0x8080808000808080, - }, - { - input: 1 << 33, - expected: 0x8080800080808080, - }, - { - input: 1 << 41, - expected: 0x8080008080808080, - }, - { - input: 1 << 49, - expected: 0x8000808080808080, - }, - { - input: 1 << 57, - expected: 0x0080808080808080, - }, - // false positive - { - input: 0x0100, - expected: 0x8080808080808080, - }, - } - - for _, tc := range testCases { - t.Run(strconv.Itoa(int(tc.input)), func(t *testing.T) { - if markZeroBytes(tc.input) != tc.expected { - t.Errorf("unexpected result: %x", markZeroBytes(tc.input)) - } - }) - } -} - -func TestSetByte(t *testing.T) { - testCases := []struct { - word uint64 - b uint8 - idx int - expected uint64 - }{ - { - word: 0xffffffffffffffff, - b: 0, - idx: 0, - expected: 0xffffffffffffff00, - }, - { - word: 0xffffffffffffffff, - b: 1, - idx: 1, - expected: 0xffffffffffff01ff, - }, - { - word: 0xffffffffffffffff, - b: 2, - idx: 2, - expected: 0xffffffffff02ffff, - }, - { - word: 0xffffffffffffffff, - b: 3, - idx: 3, - expected: 0xffffffff03ffffff, - }, - { - word: 0xffffffffffffffff, - b: 4, - idx: 4, - expected: 0xffffff04ffffffff, - }, - { - word: 0xffffffffffffffff, - b: 5, - idx: 5, - expected: 0xffff05ffffffffff, - }, - { - word: 0xffffffffffffffff, - b: 6, - idx: 6, - expected: 0xff06ffffffffffff, - }, - { - word: 0xffffffffffffffff, - b: 7, - idx: 7, - expected: 0x07ffffffffffffff, - }, - { - word: 0, - b: 0xff, - idx: 7, - expected: 0xff00000000000000, - }, - } - - for _, tc := range testCases { - t.Run(strconv.Itoa(int(tc.word)), func(t *testing.T) { - if setByte(tc.word, tc.b, tc.idx) != tc.expected { - t.Errorf("unexpected result: %x", setByte(tc.word, tc.b, tc.idx)) + for _, test := range tests { + b.Run(test.name, func(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + m := NewMap[int, int](WithPresize(test.numEntries)) + for i := 0; i < test.numEntries; i++ { + m.Store(i, i) + } + threshold := test.numEntries * test.deletePercent / 100 + m.Range(func(key int, value int) bool { + if key < threshold { + m.Delete(key) + } + return true + }) } }) }