github.com/gnolang/gno@v0.0.0-20240520182011-228e9d0192ce/tm2/pkg/std/kvpair.go (about)

     1  package std
     2  
     3  import (
     4  	"bytes"
     5  	"sort"
     6  )
     7  
     8  //----------------------------------------
     9  // KVPair
    10  
    11  // KVPair is a key-value struct for []byte value.
    12  type KVPair struct {
    13  	Key   []byte
    14  	Value []byte
    15  }
    16  
    17  // KVPairs is a slice of KVPair.
    18  type KVPairs []KVPair
    19  
    20  // Len returns the length of kvs.
    21  func (kvs KVPairs) Len() int {
    22  	return len(kvs)
    23  }
    24  
    25  // Less reports whether kvs[i] should be ordered before kvs[j].
    26  func (kvs KVPairs) Less(i, j int) bool {
    27  	switch bytes.Compare(kvs[i].Key, kvs[j].Key) {
    28  	case -1:
    29  		return true
    30  	case 0:
    31  		return bytes.Compare(kvs[i].Value, kvs[j].Value) < 0
    32  	case 1:
    33  		return false
    34  	default:
    35  		panic("invalid comparison result")
    36  	}
    37  }
    38  
    39  // Swap swaps the elements with indexes, i and j.
    40  func (kvs KVPairs) Swap(i, j int) {
    41  	kvs[i], kvs[j] = kvs[j], kvs[i]
    42  }
    43  
    44  // Sort sorts a kvs in ascending order.
    45  func (kvs KVPairs) Sort() {
    46  	sort.Sort(kvs)
    47  }
    48  
    49  //----------------------------------------
    50  // KI64Pair
    51  
    52  // KI64Pair is a key-value struct for int64 value.
    53  type KI64Pair struct {
    54  	Key   []byte
    55  	Value int64
    56  }
    57  
    58  // KI64Pairs is a slice of KI64Pair.
    59  type KI64Pairs []KI64Pair
    60  
    61  // Len returns the length of kvs.
    62  func (kvs KI64Pairs) Len() int { return len(kvs) }
    63  
    64  // Less reports whether kvs[i] should be ordered before kvs[j].
    65  func (kvs KI64Pairs) Less(i, j int) bool {
    66  	switch bytes.Compare(kvs[i].Key, kvs[j].Key) {
    67  	case -1:
    68  		return true
    69  	case 0:
    70  		return kvs[i].Value < kvs[j].Value
    71  	case 1:
    72  		return false
    73  	default:
    74  		panic("invalid comparison result")
    75  	}
    76  }
    77  
    78  // Swap swaps the elements with indexes, i and j.
    79  func (kvs KI64Pairs) Swap(i, j int) {
    80  	kvs[i], kvs[j] = kvs[j], kvs[i]
    81  }
    82  
    83  // Sort sorts a kvs in ascending order.
    84  func (kvs KI64Pairs) Sort() {
    85  	sort.Sort(kvs)
    86  }