github.com/bingoohuang/gg@v0.0.0-20240325092523-45da7dee9335/pkg/ttlcache/options.go (about) 1 package ttlcache 2 3 import "time" 4 5 // Option sets a specific cache option. 6 type Option[K comparable, V any] interface { 7 apply(opts *options[K, V]) 8 } 9 10 // optionFunc wraps a function and implements the Option interface. 11 type optionFunc[K comparable, V any] func(*options[K, V]) 12 13 // apply calls the wrapped function. 14 func (fn optionFunc[K, V]) apply(opts *options[K, V]) { 15 fn(opts) 16 } 17 18 // options holds all available cache configuration options. 19 type options[K comparable, V any] struct { 20 capacity uint64 21 ttl time.Duration 22 loader Loader[K, V] 23 disableTouchOnHit bool 24 } 25 26 // applyOptions applies the provided option values to the option struct. 27 func applyOptions[K comparable, V any](v *options[K, V], opts ...Option[K, V]) { 28 for i := range opts { 29 opts[i].apply(v) 30 } 31 } 32 33 // WithCapacity sets the maximum capacity of the cache. 34 // It has no effect when passing into Get(). 35 func WithCapacity[K comparable, V any](c uint64) Option[K, V] { 36 return optionFunc[K, V](func(opts *options[K, V]) { 37 opts.capacity = c 38 }) 39 } 40 41 // WithTTL sets the TTL of the cache. 42 // It has no effect when passing into Get(). 43 func WithTTL[K comparable, V any](ttl time.Duration) Option[K, V] { 44 return optionFunc[K, V](func(opts *options[K, V]) { 45 opts.ttl = ttl 46 }) 47 } 48 49 // WithLoader sets the loader of the cache. 50 // When passing into Get(), it sets an epheral loader that 51 // is used instead of the cache's default one. 52 func WithLoader[K comparable, V any](l Loader[K, V]) Option[K, V] { 53 return optionFunc[K, V](func(opts *options[K, V]) { 54 opts.loader = l 55 }) 56 } 57 58 // WithDisableTouchOnHit prevents the cache instance from 59 // extending/touching an item's expiration timestamp when it is being 60 // retrieved. 61 // When passing into Get(), it overrides the default value of the 62 // cache. 63 func WithDisableTouchOnHit[K comparable, V any]() Option[K, V] { 64 return optionFunc[K, V](func(opts *options[K, V]) { 65 opts.disableTouchOnHit = true 66 }) 67 }