2020-10-08 15:06:42 +08:00
|
|
|
|
package utils
|
|
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
|
"fmt"
|
2022-01-08 11:45:14 +08:00
|
|
|
|
"github.com/TeaOSLab/EdgeNode/internal/re"
|
2020-11-21 21:43:03 +08:00
|
|
|
|
"github.com/TeaOSLab/EdgeNode/internal/ttlcache"
|
2020-11-21 22:29:57 +08:00
|
|
|
|
"github.com/cespare/xxhash"
|
2020-11-21 21:43:03 +08:00
|
|
|
|
"github.com/iwind/TeaGo/types"
|
2020-10-08 15:06:42 +08:00
|
|
|
|
"strconv"
|
2020-11-21 21:43:03 +08:00
|
|
|
|
"time"
|
2020-10-08 15:06:42 +08:00
|
|
|
|
)
|
|
|
|
|
|
|
2020-11-21 21:43:03 +08:00
|
|
|
|
var cache = ttlcache.NewCache()
|
2020-10-08 15:06:42 +08:00
|
|
|
|
|
2022-01-08 11:45:14 +08:00
|
|
|
|
// MatchStringCache 正则表达式匹配字符串,并缓存结果
|
|
|
|
|
|
func MatchStringCache(regex *re.Regexp, s string) bool {
|
2020-10-08 15:06:42 +08:00
|
|
|
|
// 如果长度超过4096,大概率是不能重用的
|
|
|
|
|
|
if len(s) > 4096 {
|
|
|
|
|
|
return regex.MatchString(s)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2020-11-21 22:29:57 +08:00
|
|
|
|
hash := xxhash.Sum64String(s)
|
2020-11-21 21:43:03 +08:00
|
|
|
|
key := fmt.Sprintf("%p_", regex) + strconv.FormatUint(hash, 10)
|
|
|
|
|
|
item := cache.Read(key)
|
2020-10-08 15:06:42 +08:00
|
|
|
|
if item != nil {
|
2020-11-21 21:43:03 +08:00
|
|
|
|
return types.Int8(item.Value) == 1
|
2020-10-08 15:06:42 +08:00
|
|
|
|
}
|
|
|
|
|
|
b := regex.MatchString(s)
|
|
|
|
|
|
if b {
|
2020-11-21 21:43:03 +08:00
|
|
|
|
cache.Write(key, 1, time.Now().Unix()+1800)
|
2020-10-08 15:06:42 +08:00
|
|
|
|
} else {
|
2020-11-21 21:43:03 +08:00
|
|
|
|
cache.Write(key, 0, time.Now().Unix()+1800)
|
2020-10-08 15:06:42 +08:00
|
|
|
|
}
|
|
|
|
|
|
return b
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2022-01-08 11:45:14 +08:00
|
|
|
|
// MatchBytesCache 正则表达式匹配字节slice,并缓存结果
|
|
|
|
|
|
func MatchBytesCache(regex *re.Regexp, byteSlice []byte) bool {
|
2020-10-08 15:06:42 +08:00
|
|
|
|
// 如果长度超过4096,大概率是不能重用的
|
|
|
|
|
|
if len(byteSlice) > 4096 {
|
|
|
|
|
|
return regex.Match(byteSlice)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2020-11-21 22:29:57 +08:00
|
|
|
|
hash := xxhash.Sum64(byteSlice)
|
2020-11-21 21:43:03 +08:00
|
|
|
|
key := fmt.Sprintf("%p_", regex) + strconv.FormatUint(hash, 10)
|
|
|
|
|
|
item := cache.Read(key)
|
2020-10-08 15:06:42 +08:00
|
|
|
|
if item != nil {
|
2020-11-21 21:43:03 +08:00
|
|
|
|
return types.Int8(item.Value) == 1
|
|
|
|
|
|
}
|
|
|
|
|
|
if item != nil {
|
|
|
|
|
|
return types.Int8(item.Value) == 1
|
2020-10-08 15:06:42 +08:00
|
|
|
|
}
|
|
|
|
|
|
b := regex.Match(byteSlice)
|
|
|
|
|
|
if b {
|
2020-11-21 21:43:03 +08:00
|
|
|
|
cache.Write(key, 1, time.Now().Unix()+1800)
|
2020-10-08 15:06:42 +08:00
|
|
|
|
} else {
|
2020-11-21 21:43:03 +08:00
|
|
|
|
cache.Write(key, 0, time.Now().Unix()+1800)
|
2020-10-08 15:06:42 +08:00
|
|
|
|
}
|
|
|
|
|
|
return b
|
|
|
|
|
|
}
|