all repos — honk @ 0b202b6dc5ab3483f94f4c9e97e2de1dd082eb37

my fork of honk

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