xpath/main_test.go

98 lines
1.4 KiB
Go
Raw Permalink Normal View History

2020-09-18 10:58:49 +00:00
package main
import (
"testing"
)
type Type int
const (
TypeChild Type = iota
TypeChildren
TypeAllChildren
)
type Node struct {
Prev *Node
Next *Node
2020-09-20 18:06:43 +00:00
Name []rune
2020-09-18 10:58:49 +00:00
Type Type
}
// func extractPath(cur *Node) string {
// var path []byte
// if cur.Next.Next == nil {
// return "/"
// }
// for ; cur != nil; cur = cur.Next {
// path = append(path, cur.Name...)
// if cur.Next.Next == nil {
// break
// }
// path = append(path, '/')
// }
// return string(path)
// }
2020-09-20 18:06:43 +00:00
func toString(root *Node) string {
var content string
for root != nil {
content += string(root.Name)
if root.Type == TypeAllChildren {
content += "//"
} else {
content += "/"
}
root = root.Next
}
return content
}
func xPath(spath string) string {
var path []rune = []rune(spath)
path = append(path, ' ')
2020-09-18 10:58:49 +00:00
2020-09-18 11:19:56 +00:00
root := &Node{}
cur := root
for i := 0; i < len(spath); i++ {
2020-09-18 10:58:49 +00:00
c := path[i]
2020-09-20 18:06:43 +00:00
switch c {
case '/':
2020-09-18 11:19:56 +00:00
if path[i+1] == '/' {
cur.Type = TypeAllChildren
2020-09-20 18:06:43 +00:00
i++
2020-09-18 11:19:56 +00:00
} else {
cur.Type = TypeChild
}
2020-09-18 10:58:49 +00:00
2020-09-20 18:06:43 +00:00
if len(cur.Name) == 0 {
continue
}
cur.Next = &Node{Prev: cur}
2020-09-18 11:19:56 +00:00
cur = cur.Next
2020-09-20 18:06:43 +00:00
// case '(': 先拿括号
default:
cur.Name = append(cur.Name, c)
2020-09-18 10:58:49 +00:00
}
}
2020-09-20 18:06:43 +00:00
return toString(root)
2020-09-18 10:58:49 +00:00
}
func TestMain(t *testing.T) {
2020-09-20 18:06:43 +00:00
// t.Error(xPath("/a/../../b/../c//.//"))
2020-09-18 10:58:49 +00:00
// t.Error(xPath("/a/./b/../../c/"))
// t.Error(xPath("/"))
2020-09-20 18:06:43 +00:00
t.Error(xPath("/a/./b/../../c/"))
// t.Error(xPath("/a//b////c/d//././/.."))
2020-09-18 10:58:49 +00:00
}