github.com/shogo82148/std@v1.22.1-0.20240327122250-4e474527810c/crypto/internal/boring/bcache/cache.go (about)

     1  // Copyright 2022 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package bcache implements a GC-friendly cache (see [Cache]) for BoringCrypto.
     6  package bcache
     7  
     8  import (
     9  	"github.com/shogo82148/std/sync/atomic"
    10  )
    11  
    12  // A Cache is a GC-friendly concurrent map from unsafe.Pointer to
    13  // unsafe.Pointer. It is meant to be used for maintaining shadow
    14  // BoringCrypto state associated with certain allocated structs, in
    15  // particular public and private RSA and ECDSA keys.
    16  //
    17  // The cache is GC-friendly in the sense that the keys do not
    18  // indefinitely prevent the garbage collector from collecting them.
    19  // Instead, at the start of each GC, the cache is cleared entirely. That
    20  // is, the cache is lossy, and the loss happens at the start of each GC.
    21  // This means that clients need to be able to cope with cache entries
    22  // disappearing, but it also means that clients don't need to worry about
    23  // cache entries keeping the keys from being collected.
    24  type Cache[K, V any] struct {
    25  	// The runtime atomically stores nil to ptable at the start of each GC.
    26  	ptable atomic.Pointer[cacheTable[K, V]]
    27  }
    28  
    29  // Register registers the cache with the runtime,
    30  // so that c.ptable can be cleared at the start of each GC.
    31  // Register must be called during package initialization.
    32  func (c *Cache[K, V]) Register()
    33  
    34  // Clear clears the cache.
    35  // The runtime does this automatically at each garbage collection;
    36  // this method is exposed only for testing.
    37  func (c *Cache[K, V]) Clear()
    38  
    39  // Get returns the cached value associated with v,
    40  // which is either the value v corresponding to the most recent call to Put(k, v)
    41  // or nil if that cache entry has been dropped.
    42  func (c *Cache[K, V]) Get(k *K) *V
    43  
    44  // Put sets the cached value associated with k to v.
    45  func (c *Cache[K, V]) Put(k *K, v *V)