1 // Copyright (c) 2012, Suryandaru Triandana <syndtr@gmail.com>
2 // All rights reserved.
4 // Use of this source code is governed by a BSD-style license that can be
5 // found in the LICENSE file.
22 func (n *lruNode) insert(at *lruNode) {
30 func (n *lruNode) remove() {
37 panic("BUG: removing removed node")
48 func (r *lru) reset() {
49 r.recent.next = &r.recent
50 r.recent.prev = &r.recent
54 func (r *lru) Capacity() int {
60 func (r *lru) SetCapacity(capacity int) {
61 var evicted []*lruNode
65 for r.used > r.capacity {
68 panic("BUG: invalid LRU used or capacity counter")
73 evicted = append(evicted, rn)
77 for _, rn := range evicted {
82 func (r *lru) Promote(n *Node) {
83 var evicted []*lruNode
86 if n.CacheData == nil {
87 if n.Size() <= r.capacity {
88 rn := &lruNode{n: n, h: n.GetHandle()}
90 n.CacheData = unsafe.Pointer(rn)
93 for r.used > r.capacity {
96 panic("BUG: invalid LRU used or capacity counter")
100 r.used -= rn.n.Size()
101 evicted = append(evicted, rn)
105 rn := (*lruNode)(n.CacheData)
113 for _, rn := range evicted {
118 func (r *lru) Ban(n *Node) {
120 if n.CacheData == nil {
121 n.CacheData = unsafe.Pointer(&lruNode{n: n, ban: true})
123 rn := (*lruNode)(n.CacheData)
127 r.used -= rn.n.Size()
138 func (r *lru) Evict(n *Node) {
140 rn := (*lruNode)(n.CacheData)
141 if rn == nil || rn.ban {
151 func (r *lru) EvictNS(ns uint64) {
152 var evicted []*lruNode
155 for e := r.recent.prev; e != &r.recent; {
161 r.used -= rn.n.Size()
162 evicted = append(evicted, rn)
167 for _, rn := range evicted {
172 func (r *lru) EvictAll() {
174 back := r.recent.prev
175 for rn := back; rn != &r.recent; rn = rn.prev {
181 for rn := back; rn != &r.recent; rn = rn.prev {
186 func (r *lru) Close() error {
190 // NewLRU create a new LRU-cache.
191 func NewLRU(capacity int) Cacher {
192 r := &lru{capacity: capacity}