github.com/fufuok/freelru@v0.13.3/helper.go (about)

     1  package freelru
     2  
     3  import (
     4  	"time"
     5  )
     6  
     7  // NewDefault constructs an LRU with the given capacity of elements.
     8  // The hash function calculates a hash value from the keys.
     9  func NewDefault[K comparable, V any](capacity uint32, lifetime ...time.Duration) (*LRU[K, V], error) {
    10  	return NewWithSizeDefault[K, V](capacity, capacity, lifetime...)
    11  }
    12  
    13  // NewWithSizeDefault constructs an LRU with the given capacity and size.
    14  // The hash function calculates a hash value from the keys.
    15  // A size greater than the capacity increases memory consumption and decreases the CPU consumption
    16  // by reducing the chance of collisions.
    17  // Size must not be lower than the capacity.
    18  func NewWithSizeDefault[K comparable, V any](capacity, size uint32, lifetime ...time.Duration) (*LRU[K, V], error) {
    19  	c, err := NewWithSize[K, V](capacity, size, MakeHasher[K]())
    20  	if err != nil {
    21  		return nil, err
    22  	}
    23  	if len(lifetime) > 0 && lifetime[0] > 0 {
    24  		c.SetLifetime(lifetime[0])
    25  	}
    26  	return c, err
    27  }
    28  
    29  // NewSyncedDefault creates a new thread-safe LRU hashmap with the given capacity.
    30  func NewSyncedDefault[K comparable, V any](capacity uint32, lifetime ...time.Duration) (*SyncedLRU[K, V], error) {
    31  	return NewSyncedWithSizeDefault[K, V](capacity, capacity, lifetime...)
    32  }
    33  
    34  func NewSyncedWithSizeDefault[K comparable, V any](capacity, size uint32, lifetime ...time.Duration) (
    35  	*SyncedLRU[K, V], error,
    36  ) {
    37  	c, err := NewSyncedWithSize[K, V](capacity, size, MakeHasher[K]())
    38  	if err != nil {
    39  		return nil, err
    40  	}
    41  	if len(lifetime) > 0 && lifetime[0] > 0 {
    42  		c.SetLifetime(lifetime[0])
    43  	}
    44  	return c, err
    45  }
    46  
    47  // NewShardedDefault creates a new thread-safe sharded LRU hashmap with the given capacity.
    48  func NewShardedDefault[K comparable, V any](capacity uint32, lifetime ...time.Duration) (*ShardedLRU[K, V], error) {
    49  	c, err := NewSharded[K, V](capacity, MakeHasher[K]())
    50  	if err != nil {
    51  		return nil, err
    52  	}
    53  	if len(lifetime) > 0 && lifetime[0] > 0 {
    54  		c.SetLifetime(lifetime[0])
    55  	}
    56  	return c, err
    57  }
    58  
    59  func NewShardedWithSizeDefault[K comparable, V any](shards, capacity, size uint32, lifetime ...time.Duration) (
    60  	*ShardedLRU[K, V], error,
    61  ) {
    62  	c, err := NewShardedWithSize[K, V](shards, capacity, size, MakeHasher[K]())
    63  	if err != nil {
    64  		return nil, err
    65  	}
    66  	if len(lifetime) > 0 && lifetime[0] > 0 {
    67  		c.SetLifetime(lifetime[0])
    68  	}
    69  	return c, err
    70  }