Skip to content

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

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/mdawar/xmap"
)

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

	// 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 the value without changing the expiration time.
	// Reports whether the key was updated (Key exists).
	ok := m.Update("b", 4)

	// 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()

	// Length of the map.
	total := m.Len()

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

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

	// 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.

	// Iterate over the map entries.
	for entry := range m.Entries(context.TODO()) {
		fmt.Println("Key:", entry.Key, "-", "Value:", entry.Value)
	}
}

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