github.com/qjfoidnh/BaiduPCS-Go@v0.0.0-20231011165705-caa18a3765f3/pcsutil/cachepool/idcachepool.go (about)

     1  // Package cachepool []byte缓存池
     2  package cachepool
     3  
     4  import (
     5  	"sync"
     6  	"sync/atomic"
     7  )
     8  
     9  var (
    10  	// IDCachePool []byte 缓存池
    11  	IDCachePool = cachePool{
    12  		cachepool: sync.Map{},
    13  	}
    14  )
    15  
    16  type cachePool struct {
    17  	lastID    int32
    18  	cachepool sync.Map
    19  }
    20  
    21  func (cp *cachePool) Apply(size int) (id int32) {
    22  	for {
    23  		_, ok := cp.cachepool.Load(cp.lastID)
    24  		atomic.AddInt32(&cp.lastID, 1)
    25  		if ok {
    26  			continue
    27  		}
    28  		break
    29  	}
    30  
    31  	cp.Set(cp.lastID, size)
    32  	return cp.lastID
    33  }
    34  
    35  func (cp *cachePool) Existed(id int32) (existed bool) {
    36  	_, existed = cp.cachepool.Load(id)
    37  	return
    38  }
    39  
    40  func (cp *cachePool) Get(id int32) []byte {
    41  	cache, ok := cp.cachepool.Load(id)
    42  	if !ok {
    43  		return nil
    44  	}
    45  	return cache.([]byte)
    46  }
    47  
    48  func (cp *cachePool) Set(id int32, size int) []byte {
    49  	cache := RawMallocByteSlice(size)
    50  	cp.cachepool.Store(id, cache)
    51  	return cp.Get(id)
    52  }
    53  
    54  func (cp *cachePool) SetIfNotExist(id int32, size int) []byte {
    55  	ok := cp.Existed(id)
    56  	cache := cp.Get(id)
    57  	if !ok || len(cache) < size {
    58  		cache = nil
    59  		cp.Delete(id)
    60  		cp.Set(id, size)
    61  	}
    62  	return cp.Get(id)
    63  }
    64  
    65  func (cp *cachePool) Delete(id int32) {
    66  	cp.cachepool.Store(id, nil)
    67  	cp.cachepool.Delete(id)
    68  }
    69  
    70  func (cp *cachePool) DeleteAll() {
    71  	cp.cachepool.Range(func(k interface{}, _ interface{}) bool {
    72  		cp.Delete(k.(int32))
    73  		return true
    74  	})
    75  }
    76  
    77  // Apply 申请缓存, 返回缓存id
    78  func Apply(size int) (id int32) {
    79  	return IDCachePool.Apply(size)
    80  }
    81  
    82  // Existed 通过缓存id检测是否存在缓存
    83  func Existed(id int32) bool {
    84  	return IDCachePool.Existed(id)
    85  }
    86  
    87  // Get 通过缓存id获取缓存[]byte
    88  func Get(id int32) []byte {
    89  	return IDCachePool.Get(id)
    90  }
    91  
    92  // Set 设置缓存, 通过给定的缓存id
    93  func Set(id int32, size int) []byte {
    94  	return IDCachePool.Set(id, size)
    95  }
    96  
    97  // SetIfNotExist 如果缓存不存在, 则设置缓存池
    98  func SetIfNotExist(id int32, size int) []byte {
    99  	return IDCachePool.SetIfNotExist(id, size)
   100  }
   101  
   102  // Delete 通过缓存id删除缓存
   103  func Delete(id int32) {
   104  	IDCachePool.Delete(id)
   105  }
   106  
   107  // DeleteAll 清空缓存池
   108  func DeleteAll() {
   109  	IDCachePool.DeleteAll()
   110  }