glob/match/btree.go

118 lines
1.8 KiB
Go
Raw Normal View History

2016-01-08 20:14:31 +03:00
package match
import (
"fmt"
2016-01-09 02:34:41 +03:00
"unicode/utf8"
2016-01-08 20:14:31 +03:00
)
type BTree struct {
2016-01-12 14:06:59 +03:00
Value, Left, Right Matcher
2016-01-08 20:14:31 +03:00
}
func (self BTree) Kind() Kind {
return KindBTree
}
2016-01-09 02:34:41 +03:00
func (self BTree) len() (l, v, r int, ok bool) {
v = self.Value.Len()
if self.Left != nil {
l = self.Left.Len()
}
if self.Right != nil {
r = self.Right.Len()
}
ok = l > -1 && v > -1 && r > -1
return
}
func (self BTree) Len() int {
l, v, r, ok := self.len()
if ok {
return l + v + r
}
return -1
}
2016-01-12 14:06:59 +03:00
// todo
func (self BTree) Index(s string) (int, []int) {
return -1, nil
}
2016-01-08 20:14:31 +03:00
func (self BTree) Match(s string) bool {
2016-01-09 02:34:41 +03:00
inputLen := len(s)
lLen, vLen, rLen, ok := self.len()
if ok && lLen+vLen+rLen > inputLen {
return false
}
2016-01-08 20:14:31 +03:00
2016-01-09 02:34:41 +03:00
var offset, limit int
if lLen >= 0 {
offset = lLen
}
if rLen >= 0 {
limit = inputLen - rLen
} else {
limit = inputLen
}
2016-01-08 20:14:31 +03:00
2016-01-09 02:34:41 +03:00
for offset < limit {
index, segments := self.Value.Index(s[offset:limit])
2016-01-08 20:14:31 +03:00
if index == -1 {
return false
}
2016-01-09 02:34:41 +03:00
l := string(s[:offset+index])
var left bool
if self.Left != nil {
left = self.Left.Match(l)
} else {
left = l == ""
}
2016-01-08 20:14:31 +03:00
2016-01-09 02:34:41 +03:00
if left {
for i := len(segments) - 1; i >= 0; i-- {
length := segments[i]
2016-01-08 20:14:31 +03:00
2016-01-09 02:34:41 +03:00
if rLen >= 0 && inputLen-(offset+index+length) != rLen {
continue
}
2016-01-08 20:14:31 +03:00
2016-01-09 02:34:41 +03:00
var right bool
2016-01-08 20:14:31 +03:00
2016-01-09 02:34:41 +03:00
var r string
// if there is no string for the right branch
if inputLen <= offset+index+length {
r = ""
} else {
r = s[offset+index+length:]
}
if self.Right != nil {
right = self.Right.Match(r)
} else {
right = r == ""
}
2016-01-08 20:14:31 +03:00
2016-01-09 02:34:41 +03:00
if right {
return true
}
2016-01-08 20:14:31 +03:00
}
}
2016-01-09 02:34:41 +03:00
_, step := utf8.DecodeRuneInString(s[offset+index:])
offset += index + step
2016-01-08 20:14:31 +03:00
}
return false
}
func (self BTree) String() string {
2016-01-13 01:26:48 +03:00
return fmt.Sprintf("<btree:[%s<-%s->%s]>", self.Left, self.Value, self.Right)
2016-01-08 20:14:31 +03:00
}