github.com/TeaOSLab/EdgeNode@v1.3.8/internal/utils/maps/map_fixed.go (about)

     1  // Copyright 2023 Liuxiangchao iwind.liu@gmail.com. All rights reserved. Official site: https://goedge.cn .
     2  
     3  package maputils
     4  
     5  import "sync"
     6  
     7  type KeyType interface {
     8  	string | int | int64 | int32 | uint64 | uint32
     9  }
    10  
    11  type ValueType interface {
    12  	any
    13  }
    14  
    15  // FixedMap
    16  // TODO 解决已存在元素不能按顺序弹出的问题
    17  type FixedMap[KeyT KeyType, ValueT ValueType] struct {
    18  	m    map[KeyT]ValueT
    19  	keys []KeyT
    20  
    21  	maxSize int
    22  	locker  sync.RWMutex
    23  }
    24  
    25  func NewFixedMap[KeyT KeyType, ValueT ValueType](maxSize int) *FixedMap[KeyT, ValueT] {
    26  	return &FixedMap[KeyT, ValueT]{
    27  		maxSize: maxSize,
    28  		m:       map[KeyT]ValueT{},
    29  	}
    30  }
    31  
    32  func (this *FixedMap[KeyT, ValueT]) Put(key KeyT, value ValueT) {
    33  	this.locker.Lock()
    34  	defer this.locker.Unlock()
    35  
    36  	if this.maxSize <= 0 {
    37  		return
    38  	}
    39  
    40  	_, exists := this.m[key]
    41  	this.m[key] = value
    42  
    43  	if !exists {
    44  		this.keys = append(this.keys, key)
    45  
    46  		if len(this.keys) > this.maxSize {
    47  			var firstKey = this.keys[0]
    48  			this.keys = this.keys[1:]
    49  			delete(this.m, firstKey)
    50  		}
    51  	}
    52  }
    53  
    54  func (this *FixedMap[KeyT, ValueT]) Get(key KeyT) (value ValueT, ok bool) {
    55  	this.locker.RLock()
    56  	defer this.locker.RUnlock()
    57  	value, ok = this.m[key]
    58  	return
    59  }
    60  
    61  func (this *FixedMap[KeyT, ValueT]) Has(key KeyT) bool {
    62  	this.locker.RLock()
    63  	defer this.locker.RUnlock()
    64  	_, ok := this.m[key]
    65  	return ok
    66  }
    67  
    68  func (this *FixedMap[KeyT, ValueT]) Keys() []KeyT {
    69  	this.locker.RLock()
    70  	defer this.locker.RUnlock()
    71  	return this.keys
    72  }
    73  
    74  func (this *FixedMap[KeyT, ValueT]) RawMap() map[KeyT]ValueT {
    75  	this.locker.RLock()
    76  	defer this.locker.RUnlock()
    77  	return this.m
    78  }