github.com/puellanivis/breton@v0.2.16/lib/metrics/internal/kv/keyval.go (about)

     1  package kv
     2  
     3  import (
     4  	"sort"
     5  )
     6  
     7  // A KeyVal defines an equivalent store to map[string]string that can be used for small maps where traversing in sorted order is important.
     8  // (Small Go maps enforce random traversal which can impose a lot of overhead.)
     9  type KeyVal struct {
    10  	Keys []string
    11  	Vals []string
    12  }
    13  
    14  // Len returns how many entries are in the KeyVal map.
    15  func (kv KeyVal) Len() int {
    16  	return len(kv.Keys)
    17  }
    18  
    19  // Less returns true iff the i-th element should sort before the j-th element.
    20  func (kv KeyVal) Less(i, j int) bool {
    21  	return kv.Keys[i] < kv.Keys[j]
    22  }
    23  
    24  // Swap swaps the i-th and j-th keys and values.
    25  func (kv KeyVal) Swap(i, j int) {
    26  	kv.Keys[i], kv.Keys[j] = kv.Keys[j], kv.Keys[i]
    27  	kv.Vals[i], kv.Vals[j] = kv.Vals[j], kv.Vals[i]
    28  }
    29  
    30  // Sort sorts the KeyVal set.
    31  func (kv KeyVal) Sort() {
    32  	sort.Sort(kv)
    33  }
    34  
    35  // Append adds a (key:value) pair to the end of the KeyVal.
    36  func (kv *KeyVal) Append(key, val string) {
    37  	kv.Keys = append(kv.Keys, key)
    38  	kv.Vals = append(kv.Vals, val)
    39  }
    40  
    41  // Index returns the index a given key has into the KeyVal store, and true if the key is present.
    42  // Otherwise, it returns (0, false).
    43  // (Caller MUST ensure that the KeyVal has been sorted. One may use kv.Sort() from the sort.Keys)
    44  func (kv *KeyVal) Index(key string) (int, bool) {
    45  	i := sort.Search(len(kv.Keys), func(i int) bool {
    46  		return kv.Keys[i] >= key
    47  	})
    48  
    49  	if i < len(kv.Keys) && kv.Keys[i] == key {
    50  		return i, true
    51  	}
    52  
    53  	return 0, false
    54  }