github.com/fzfile/BaiduPCS-Go@v0.0.0-20200606205115-4408961cf336/pcsutil/cachepool/cachepool.go (about)

     1  package cachepool
     2  
     3  import (
     4  	"sync"
     5  )
     6  
     7  var (
     8  	//CachePool []byte 缓存池 2
     9  	CachePool = cachePool2{}
    10  )
    11  
    12  //Cache cache
    13  type Cache interface {
    14  	Bytes() []byte
    15  	Free()
    16  }
    17  
    18  type cache struct {
    19  	isUsed bool
    20  	b      []byte
    21  }
    22  
    23  func (c *cache) Bytes() []byte {
    24  	if !c.isUsed {
    25  		return nil
    26  	}
    27  	return c.b
    28  }
    29  
    30  func (c *cache) Free() {
    31  	c.isUsed = false
    32  }
    33  
    34  type cachePool2 struct {
    35  	pool []*cache
    36  	mu   sync.Mutex
    37  }
    38  
    39  func (cp2 *cachePool2) Require(size int) Cache {
    40  	cp2.mu.Lock()
    41  	defer cp2.mu.Unlock()
    42  	for k := range cp2.pool {
    43  		if cp2.pool[k] == nil || cp2.pool[k].isUsed || len(cp2.pool[k].b) < size {
    44  			continue
    45  		}
    46  
    47  		cp2.pool[k].isUsed = true
    48  		return cp2.pool[k]
    49  	}
    50  	newCache := &cache{
    51  		isUsed: true,
    52  		b:      RawMallocByteSlice(size),
    53  	}
    54  	cp2.addCache(newCache)
    55  	return newCache
    56  }
    57  
    58  func (cp2 *cachePool2) addCache(newCache *cache) {
    59  	for k := range cp2.pool {
    60  		if cp2.pool[k] == nil {
    61  			cp2.pool[k] = newCache
    62  			return
    63  		}
    64  	}
    65  	cp2.pool = append(cp2.pool, newCache)
    66  }
    67  
    68  func (cp2 *cachePool2) DeleteNotUsed() {
    69  	cp2.mu.Lock()
    70  	defer cp2.mu.Unlock()
    71  	for k := range cp2.pool {
    72  		if cp2.pool[k] == nil {
    73  			continue
    74  		}
    75  
    76  		if !cp2.pool[k].isUsed {
    77  			cp2.pool[k] = nil
    78  		}
    79  	}
    80  }
    81  
    82  func (cp2 *cachePool2) DeleteAll() {
    83  	cp2.mu.Lock()
    84  	defer cp2.mu.Unlock()
    85  	for k := range cp2.pool {
    86  		cp2.pool[k] = nil
    87  	}
    88  }
    89  
    90  //Require 申请Cache
    91  func Require(size int) Cache {
    92  	return CachePool.Require(size)
    93  }