cache.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package ignore
  7. import "time"
  8. type nower interface {
  9. Now() time.Time
  10. }
  11. var clock = nower(defaultClock{})
  12. type cache struct {
  13. patterns []Pattern
  14. entries map[string]cacheEntry
  15. }
  16. type cacheEntry struct {
  17. result Result
  18. access time.Time
  19. }
  20. func newCache(patterns []Pattern) *cache {
  21. return &cache{
  22. patterns: patterns,
  23. entries: make(map[string]cacheEntry),
  24. }
  25. }
  26. func (c *cache) clean(d time.Duration) {
  27. for k, v := range c.entries {
  28. if clock.Now().Sub(v.access) > d {
  29. delete(c.entries, k)
  30. }
  31. }
  32. }
  33. func (c *cache) get(key string) (Result, bool) {
  34. entry, ok := c.entries[key]
  35. if ok {
  36. entry.access = clock.Now()
  37. c.entries[key] = entry
  38. }
  39. return entry.result, ok
  40. }
  41. func (c *cache) set(key string, result Result) {
  42. c.entries[key] = cacheEntry{result, time.Now()}
  43. }
  44. func (c *cache) len() int {
  45. l := len(c.entries)
  46. return l
  47. }
  48. type defaultClock struct{}
  49. func (defaultClock) Now() time.Time {
  50. return time.Now()
  51. }