github.com/matrixorigin/matrixone@v0.7.0/pkg/hakeeper/task/cn_ordered_map.go (about)

     1  // Copyright 2022 Matrix Origin
     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 task
    16  
    17  import (
    18  	"sort"
    19  )
    20  
    21  type cnMap struct {
    22  	m           map[string]uint32
    23  	orderedKeys []string
    24  }
    25  
    26  func newOrderedMap(keys []string) *cnMap {
    27  	orderedMap := &cnMap{
    28  		m:           make(map[string]uint32, len(keys)),
    29  		orderedKeys: make([]string, 0, len(keys)),
    30  	}
    31  
    32  	for _, key := range keys {
    33  		orderedMap.m[key] = 0
    34  		orderedMap.orderedKeys = append(orderedMap.orderedKeys, key)
    35  	}
    36  
    37  	return orderedMap
    38  }
    39  
    40  func (o *cnMap) sort() {
    41  	sort.Slice(o.orderedKeys, func(i, j int) bool {
    42  		return o.m[o.orderedKeys[i]] < o.m[o.orderedKeys[j]]
    43  	})
    44  }
    45  
    46  func (o *cnMap) set(key string, val uint32) {
    47  	if _, ok := o.m[key]; !ok {
    48  		o.orderedKeys = append(o.orderedKeys, key)
    49  	}
    50  	o.m[key] = val
    51  	o.sort()
    52  }
    53  
    54  func (o *cnMap) get(key string) uint32 {
    55  	return o.m[key]
    56  }
    57  
    58  func (o *cnMap) inc(key string) {
    59  	o.set(key, o.get(key)+1)
    60  }
    61  
    62  func (o *cnMap) min() string {
    63  	if len(o.orderedKeys) == 0 {
    64  		return ""
    65  	}
    66  	return o.orderedKeys[0]
    67  }