cache.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This program is free software: you can redistribute it and/or modify it
  4. // under the terms of the GNU General Public License as published by the Free
  5. // Software Foundation, either version 3 of the License, or (at your option)
  6. // any later version.
  7. //
  8. // This program is distributed in the hope that it will be useful, but WITHOUT
  9. // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  10. // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  11. // more details.
  12. //
  13. // You should have received a copy of the GNU General Public License along
  14. // with this program. If not, see <http://www.gnu.org/licenses/>.
  15. package ignore
  16. import (
  17. "sync"
  18. "time"
  19. )
  20. var (
  21. caches = make(map[string]*cache)
  22. cacheMut sync.Mutex
  23. )
  24. func init() {
  25. // Periodically go through the cache and remove cache entries that have
  26. // not been touched in the last two hours.
  27. go cleanIgnoreCaches(2 * time.Hour)
  28. }
  29. type cache struct {
  30. patterns []Pattern
  31. entries map[string]cacheEntry
  32. mut sync.Mutex
  33. }
  34. type cacheEntry struct {
  35. value bool
  36. access time.Time
  37. }
  38. func newCache(patterns []Pattern) *cache {
  39. return &cache{
  40. patterns: patterns,
  41. entries: make(map[string]cacheEntry),
  42. }
  43. }
  44. func (c *cache) clean(d time.Duration) {
  45. c.mut.Lock()
  46. for k, v := range c.entries {
  47. if time.Since(v.access) > d {
  48. delete(c.entries, k)
  49. }
  50. }
  51. c.mut.Unlock()
  52. }
  53. func (c *cache) get(key string) (result, ok bool) {
  54. c.mut.Lock()
  55. res, ok := c.entries[key]
  56. if ok {
  57. res.access = time.Now()
  58. c.entries[key] = res
  59. }
  60. c.mut.Unlock()
  61. return res.value, ok
  62. }
  63. func (c *cache) set(key string, val bool) {
  64. c.mut.Lock()
  65. c.entries[key] = cacheEntry{val, time.Now()}
  66. c.mut.Unlock()
  67. }
  68. func (c *cache) len() int {
  69. c.mut.Lock()
  70. l := len(c.entries)
  71. c.mut.Unlock()
  72. return l
  73. }
  74. func cleanIgnoreCaches(dur time.Duration) {
  75. for {
  76. time.Sleep(dur)
  77. cacheMut.Lock()
  78. for _, v := range caches {
  79. v.clean(dur)
  80. }
  81. cacheMut.Unlock()
  82. }
  83. }