github.com/cilium/cilium@v1.16.2/pkg/counter/counter.go (about)

     1  // SPDX-License-Identifier: Apache-2.0
     2  // Copyright Authors of Cilium
     3  
     4  package counter
     5  
     6  // Counter tracks references for comparable .
     7  //
     8  // No thread safety is provided within this structure, the user is expected to
     9  // handle concurrent access to this structure if it is used from multiple
    10  // threads.
    11  type Counter[T comparable] map[T]int
    12  
    13  // Add increments the reference count for the specified key.
    14  func (c Counter[T]) Add(key T) bool {
    15  	value, exists := c[key]
    16  	c[key] = value + 1
    17  	return !exists
    18  }
    19  
    20  // Delete decrements the reference count for the specified key.
    21  func (c Counter[T]) Delete(key T) bool {
    22  	value := c[key]
    23  	if value <= 1 {
    24  		delete(c, key)
    25  		return true
    26  	}
    27  	c[key] = value - 1
    28  	return false
    29  }
    30  
    31  // DeepCopy makes a new copy of the received Counter.
    32  func (c Counter[T]) DeepCopy() Counter[T] {
    33  	result := make(Counter[T], len(c))
    34  	for k, v := range c {
    35  		result[k] = v
    36  	}
    37  	return result
    38  }