2015-12-24 17:54:54 +03:00
|
|
|
package match
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2016-01-08 20:14:31 +03:00
|
|
|
"strings"
|
2018-02-16 17:36:02 +03:00
|
|
|
"unicode/utf8"
|
2015-12-24 17:54:54 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
type PrefixSuffix struct {
|
2018-02-16 17:36:02 +03:00
|
|
|
p, s string
|
|
|
|
minLen int
|
2015-12-24 17:54:54 +03:00
|
|
|
}
|
|
|
|
|
2016-02-24 12:36:15 +03:00
|
|
|
func NewPrefixSuffix(p, s string) PrefixSuffix {
|
2018-02-16 17:36:02 +03:00
|
|
|
pn := utf8.RuneCountInString(p)
|
|
|
|
sn := utf8.RuneCountInString(s)
|
|
|
|
return PrefixSuffix{p, s, pn + sn}
|
2016-02-24 12:36:15 +03:00
|
|
|
}
|
|
|
|
|
2018-02-16 17:36:02 +03:00
|
|
|
func (ps PrefixSuffix) Index(s string) (int, []int) {
|
|
|
|
prefixIdx := strings.Index(s, ps.p)
|
2016-01-12 14:06:59 +03:00
|
|
|
if prefixIdx == -1 {
|
|
|
|
return -1, nil
|
|
|
|
}
|
|
|
|
|
2018-02-16 17:36:02 +03:00
|
|
|
suffixLen := len(ps.s)
|
2016-02-05 17:29:41 +03:00
|
|
|
if suffixLen <= 0 {
|
|
|
|
return prefixIdx, []int{len(s) - prefixIdx}
|
|
|
|
}
|
2016-01-15 19:50:12 +03:00
|
|
|
|
2016-02-24 12:36:15 +03:00
|
|
|
if (len(s) - prefixIdx) <= 0 {
|
|
|
|
return -1, nil
|
|
|
|
}
|
|
|
|
|
2016-02-23 00:26:06 +03:00
|
|
|
segments := acquireSegments(len(s) - prefixIdx)
|
2016-02-05 17:29:41 +03:00
|
|
|
for sub := s[prefixIdx:]; ; {
|
2018-02-16 17:36:02 +03:00
|
|
|
suffixIdx := strings.LastIndex(sub, ps.s)
|
2016-02-05 17:29:41 +03:00
|
|
|
if suffixIdx == -1 {
|
|
|
|
break
|
2016-01-12 14:06:59 +03:00
|
|
|
}
|
|
|
|
|
2016-02-05 17:29:41 +03:00
|
|
|
segments = append(segments, suffixIdx+suffixLen)
|
|
|
|
sub = sub[:suffixIdx]
|
|
|
|
}
|
2016-01-12 14:06:59 +03:00
|
|
|
|
2016-02-05 17:29:41 +03:00
|
|
|
if len(segments) == 0 {
|
2016-02-24 12:36:15 +03:00
|
|
|
releaseSegments(segments)
|
|
|
|
return -1, nil
|
2016-01-12 14:06:59 +03:00
|
|
|
}
|
|
|
|
|
2016-02-05 17:29:41 +03:00
|
|
|
reverseSegments(segments)
|
|
|
|
|
2016-02-02 22:03:37 +03:00
|
|
|
return prefixIdx, segments
|
2016-01-12 14:06:59 +03:00
|
|
|
}
|
|
|
|
|
2018-02-16 17:36:02 +03:00
|
|
|
func (ps PrefixSuffix) Match(s string) bool {
|
|
|
|
return strings.HasPrefix(s, ps.p) && strings.HasSuffix(s, ps.s)
|
2016-01-09 02:34:41 +03:00
|
|
|
}
|
|
|
|
|
2018-02-16 17:36:02 +03:00
|
|
|
func (ps PrefixSuffix) MinLen() int {
|
|
|
|
return ps.minLen
|
2015-12-24 17:54:54 +03:00
|
|
|
}
|
|
|
|
|
2018-02-16 17:36:02 +03:00
|
|
|
func (ps PrefixSuffix) String() string {
|
|
|
|
return fmt.Sprintf("<prefix_suffix:[%s,%s]>", ps.p, ps.s)
|
2016-01-08 20:14:31 +03:00
|
|
|
}
|