Skip to content
/ xmap Public

A generic and thread-safe Go map with automatic key expiration.

License

Notifications You must be signed in to change notification settings

mdawar/xmap

Repository files navigation

xmap

Go Reference Go Report Card Go Tests

A generic and thread-safe Go map with automatic key expiration.

Installation

go get -u github.com/mdawar/xmap

Usage

New Map

// Create a map with the default configuration.
m := xmap.New[string, int]()
// Stop the cleanup goroutine and clear the map.
defer m.Stop()

Create

// Create new entries in the map.
m.Set("a", 1, time.Minute) // Key that expires in 1 minute.
m.Set("b", 2, 0)           // Key that never expires (0 TTL).

// Replace a key.
m.Set("a", 3, time.Hour) // Replace key (New value and expiration time).

Update

// Update the value without changing the expiration time.
// Reports whether the key was updated (Key exists).
ok := m.Update("b", 4)

Get

// Get the value if the key exists and has not expired.
// The second return value reports whether the key exists.
value, ok := m.Get("a")

// Get the value with the expiration time.
// The third return value reports whether the key exists.
value, expiration, ok := m.GetWithExpiration("a")
// If the key never expires, it will have a zero expiration time value.
neverExpires := expiration.IsZero()

Delete

// Delete a key from the map.
m.Delete("a")

// Delete all the keys from the map.
m.Clear()

Length

total := m.Len()

Iteration

for key, value := range m.All() {
	fmt.Println("Key:", key, "-", "Value:", value)
}

Remove Expired Keys

// Expired keys are automatically removed at regular intervals.
// Additionally, the removal of expired keys can be manually triggered.
removed := m.RemoveExpired() // Returns the number of removed keys.

Configuration

Name Type Description
CleanupInterval time.Duration Interval at which expired keys are removed (Default: 5 minutes).
InitialCapacity int Initial map capacity hint (Passed to make()).
TimeSource xmap.Time Custom time source (Useful for testing).

Example:

package xmap

import (
	"time"

	"github.com/mdawar/xmap"
)

func main() {
	m := xmap.NewWithConfig[string, int](xmap.Config{
		CleanupInterval: 10 * time.Minute,
		InitialCapacity: 10_000_000,
		TimeSource:      mockTime,
	})
	defer m.Stop()
}

Tests

make test

Or:

go test -cover -race

Benchmarks

make benchmark

Or:

go test -bench .

About

A generic and thread-safe Go map with automatic key expiration.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published