github.com/GoWebProd/gip@v0.0.0-20230623090727-b60d41d5d320/smap/map.go (about)

     1  package smap
     2  
     3  // Copyright 2016 The Go Authors. All rights reserved.
     4  // Use of this source code is governed by a BSD-style
     5  // license that can be found in the LICENSE file.
     6  
     7  import (
     8  	"sync"
     9  	"sync/atomic"
    10  	"unsafe"
    11  )
    12  
    13  // Map is like a Go map[interface{}]interface{} but is safe for concurrent use
    14  // by multiple goroutines without additional locking or coordination.
    15  // Loads, stores, and deletes run in amortized constant time.
    16  //
    17  // The Map type is specialized. Most code should use a plain Go map instead,
    18  // with separate locking or coordination, for better type safety and to make it
    19  // easier to maintain other invariants along with the map content.
    20  //
    21  // The Map type is optimized for two common use cases: (1) when the entry for a given
    22  // key is only ever written once but read many times, as in caches that only grow,
    23  // or (2) when multiple goroutines read, write, and overwrite entries for disjoint
    24  // sets of keys. In these two cases, use of a Map may significantly reduce lock
    25  // contention compared to a Go map paired with a separate Mutex or RWMutex.
    26  //
    27  // The zero Map is empty and ready for use. A Map must not be copied after first use.
    28  type Map[K comparable, V any] struct {
    29  	mu sync.Mutex
    30  
    31  	// read contains the portion of the map's contents that are safe for
    32  	// concurrent access (with or without mu held).
    33  	//
    34  	// The read field itself is always safe to load, but must only be stored with
    35  	// mu held.
    36  	//
    37  	// Entries stored in read may be updated concurrently without mu, but updating
    38  	// a previously-expunged entry requires that the entry be copied to the dirty
    39  	// map and unexpunged with mu held.
    40  	read atomic.Value // readOnly
    41  
    42  	// dirty contains the portion of the map's contents that require mu to be
    43  	// held. To ensure that the dirty map can be promoted to the read map quickly,
    44  	// it also includes all of the non-expunged entries in the read map.
    45  	//
    46  	// Expunged entries are not stored in the dirty map. An expunged entry in the
    47  	// clean map must be unexpunged and added to the dirty map before a new value
    48  	// can be stored to it.
    49  	//
    50  	// If the dirty map is nil, the next write to the map will initialize it by
    51  	// making a shallow copy of the clean map, omitting stale entries.
    52  	dirty map[K]*entry[V]
    53  
    54  	// misses counts the number of loads since the read map was last updated that
    55  	// needed to lock mu to determine whether the key was present.
    56  	//
    57  	// Once enough misses have occurred to cover the cost of copying the dirty
    58  	// map, the dirty map will be promoted to the read map (in the unamended
    59  	// state) and the next store to the map will make a new dirty copy.
    60  	misses int
    61  }
    62  
    63  // readOnly is an immutable struct stored atomically in the Map.read field.
    64  type readOnly[K comparable, V any] struct {
    65  	m       map[K]*entry[V]
    66  	amended bool // true if the dirty map contains some key not in m.
    67  }
    68  
    69  // expunged is an arbitrary pointer that marks entries which have been deleted
    70  // from the dirty map.
    71  var expunged = unsafe.Pointer(new(interface{}))
    72  
    73  // An entry is a slot in the map corresponding to a particular key.
    74  type entry[V any] struct {
    75  	// p points to the interface{} value stored for the entry.
    76  	//
    77  	// If p == nil, the entry has been deleted, and either m.dirty == nil or
    78  	// m.dirty[key] is e.
    79  	//
    80  	// If p == expunged, the entry has been deleted, m.dirty != nil, and the entry
    81  	// is missing from m.dirty.
    82  	//
    83  	// Otherwise, the entry is valid and recorded in m.read.m[key] and, if m.dirty
    84  	// != nil, in m.dirty[key].
    85  	//
    86  	// An entry can be deleted by atomic replacement with nil: when m.dirty is
    87  	// next created, it will atomically replace nil with expunged and leave
    88  	// m.dirty[key] unset.
    89  	//
    90  	// An entry's associated value can be updated by atomic replacement, provided
    91  	// p != expunged. If p == expunged, an entry's associated value can be updated
    92  	// only after first setting m.dirty[key] = e so that lookups using the dirty
    93  	// map find the entry.
    94  	p unsafe.Pointer // *interface{}
    95  }
    96  
    97  func newEntry[V any](i V) *entry[V] {
    98  	return &entry[V]{p: unsafe.Pointer(&i)}
    99  }
   100  
   101  // Load returns the value stored in the map for a key, or nil if no
   102  // value is present.
   103  // The ok result indicates whether value was found in the map.
   104  func (m *Map[K, V]) Load(key K) (value V, ok bool) {
   105  	var v V
   106  
   107  	read, _ := m.read.Load().(readOnly[K, V])
   108  
   109  	e, ok := read.m[key]
   110  	if !ok && read.amended {
   111  		m.mu.Lock()
   112  		// Avoid reporting a spurious miss if m.dirty got promoted while we were
   113  		// blocked on m.mu. (If further loads of the same key will not miss, it's
   114  		// not worth copying the dirty map for this key.)
   115  		read, _ = m.read.Load().(readOnly[K, V])
   116  
   117  		e, ok = read.m[key]
   118  		if !ok && read.amended {
   119  			e, ok = m.dirty[key]
   120  			// Regardless of whether the entry was present, record a miss: this key
   121  			// will take the slow path until the dirty map is promoted to the read
   122  			// map.
   123  			m.missLocked()
   124  		}
   125  
   126  		m.mu.Unlock()
   127  	}
   128  
   129  	if !ok {
   130  		return v, false
   131  	}
   132  
   133  	return e.load()
   134  }
   135  
   136  func (e *entry[V]) load() (value V, ok bool) {
   137  	var v V
   138  
   139  	p := atomic.LoadPointer(&e.p)
   140  	if p == nil || p == expunged {
   141  		return v, false
   142  	}
   143  
   144  	return *(*V)(p), true
   145  }
   146  
   147  // Store sets the value for a key.
   148  func (m *Map[K, V]) Store(key K, value V) {
   149  	read, _ := m.read.Load().(readOnly[K, V])
   150  	if e, ok := read.m[key]; ok && e.tryStore(&value) {
   151  		return
   152  	}
   153  
   154  	m.mu.Lock()
   155  	read, _ = m.read.Load().(readOnly[K, V])
   156  	if e, ok := read.m[key]; ok {
   157  		if e.unexpungeLocked() {
   158  			// The entry was previously expunged, which implies that there is a
   159  			// non-nil dirty map and this entry is not in it.
   160  			m.dirty[key] = e
   161  		}
   162  		e.storeLocked(&value)
   163  	} else if e, ok := m.dirty[key]; ok {
   164  		e.storeLocked(&value)
   165  	} else {
   166  		if !read.amended {
   167  			// We're adding the first new key to the dirty map.
   168  			// Make sure it is allocated and mark the read-only map as incomplete.
   169  			m.dirtyLocked()
   170  			m.read.Store(readOnly[K, V]{m: read.m, amended: true})
   171  		}
   172  		m.dirty[key] = newEntry(value)
   173  	}
   174  	m.mu.Unlock()
   175  }
   176  
   177  // tryStore stores a value if the entry has not been expunged.
   178  //
   179  // If the entry is expunged, tryStore returns false and leaves the entry
   180  // unchanged.
   181  func (e *entry[V]) tryStore(i *V) bool {
   182  	for {
   183  		p := atomic.LoadPointer(&e.p)
   184  		if p == expunged {
   185  			return false
   186  		}
   187  		if atomic.CompareAndSwapPointer(&e.p, p, unsafe.Pointer(i)) {
   188  			return true
   189  		}
   190  	}
   191  }
   192  
   193  // unexpungeLocked ensures that the entry is not marked as expunged.
   194  //
   195  // If the entry was previously expunged, it must be added to the dirty map
   196  // before m.mu is unlocked.
   197  func (e *entry[V]) unexpungeLocked() (wasExpunged bool) {
   198  	return atomic.CompareAndSwapPointer(&e.p, expunged, nil)
   199  }
   200  
   201  // storeLocked unconditionally stores a value to the entry.
   202  //
   203  // The entry must be known not to be expunged.
   204  func (e *entry[V]) storeLocked(i *V) {
   205  	atomic.StorePointer(&e.p, unsafe.Pointer(i))
   206  }
   207  
   208  // LoadOrStore returns the existing value for the key if present.
   209  // Otherwise, it stores and returns the given value.
   210  // The loaded result is true if the value was loaded, false if stored.
   211  func (m *Map[K, V]) LoadOrStore(key K, value V) (actual V, loaded bool) {
   212  	// Avoid locking if it's a clean hit.
   213  	read, _ := m.read.Load().(readOnly[K, V])
   214  	if e, ok := read.m[key]; ok {
   215  		actual, loaded, ok := e.tryLoadOrStore(value)
   216  		if ok {
   217  			return actual, loaded
   218  		}
   219  	}
   220  
   221  	m.mu.Lock()
   222  	read, _ = m.read.Load().(readOnly[K, V])
   223  	if e, ok := read.m[key]; ok {
   224  		if e.unexpungeLocked() {
   225  			m.dirty[key] = e
   226  		}
   227  		actual, loaded, _ = e.tryLoadOrStore(value)
   228  	} else if e, ok := m.dirty[key]; ok {
   229  		actual, loaded, _ = e.tryLoadOrStore(value)
   230  		m.missLocked()
   231  	} else {
   232  		if !read.amended {
   233  			// We're adding the first new key to the dirty map.
   234  			// Make sure it is allocated and mark the read-only map as incomplete.
   235  			m.dirtyLocked()
   236  			m.read.Store(readOnly[K, V]{m: read.m, amended: true})
   237  		}
   238  		m.dirty[key] = newEntry(value)
   239  		actual, loaded = value, false
   240  	}
   241  	m.mu.Unlock()
   242  
   243  	return actual, loaded
   244  }
   245  
   246  // tryLoadOrStore atomically loads or stores a value if the entry is not
   247  // expunged.
   248  //
   249  // If the entry is expunged, tryLoadOrStore leaves the entry unchanged and
   250  // returns with ok==false.
   251  func (e *entry[V]) tryLoadOrStore(i V) (actual V, loaded, ok bool) {
   252  	var v V
   253  
   254  	p := atomic.LoadPointer(&e.p)
   255  	if p == expunged {
   256  		return v, false, false
   257  	}
   258  	if p != nil {
   259  		return *(*V)(p), true, true
   260  	}
   261  
   262  	// Copy the interface after the first load to make this method more amenable
   263  	// to escape analysis: if we hit the "load" path or the entry is expunged, we
   264  	// shouldn't bother heap-allocating.
   265  	ic := i
   266  	for {
   267  		if atomic.CompareAndSwapPointer(&e.p, nil, unsafe.Pointer(&ic)) {
   268  			return i, false, true
   269  		}
   270  		p = atomic.LoadPointer(&e.p)
   271  		if p == expunged {
   272  			return v, false, false
   273  		}
   274  		if p != nil {
   275  			return *(*V)(p), true, true
   276  		}
   277  	}
   278  }
   279  
   280  // LoadAndDelete deletes the value for a key, returning the previous value if any.
   281  // The loaded result reports whether the key was present.
   282  func (m *Map[K, V]) LoadAndDelete(key K) (value V, loaded bool) {
   283  	var v V
   284  
   285  	read, _ := m.read.Load().(readOnly[K, V])
   286  	e, ok := read.m[key]
   287  	if !ok && read.amended {
   288  		m.mu.Lock()
   289  		read, _ = m.read.Load().(readOnly[K, V])
   290  		e, ok = read.m[key]
   291  		if !ok && read.amended {
   292  			e, ok = m.dirty[key]
   293  			delete(m.dirty, key)
   294  			// Regardless of whether the entry was present, record a miss: this key
   295  			// will take the slow path until the dirty map is promoted to the read
   296  			// map.
   297  			m.missLocked()
   298  		}
   299  		m.mu.Unlock()
   300  	}
   301  	if ok {
   302  		return e.delete()
   303  	}
   304  
   305  	return v, false
   306  }
   307  
   308  // Delete deletes the value for a key.
   309  func (m *Map[K, V]) Delete(key K) {
   310  	m.LoadAndDelete(key)
   311  }
   312  
   313  func (e *entry[V]) delete() (value V, ok bool) {
   314  	var v V
   315  
   316  	for {
   317  		p := atomic.LoadPointer(&e.p)
   318  		if p == nil || p == expunged {
   319  			return v, false
   320  		}
   321  		if atomic.CompareAndSwapPointer(&e.p, p, nil) {
   322  			return *(*V)(p), true
   323  		}
   324  	}
   325  }
   326  
   327  // Range calls f sequentially for each key and value present in the map.
   328  // If f returns false, range stops the iteration.
   329  //
   330  // Range does not necessarily correspond to any consistent snapshot of the Map's
   331  // contents: no key will be visited more than once, but if the value for any key
   332  // is stored or deleted concurrently, Range may reflect any mapping for that key
   333  // from any point during the Range call.
   334  //
   335  // Range may be O(N) with the number of elements in the map even if f returns
   336  // false after a constant number of calls.
   337  func (m *Map[K, V]) Range(f func(key K, value V) bool) {
   338  	// We need to be able to iterate over all of the keys that were already
   339  	// present at the start of the call to Range.
   340  	// If read.amended is false, then read.m satisfies that property without
   341  	// requiring us to hold m.mu for a long time.
   342  	read, _ := m.read.Load().(readOnly[K, V])
   343  	if read.amended {
   344  		// m.dirty contains keys not in read.m. Fortunately, Range is already O(N)
   345  		// (assuming the caller does not break out early), so a call to Range
   346  		// amortizes an entire copy of the map: we can promote the dirty copy
   347  		// immediately!
   348  		m.mu.Lock()
   349  		read, _ = m.read.Load().(readOnly[K, V])
   350  		if read.amended {
   351  			read = readOnly[K, V]{m: m.dirty}
   352  			m.read.Store(read)
   353  			m.dirty = nil
   354  			m.misses = 0
   355  		}
   356  		m.mu.Unlock()
   357  	}
   358  
   359  	for k, e := range read.m {
   360  		v, ok := e.load()
   361  		if !ok {
   362  			continue
   363  		}
   364  		if !f(k, v) {
   365  			break
   366  		}
   367  	}
   368  }
   369  
   370  func (m *Map[K, V]) missLocked() {
   371  	m.misses++
   372  	if m.misses < len(m.dirty) {
   373  		return
   374  	}
   375  	m.read.Store(readOnly[K, V]{m: m.dirty})
   376  	m.dirty = nil
   377  	m.misses = 0
   378  }
   379  
   380  func (m *Map[K, V]) dirtyLocked() {
   381  	if m.dirty != nil {
   382  		return
   383  	}
   384  
   385  	read, _ := m.read.Load().(readOnly[K, V])
   386  	m.dirty = make(map[K]*entry[V], len(read.m))
   387  	for k, e := range read.m {
   388  		if !e.tryExpungeLocked() {
   389  			m.dirty[k] = e
   390  		}
   391  	}
   392  }
   393  
   394  func (e *entry[V]) tryExpungeLocked() (isExpunged bool) {
   395  	p := atomic.LoadPointer(&e.p)
   396  	for p == nil {
   397  		if atomic.CompareAndSwapPointer(&e.p, nil, expunged) {
   398  			return true
   399  		}
   400  		p = atomic.LoadPointer(&e.p)
   401  	}
   402  	return p == expunged
   403  }