aboutsummaryrefslogtreecommitdiffstats
path: root/cache/object.go
blob: 47e390bea4ea8e6b2bf4d6a7f2f0c3076c0bb5c1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package cache

import "srcd.works/go-git.v4/plumbing"

const (
	initialQueueSize = 20
	MaxSize          = 10 * MiByte
)

type ObjectFIFO struct {
	objects map[plumbing.Hash]plumbing.EncodedObject
	order   *queue

	maxSize    int64
	actualSize int64
}

// NewObjectFIFO returns an Object cache that keeps the newest objects that fit
// into the specific memory size
func NewObjectFIFO(size int64) *ObjectFIFO {
	return &ObjectFIFO{
		objects: make(map[plumbing.Hash]plumbing.EncodedObject),
		order:   newQueue(initialQueueSize),
		maxSize: size,
	}
}

// Add adds a new object to the cache. If the object size is greater than the
// cache size, the object is not added.
func (c *ObjectFIFO) Add(o plumbing.EncodedObject) {
	// if the size of the object is bigger or equal than the cache size,
	// skip it
	if o.Size() >= c.maxSize {
		return
	}

	// if the object is into the cache, do not add it again
	if _, ok := c.objects[o.Hash()]; ok {
		return
	}

	// delete the oldest object if cache is full
	if c.actualSize >= c.maxSize {
		h := c.order.Pop()
		o := c.objects[h]
		if o != nil {
			c.actualSize -= o.Size()
			delete(c.objects, h)
		}
	}

	c.objects[o.Hash()] = o
	c.order.Push(o.Hash())
	c.actualSize += o.Size()
}

// Get returns an object by his hash. If the object is not found in the cache, it
// returns nil
func (c *ObjectFIFO) Get(k plumbing.Hash) plumbing.EncodedObject {
	return c.objects[k]
}

// Clear the content of this object cache
func (c *ObjectFIFO) Clear() {
	c.objects = make(map[plumbing.Hash]plumbing.EncodedObject)
	c.order = newQueue(initialQueueSize)
	c.actualSize = 0
}