cache.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 (
  8. "time"
  9. "github.com/syncthing/syncthing/lib/ignore/ignoreresult"
  10. )
  11. type nower interface {
  12. Now() time.Time
  13. }
  14. var clock = nower(defaultClock{})
  15. type cache struct {
  16. entries map[string]cacheEntry
  17. }
  18. type cacheEntry struct {
  19. result ignoreresult.R
  20. access int64 // Unix nanosecond count. Sufficient until the year 2262.
  21. }
  22. func newCache() *cache {
  23. return &cache{
  24. entries: make(map[string]cacheEntry),
  25. }
  26. }
  27. func (c *cache) clean(d time.Duration) {
  28. for k, v := range c.entries {
  29. if clock.Now().Sub(time.Unix(0, v.access)) > d {
  30. delete(c.entries, k)
  31. }
  32. }
  33. }
  34. func (c *cache) get(key string) (ignoreresult.R, bool) {
  35. entry, ok := c.entries[key]
  36. if ok {
  37. entry.access = clock.Now().UnixNano()
  38. c.entries[key] = entry
  39. }
  40. return entry.result, ok
  41. }
  42. func (c *cache) set(key string, result ignoreresult.R) {
  43. c.entries[key] = cacheEntry{result, time.Now().UnixNano()}
  44. }
  45. func (c *cache) len() int {
  46. l := len(c.entries)
  47. return l
  48. }
  49. type defaultClock struct{}
  50. func (defaultClock) Now() time.Time {
  51. return time.Now()
  52. }