github.com/elfadel/cilium@v1.6.12/pkg/counter/integer.go (about)

     1  // Copyright 2018 Authors of Cilium
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package counter
    16  
    17  import (
    18  	"sort"
    19  )
    20  
    21  // IntCounter tracks references for integers with an optional limiter.
    22  //
    23  // No threadsafety is provided within this structure, the user is expected to
    24  // handle concurrent access to this structure if it is used from multiple
    25  // threads.
    26  type IntCounter map[int]int
    27  
    28  // DeepCopy makes a new copy of the received IntCounter.
    29  func (i IntCounter) DeepCopy() IntCounter {
    30  	result := make(IntCounter, len(i))
    31  	for k, v := range i {
    32  		result[k] = v
    33  	}
    34  	return result
    35  }
    36  
    37  // Add increments the reference count for the specified integer key.
    38  func (i IntCounter) Add(key int) (changed bool) {
    39  	value, exists := i[key]
    40  	if !exists {
    41  		changed = true
    42  	}
    43  	i[key] = value + 1
    44  	return changed
    45  }
    46  
    47  // Delete decrements the reference count for the specified integer key.
    48  func (i IntCounter) Delete(key int) bool {
    49  	value := i[key]
    50  	if value <= 1 {
    51  		delete(i, key)
    52  		return true
    53  	}
    54  	i[key] = value - 1
    55  	return false
    56  }
    57  
    58  // ToBPFData returns the keys as a slice, sorted from high to low.
    59  func (i IntCounter) ToBPFData() []int {
    60  	result := make([]int, 0, len(i))
    61  
    62  	for key := range i {
    63  		result = append(result, key)
    64  	}
    65  	sort.Sort(sort.Reverse(sort.IntSlice(result)))
    66  	return result
    67  }