aboutsummaryrefslogtreecommitdiffstats
path: root/lib/parse/match.go
diff options
context:
space:
mode:
authorRobin Jarry <robin@jarry.cc>2023-03-04 01:12:23 +0100
committerRobin Jarry <robin@jarry.cc>2023-03-08 00:43:02 +0100
commit56a6ed0cf71ecf55f37e94b574c41927452abc44 (patch)
tree9d18955520db78247b1a62a8d79121b0b63974ce /lib/parse/match.go
parent573b3266afcf6dc52c82ffa238f5d9b82ee11cf7 (diff)
downloadaerc-56a6ed0cf71ecf55f37e94b574c41927452abc44.tar.gz
templates: add match function
Add a match function that returns true if a string matches the provided regular expression. The compiled regular expressions are cached in a sync.Map to avoid repetitive compilations of the same expressions. Caveat: if the user mixes the arguments order, it may cause the cache to consume a lot of memory filled with garbage regular expression objects. Ideally, we would need to limit the size of this cache and/or use a LRU cache implementation. Maybe someday? Signed-off-by: Robin Jarry <robin@jarry.cc> Acked-by: Tim Culverhouse <tim@timculverhouse.com>
Diffstat (limited to 'lib/parse/match.go')
-rw-r--r--lib/parse/match.go30
1 files changed, 30 insertions, 0 deletions
diff --git a/lib/parse/match.go b/lib/parse/match.go
new file mode 100644
index 00000000..ac43673e
--- /dev/null
+++ b/lib/parse/match.go
@@ -0,0 +1,30 @@
+package parse
+
+import (
+ "regexp"
+ "sync"
+
+ "git.sr.ht/~rjarry/aerc/log"
+)
+
+var reCache sync.Map
+
+// Check if a string matches the specified regular expression.
+// The regexp is compiled only once and stored in a cache for future use.
+func MatchCache(s, expr string) bool {
+ var re interface{}
+ var found bool
+
+ if re, found = reCache.Load(expr); !found {
+ var err error
+ re, err = regexp.Compile(expr)
+ if err != nil {
+ log.Errorf("`%s` invalid regexp: %s", expr, err)
+ }
+ reCache.Store(expr, re)
+ }
+ if re, ok := re.(*regexp.Regexp); ok && re != nil {
+ return re.MatchString(s)
+ }
+ return false
+}