expset

package module
v0.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 25, 2025 License: Apache-2.0 Imports: 4 Imported by: 0

README

Expiring Set

A generic set with time based eviction.

Go Reference License Go Report Card Go Coverage

This set uses generics to contain any type of comparable element, evicting elements after a given expiration period.

Usage

Create and start the set then add some items with time to live

import "github.com/logbn/expset"

s := expset.New[string]()
s.Start()
defer s.Stop()

s.Add("test-1", 10 * time.Second)
s.Add("test-2", 20 * time.Second)
s.Add("test-3", 30 * time.Second)

println(s.Len())
// output:
//   3

Test whether set Has a value

println(s.Has("test-1"))
// output:
//   true

println(s.Has("test-2"))
// output:
//   true

Observe expiration

time.Sleep(10*time.Second)

println(s.Has("test-1"))
// output:
//   false

println(s.Has("test-2"))
// output:
//   true

Refresh an item to reset its expiration

s.Refresh("test-2")

time.Sleep(10*time.Second)

println(s.Has("test-2"))
// output:
//   true

Concurrency

This package is thread safe.

License

Expiring Set is licensed under Apache 2.0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Set

type Set[T comparable] struct {
	// contains filtered or unexported fields
}

Set implements a generic expiring set.

func New

func New[T comparable]() *Set[T]

New returns a new [Cache].

func (*Set[T]) Add

func (c *Set[T]) Add(val T, ttl time.Duration)

Add adds an item to the set with a given time to live.

func (*Set[T]) Clear

func (c *Set[T]) Clear()

Clear clears the set.

func (*Set[T]) Has

func (c *Set[T]) Has(val T) bool

Has indicates whether the set contains a value.

func (*Set[T]) Len

func (c *Set[T]) Len() int

Len returns the number of items in the set.

func (*Set[T]) Refresh

func (c *Set[T]) Refresh(val T) bool

Refresh refreshes the expiration based on the original TTL

func (*Set[T]) Start

func (c *Set[T]) Start()

Start begins the eviction process.

func (*Set[T]) Stop

func (c *Set[T]) Stop()

Stop stops the eviction process.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL