Debian Codegraph @

plumbing/cache/object_lru.go

raw
1 package cache
2
3 import (
4 "container/list"
5 "sync"
6
7 "github.com/go-git/go-git/v5/plumbing"
8 )
9
10 // ObjectLRU implements an object cache with an LRU eviction policy and a
11 // maximum size (measured in object size).
12 type ObjectLRU struct {
13 MaxSize FileSize
14
15 actualSize FileSize
16 ll *list.List
17 cache map[interface{}]*list.Element
18 mut sync.Mutex
19 }
20
21 // NewObjectLRU creates a new ObjectLRU with the given maximum size. The maximum
22 // size will never be exceeded.
23 func NewObjectLRU(maxSize FileSize) *ObjectLRU {
24 return &ObjectLRU{MaxSize: maxSize}
25 }
26
27 // NewObjectLRUDefault creates a new ObjectLRU with the default cache size.
28 func NewObjectLRUDefault() *ObjectLRU {
29 return &ObjectLRU{MaxSize: DefaultMaxSize}
30 }
31
32 // Put puts an object into the cache. If the object is already in the cache, it
33 // will be marked as used. Otherwise, it will be inserted. A single object might
34 // be evicted to make room for the new object.
35 func (c *ObjectLRU) Put(obj plumbing.EncodedObject) {
36 c.mut.Lock()
37 defer c.mut.Unlock()
38
39 if c.cache == nil {
40 c.actualSize = 0
41 c.cache = make(map[interface{}]*list.Element, 1000)
42 c.ll = list.New()
43 }
44
45 objSize := FileSize(obj.Size())
46 key := obj.Hash()
47 if ee, ok := c.cache[key]; ok {
48 oldObj := ee.Value.(plumbing.EncodedObject)
49 // in this case objSize is a delta: new size - old size
50 objSize -= FileSize(oldObj.Size())
51 c.ll.MoveToFront(ee)
52 ee.Value = obj
53 } else {
54 if objSize > c.MaxSize {
55 return
56 }
57 ee := c.ll.PushFront(obj)
58 c.cache[key] = ee
59 }
60
61 c.actualSize += objSize
62 for c.actualSize > c.MaxSize {
63 last := c.ll.Back()
64 if last == nil {
65 c.actualSize = 0
66 break
67 }
68
69 lastObj := last.Value.(plumbing.EncodedObject)
70 lastSize := FileSize(lastObj.Size())
71
72 c.ll.Remove(last)
73 delete(c.cache, lastObj.Hash())
74 c.actualSize -= lastSize
75 }
76 }
77
78 // Get returns an object by its hash. It marks the object as used. If the object
79 // is not in the cache, (nil, false) will be returned.
80 func (c *ObjectLRU) Get(k plumbing.Hash) (plumbing.EncodedObject, bool) {
81 c.mut.Lock()
82 defer c.mut.Unlock()
83
84 ee, ok := c.cache[k]
85 if !ok {
86 return nil, false
87 }
88
89 c.ll.MoveToFront(ee)
90 return ee.Value.(plumbing.EncodedObject), true
91 }
92
93 // Clear the content of this object cache.
94 func (c *ObjectLRU) Clear() {
95 c.mut.Lock()
96 defer c.mut.Unlock()
97
98 c.ll = nil
99 c.cache = nil
100 c.actualSize = 0
101 }