cache.go (view raw)
1//
2// Copyright (c) 2019 Ted Unangst <tedu@tedunangst.com>
3//
4// Permission to use, copy, modify, and distribute this software for any
5// purpose with or without fee is hereby granted, provided that the above
6// copyright notice and this permission notice appear in all copies.
7//
8// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15
16package main
17
18import (
19 "reflect"
20 "sync"
21 "time"
22)
23
24type cacheFiller func(key interface{}) (interface{}, bool)
25
26type cacheOptions struct {
27 Filler interface{}
28 Duration time.Duration
29}
30
31type Cache struct {
32 cache map[interface{}]interface{}
33 filler cacheFiller
34 lock sync.Mutex
35 stale time.Time
36 duration time.Duration
37}
38
39func cacheNew(options cacheOptions) *Cache {
40 c := new(Cache)
41 c.cache = make(map[interface{}]interface{})
42 fillfn := options.Filler
43 ftype := reflect.TypeOf(fillfn)
44 if ftype.Kind() != reflect.Func {
45 panic("cache filler is not function")
46 }
47 if ftype.NumIn() != 1 || ftype.NumOut() != 2 {
48 panic("cache filler has wrong argument count")
49 }
50 c.filler = func(key interface{}) (interface{}, bool) {
51 vfn := reflect.ValueOf(fillfn)
52 args := []reflect.Value{reflect.ValueOf(key)}
53 rv := vfn.Call(args)
54 return rv[0].Interface(), rv[1].Bool()
55 }
56 if options.Duration != 0 {
57 c.duration = options.Duration
58 c.stale = time.Now().Add(c.duration)
59 }
60 return c
61}
62
63func (cache *Cache) Get(key interface{}, value interface{}) bool {
64 cache.lock.Lock()
65 defer cache.lock.Unlock()
66 if !cache.stale.IsZero() && cache.stale.Before(time.Now()) {
67 cache.stale = time.Now().Add(cache.duration)
68 cache.cache = make(map[interface{}]interface{})
69 }
70 v, ok := cache.cache[key]
71 if !ok {
72 v, ok = cache.filler(key)
73 if ok {
74 cache.cache[key] = v
75 }
76 }
77 if ok {
78 ptr := reflect.ValueOf(v)
79 reflect.ValueOf(value).Elem().Set(ptr)
80 }
81 return ok
82}
83
84func (cache *Cache) Clear(key interface{}) {
85 cache.lock.Lock()
86 defer cache.lock.Unlock()
87 delete(cache.cache, key)
88}
89
90func (cache *Cache) Flush() {
91 cache.lock.Lock()
92 defer cache.lock.Unlock()
93 cache.cache = make(map[interface{}]interface{})
94}