diff options
author | Máximo Cuadros <mcuadros@gmail.com> | 2017-02-21 16:08:57 +0100 |
---|---|---|
committer | GitHub <noreply@github.com> | 2017-02-21 16:08:57 +0100 |
commit | e26a605c93d8085dfff8e440838fd3c43b63cff6 (patch) | |
tree | 7022e74d0fa7a3ab542eaa2df851e7f625e8f1ff /plumbing/cache/object.go | |
parent | 73855d0a5f617bcda1f33e730f3bc7cf8afbef6c (diff) | |
parent | 6e15f9cb0dbac68992eb242282e725784fe72b32 (diff) | |
download | go-git-e26a605c93d8085dfff8e440838fd3c43b63cff6.tar.gz |
Merge pull request #278 from ajnavarro/improvement/move-cache-to-plumbing
cache: move package to plumbing
Diffstat (limited to 'plumbing/cache/object.go')
-rw-r--r-- | plumbing/cache/object.go | 68 |
1 files changed, 68 insertions, 0 deletions
diff --git a/plumbing/cache/object.go b/plumbing/cache/object.go new file mode 100644 index 0000000..47e390b --- /dev/null +++ b/plumbing/cache/object.go @@ -0,0 +1,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 +} |