Some checks failed
cache-seeder / prune (push) Has been skipped
cache-seeder / frontend (push) Failing after 3s
cache-seeder / python (push) Failing after 3s
cache-seeder / gobuild (push) Failing after 4s
cache-seeder / lint (bindata, lint-backend) (push) Failing after 3s
giteabot backport / giteabot (push) Has been skipped
giteabot / giteabot (push) Has been skipped
cache-prune / prune (push) Has been skipped
release-nightly-snapcraft / build-and-publish (ubuntu-24.04) (push) Has been cancelled
release-nightly-snapcraft / build-and-publish (ubuntu-24.04-arm) (push) Has been cancelled
release-nightly / nightly-binary (push) Has been cancelled
release-nightly / nightly-container (push) Has been cancelled
cron-renovate / cron-renovate (push) Has been skipped
42 lines
980 B
Go
42 lines
980 B
Go
// Copyright 2022 The Gitea Authors. All rights reserved.
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
package regexplru
|
|
|
|
import (
|
|
"regexp"
|
|
"sync"
|
|
|
|
lru "github.com/hashicorp/golang-lru/v2"
|
|
)
|
|
|
|
type lruItem struct {
|
|
regexp *regexp.Regexp
|
|
err error
|
|
}
|
|
|
|
type RegexpCache struct {
|
|
lruCache *lru.Cache[string, *lruItem]
|
|
}
|
|
|
|
func NewCache(size int) *RegexpCache {
|
|
lruCache, _ := lru.New[string, *lruItem](size)
|
|
return &RegexpCache{lruCache: lruCache}
|
|
}
|
|
|
|
// GetCompiled works like regexp.Compile, the compiled expr or error is stored in LRU cache
|
|
func (regexpCache *RegexpCache) GetCompiled(expr string) (r *regexp.Regexp, err error) {
|
|
v, ok := regexpCache.lruCache.Get(expr)
|
|
if !ok {
|
|
r, err = regexp.Compile(expr)
|
|
regexpCache.lruCache.Add(expr, &lruItem{regexp: r, err: err})
|
|
return r, err
|
|
}
|
|
return v.regexp, v.err
|
|
}
|
|
|
|
var (
|
|
UserCache = sync.OnceValue(func() *RegexpCache { return NewCache(1000) })
|
|
SystemCache = sync.OnceValue(func() *RegexpCache { return NewCache(1000) })
|
|
)
|