package lrure

import "git.sr.ht/~jamesponddotco/recache-go/lrure"

Package lrure implements a thread-safe LRU cache for Go's standard regex package that complies with the recache.Cache interface.

Index

Examples

Types

type Cache

type Cache struct {
	// contains filtered or unexported fields
}

Cache is a thread-safe LRU cache for Go's standard regex package.

func New

func New(capacity int) *Cache

New returns a new LRU cache with the given capacity.

If capacity is less than 1, recache.DefaultCapacity is used instead.

func (*Cache) Capacity

func (c *Cache) Capacity() int

Capacity returns the maximum number of regular expressions that can be stored in the cache.

func (*Cache) Clear

func (c *Cache) Clear()

Clear removes all regular expressions from the cache.

func (*Cache) Get

func (c *Cache) Get(_ context.Context, pattern string, flag recache.Flag) (*regexp.Regexp, error)

Get returns a compiled regular expression from the cache given a pattern and an optional flag.

If the regular expression is not in the cache, it is compiled and added to it.

Example

Code:

{
	// Create a new Cache instance with the default cache capacity.
	cache := lrure.New(recache.DefaultCapacity)

	// Add the regular expression to the cache for the first time, which will
	// cause it to be compiled.
	regex, err := cache.Get(context.Background(), "p([a-z]+)ch", recache.DefaultFlag)
	if err != nil {
		log.Fatal(err)
	}

	// Match the string against the regular expression.
	fmt.Println(regex.MatchString("peach"))

	// Get the regular expression, which by now has been compiled and returns
	// super fast, without the need for recompilation.
	sameRegex, err := cache.Get(context.Background(), "p([a-z]+)ch", recache.DefaultFlag)
	if err != nil {
		log.Fatal(err)
	}

	// Match the string against the regular expression.
	fmt.Println(sameRegex.MatchString("peach"))

	// Output:
	// true
	// true
}

Output:

true
true

func (*Cache) SetCapacity

func (c *Cache) SetCapacity(capacity int) error

SetCapacity sets the maximum number of regular expressions that can be stored in the cache.

func (*Cache) Size

func (c *Cache) Size() int

Size returns the number of regular expressions currently stored in the cache.

Source Files

lrure.go

Version
v1.0.1 (latest)
Published
Apr 1, 2023
Platform
linux/amd64
Imports
6 packages
Last checked
6 days ago

Tools for package owners.