go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/logdog/common/storage/memory/cache.go (about)

     1  // Copyright 2016 The LUCI Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package memory
    16  
    17  import (
    18  	"context"
    19  	"sync"
    20  	"time"
    21  
    22  	"go.chromium.org/luci/logdog/common/storage"
    23  )
    24  
    25  // Cache is an in-memory storage.Cache implementation.
    26  type Cache struct {
    27  	mu       sync.Mutex
    28  	cacheMap map[storage.CacheKey][]byte
    29  }
    30  
    31  var _ storage.Cache = (*Cache)(nil)
    32  
    33  // Put implements storage.Cache.
    34  func (c *Cache) Put(ctx context.Context, key storage.CacheKey, val []byte, exp time.Duration) {
    35  	c.mu.Lock()
    36  	defer c.mu.Unlock()
    37  
    38  	if c.cacheMap == nil {
    39  		c.cacheMap = make(map[storage.CacheKey][]byte)
    40  	}
    41  
    42  	c.cacheMap[key] = val
    43  }
    44  
    45  // Get implements storage.Cache.
    46  func (c *Cache) Get(ctx context.Context, key storage.CacheKey) ([]byte, bool) {
    47  	c.mu.Lock()
    48  	defer c.mu.Unlock()
    49  
    50  	v, ok := c.cacheMap[key]
    51  	return v, ok
    52  }