2014-12-02 22:13:03 +00:00
|
|
|
// Copyright (C) 2014 The Syncthing Authors.
|
|
|
|
//
|
2015-03-07 20:36:35 +00:00
|
|
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
|
|
|
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
|
2017-02-09 06:52:18 +00:00
|
|
|
// You can obtain one at https://mozilla.org/MPL/2.0/.
|
2014-12-02 22:13:03 +00:00
|
|
|
|
|
|
|
package ignore
|
|
|
|
|
2014-12-23 09:05:08 +00:00
|
|
|
import "time"
|
2014-12-02 22:13:03 +00:00
|
|
|
|
2017-06-11 10:27:12 +00:00
|
|
|
type nower interface {
|
|
|
|
Now() time.Time
|
|
|
|
}
|
|
|
|
|
|
|
|
var clock = nower(defaultClock{})
|
|
|
|
|
2014-12-02 22:13:03 +00:00
|
|
|
type cache struct {
|
|
|
|
patterns []Pattern
|
|
|
|
entries map[string]cacheEntry
|
|
|
|
}
|
|
|
|
|
|
|
|
type cacheEntry struct {
|
2016-04-07 09:34:07 +00:00
|
|
|
result Result
|
2021-02-04 17:39:06 +00:00
|
|
|
access int64 // Unix nanosecond count. Sufficient until the year 2262.
|
2014-12-02 22:13:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func newCache(patterns []Pattern) *cache {
|
|
|
|
return &cache{
|
|
|
|
patterns: patterns,
|
|
|
|
entries: make(map[string]cacheEntry),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *cache) clean(d time.Duration) {
|
|
|
|
for k, v := range c.entries {
|
2021-02-04 17:39:06 +00:00
|
|
|
if clock.Now().Sub(time.Unix(0, v.access)) > d {
|
2014-12-02 22:13:03 +00:00
|
|
|
delete(c.entries, k)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-04-07 09:34:07 +00:00
|
|
|
func (c *cache) get(key string) (Result, bool) {
|
|
|
|
entry, ok := c.entries[key]
|
2014-12-02 22:13:03 +00:00
|
|
|
if ok {
|
2021-02-04 17:39:06 +00:00
|
|
|
entry.access = clock.Now().UnixNano()
|
2016-04-07 09:34:07 +00:00
|
|
|
c.entries[key] = entry
|
2014-12-02 22:13:03 +00:00
|
|
|
}
|
2016-04-07 09:34:07 +00:00
|
|
|
return entry.result, ok
|
2014-12-02 22:13:03 +00:00
|
|
|
}
|
|
|
|
|
2016-04-07 09:34:07 +00:00
|
|
|
func (c *cache) set(key string, result Result) {
|
2021-02-04 17:39:06 +00:00
|
|
|
c.entries[key] = cacheEntry{result, time.Now().UnixNano()}
|
2014-12-02 22:13:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (c *cache) len() int {
|
|
|
|
l := len(c.entries)
|
|
|
|
return l
|
|
|
|
}
|
2017-06-11 10:27:12 +00:00
|
|
|
|
|
|
|
type defaultClock struct{}
|
|
|
|
|
|
|
|
func (defaultClock) Now() time.Time {
|
|
|
|
return time.Now()
|
|
|
|
}
|