cache.go 789 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package trie
  2. type Backend interface {
  3. Get([]byte) ([]byte, error)
  4. Put([]byte, []byte)
  5. }
  6. type Cache struct {
  7. store map[string][]byte
  8. backend Backend
  9. }
  10. func NewCache(backend Backend) *Cache {
  11. return &Cache{make(map[string][]byte), backend}
  12. }
  13. func (self *Cache) Get(key []byte) []byte {
  14. data := self.store[string(key)]
  15. if data == nil {
  16. data, _ = self.backend.Get(key)
  17. }
  18. return data
  19. }
  20. func (self *Cache) Put(key []byte, data []byte) {
  21. self.store[string(key)] = data
  22. }
  23. func (self *Cache) Flush() {
  24. for k, v := range self.store {
  25. self.backend.Put([]byte(k), v)
  26. }
  27. // This will eventually grow too large. We'd could
  28. // do a make limit on storage and push out not-so-popular nodes.
  29. //self.Reset()
  30. }
  31. func (self *Cache) Reset() {
  32. self.store = make(map[string][]byte)
  33. }