-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathcache.go
35 lines (30 loc) · 876 Bytes
/
cache.go
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
package memoria
import "fmt"
// implement here the different cache types here
type CachePolicy interface {
Eject(m *Memoria, requriedSpace uint64) error
Insert(m *Memoria, key string, val []byte) error
}
type defaultCachePolicy struct{}
func (dc *defaultCachePolicy) Eject(m *Memoria, requriedSpace uint64) error {
spaceFreed := uint64(0)
for key, val := range m.cache {
if spaceFreed >= requriedSpace {
break
}
valSize := uint64(len(val))
m.cacheSize -= valSize
delete(m.cache, key)
spaceFreed += valSize
}
return nil
}
func (dc *defaultCachePolicy) Insert(m *Memoria, key string, val []byte) error {
valueSize := uint64(len(val))
if m.cacheSize+valueSize > m.MaxCacheSize {
return fmt.Errorf("defaultCachePolicy: Failded to make room for value (%d/%d)", valueSize, m.MaxCacheSize)
}
m.cache[key] = val
m.cacheSize += valueSize
return nil
}