github.com/searKing/golang/go@v1.2.117/sync/lru_pool.lru.go (about)

     1  // Copyright 2021 The searKing Author. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package sync
     6  
     7  import (
     8  	"container/list"
     9  )
    10  
    11  type resourceLRU struct {
    12  	ll *list.List // list.Element.Value type is of *PersistResource
    13  	m  map[*PersistResource]*list.Element
    14  }
    15  
    16  // add adds pc to the head of the linked list.
    17  func (cl *resourceLRU) add(pc *PersistResource) {
    18  	if cl.ll == nil {
    19  		cl.ll = list.New()
    20  		cl.m = make(map[*PersistResource]*list.Element)
    21  	}
    22  	ele := cl.ll.PushFront(pc)
    23  	if _, ok := cl.m[pc]; ok {
    24  		panic("PersistResource was already in LRU")
    25  	}
    26  	cl.m[pc] = ele
    27  }
    28  
    29  func (cl *resourceLRU) removeOldest() *PersistResource {
    30  	ele := cl.ll.Back()
    31  	pc := ele.Value.(*PersistResource)
    32  	cl.ll.Remove(ele)
    33  	delete(cl.m, pc)
    34  	return pc
    35  }
    36  
    37  // remove remove pc from cl.
    38  func (cl *resourceLRU) remove(pc *PersistResource) {
    39  	if ele, ok := cl.m[pc]; ok {
    40  		cl.ll.Remove(ele)
    41  		delete(cl.m, pc)
    42  	}
    43  }
    44  
    45  // len returns the number of items in the cache.
    46  func (cl *resourceLRU) len() int {
    47  	return len(cl.m)
    48  }