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)
22
23type cacheFiller func(key interface{}) (interface{}, bool)
24
25type cacheOptions struct {
26 Filler interface{}
27}
28
29type Cache struct {
30 cache map[interface{}]interface{}
31 filler cacheFiller
32 lock sync.Mutex
33}
34
35func cacheNew(options cacheOptions) *Cache {
36 c := new(Cache)
37 c.cache = make(map[interface{}]interface{})
38 fillfn := options.Filler
39 ftype := reflect.TypeOf(fillfn)
40 if ftype.Kind() != reflect.Func {
41 panic("cache filler is not function")
42 }
43 if ftype.NumIn() != 1 || ftype.NumOut() != 2 {
44 panic("cache filler has wrong argument count")
45 }
46 c.filler = func(key interface{}) (interface{}, bool) {
47 vfn := reflect.ValueOf(fillfn)
48 args := []reflect.Value{reflect.ValueOf(key)}
49 rv := vfn.Call(args)
50 return rv[0].Interface(), rv[1].Bool()
51 }
52 return c
53}
54
55func (cache *Cache) Get(key interface{}, value interface{}) bool {
56 cache.lock.Lock()
57 defer cache.lock.Unlock()
58 v, ok := cache.cache[key]
59 if !ok {
60 v, ok = cache.filler(key)
61 if ok {
62 cache.cache[key] = v
63 }
64 }
65 if ok {
66 ptr := reflect.ValueOf(v)
67 reflect.ValueOf(value).Elem().Set(ptr)
68 }
69 return ok
70}
71
72func (cache *Cache) Clear(key interface{}) {
73 cache.lock.Lock()
74 defer cache.lock.Unlock()
75 delete(cache.cache, key)
76}
77
78func (cache *Cache) Flush() {
79 cache.lock.Lock()
80 defer cache.lock.Unlock()
81 cache.cache = make(map[interface{}]interface{})
82}