github.com/grailbio/base@v0.0.11/sync/loadingcache/ctxloadingcache/ctxloadingcache.go (about)

     1  package ctxloadingcache
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/grailbio/base/sync/loadingcache"
     7  )
     8  
     9  type contextKeyType struct{}
    10  
    11  var contextKey contextKeyType
    12  
    13  // With returns a child context which, when passed to Value, gets and sets in m.
    14  // Callers now control the lifetime of the returned context's cache and can clear it.
    15  func With(ctx context.Context, m *loadingcache.Map) context.Context {
    16  	return context.WithValue(ctx, contextKey, m)
    17  }
    18  
    19  // Value retrieves a *loadingcache.Value that's linked to a cache, if ctx was returned by With.
    20  // If ctx didn't come from an earlier With call, there's no linked cache, so caching will be
    21  // disabled by returning nil (which callers don't need to check, because nil is usable).
    22  func Value(ctx context.Context, key interface{}) *loadingcache.Value {
    23  	var m *loadingcache.Map
    24  	if v := ctx.Value(contextKey); v != nil {
    25  		m = v.(*loadingcache.Map)
    26  	}
    27  	return m.GetOrCreate(key)
    28  }