github.com/gitbundle/modules@v0.0.0-20231025071548-85b91c5c3b01/regexplru/regexplru.go (about) 1 // Copyright 2023 The GitBundle Inc. All rights reserved. 2 // Copyright 2017 The Gitea Authors. All rights reserved. 3 // Use of this source code is governed by a MIT-style 4 // license that can be found in the LICENSE file. 5 6 package regexplru 7 8 import ( 9 "regexp" 10 11 "github.com/gitbundle/modules/log" 12 13 lru "github.com/hashicorp/golang-lru" 14 ) 15 16 var lruCache *lru.Cache 17 18 func init() { 19 var err error 20 lruCache, err = lru.New(1000) 21 if err != nil { 22 log.Fatal("failed to new LRU cache, err: %v", err) 23 } 24 } 25 26 // GetCompiled works like regexp.Compile, the compiled expr or error is stored in LRU cache 27 func GetCompiled(expr string) (r *regexp.Regexp, err error) { 28 v, ok := lruCache.Get(expr) 29 if !ok { 30 r, err = regexp.Compile(expr) 31 if err != nil { 32 lruCache.Add(expr, err) 33 return nil, err 34 } 35 lruCache.Add(expr, r) 36 } else { 37 r, ok = v.(*regexp.Regexp) 38 if !ok { 39 if err, ok = v.(error); ok { 40 return nil, err 41 } 42 panic("impossible") 43 } 44 } 45 return r, nil 46 }