all repos — honk @ b188b09e95c9661ba24bc99d0f92983b9ad0be90

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(filler cacheFiller) *Cache {
32	c := new(Cache)
33	c.cache = make(map[interface{}]interface{})
34	c.filler = filler
35	return c
36}
37
38func (cache *Cache) Get(key interface{}, value interface{}) bool {
39	cache.lock.Lock()
40	defer cache.lock.Unlock()
41	v, ok := cache.cache[key]
42	if !ok {
43		v, ok = cache.filler(key)
44		if ok {
45			cache.cache[key] = v
46		}
47	}
48	if ok {
49		ptr := reflect.ValueOf(v)
50		reflect.ValueOf(value).Elem().Set(ptr)
51	}
52	return ok
53}
54
55func (cache *Cache) Clear(key interface{}) {
56	cache.lock.Lock()
57	defer cache.lock.Unlock()
58	delete(cache.cache, key)
59}
60
61func (cache *Cache) Flush() {
62	cache.lock.Lock()
63	defer cache.lock.Unlock()
64	cache.cache = make(map[interface{}]interface{})
65}