You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
ims/util/evio/utils.go

55 lines
1.0 KiB

2 months ago
package evio
import "strings"
type null[T any] struct {
val T
ok bool
}
type matcher struct {
rawPattern string
pattern string
matchPrefix bool
matchSuffix bool
}
// TODO 优化,使用缓存,只处理一次
func NewMatcher(pattern string) Matcher {
m := matcher{
rawPattern: pattern,
pattern: pattern,
matchPrefix: strings.HasSuffix(pattern, ".*"), // foo.*
matchSuffix: strings.HasPrefix(pattern, ".*"), // *.bar
}
if m.matchPrefix {
m.pattern = pattern[:len(pattern)-1]
}
if m.matchSuffix {
m.pattern = pattern[1:]
}
return &m
}
func (m *matcher) Match(topic string) bool {
if m.rawPattern == topic {
return true
}
hasPrefix := strings.HasPrefix(topic, m.pattern)
hasSuffix := strings.HasSuffix(topic, m.pattern)
hasMiddle := strings.Contains(topic, m.pattern)
// *.bar.*
if !m.matchPrefix && !m.matchSuffix {
return hasMiddle && !hasPrefix && !hasSuffix
}
// foo.*
if m.matchPrefix {
return hasPrefix
}
// *.bar
if m.matchSuffix {
return hasSuffix
}
return false
}