-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutil.go
More file actions
109 lines (99 loc) · 2.3 KB
/
util.go
File metadata and controls
109 lines (99 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package htmlparse
import (
"errors"
"strings"
"unicode"
)
var (
NotTagError = errors.New("it's not a tag")
NotCssSelectorError = errors.New("css selector syntax error")
TagsWithoutClose = map[string]bool{
"br": true,
"img": true,
"hr": true,
"input": true,
"link": true,
"meta": true,
}
)
func ReadWord(s []byte) []byte {
for i := 0; i < len(s); i++ {
if unicode.IsLetter(rune(s[i])) || unicode.IsDigit(rune(s[i])) {
continue
}
return s[:i]
}
return []byte{}
}
//read the bytes terminate with or followed by a '<' or '>'
func ReadSegment(s []byte, offset int) (int, []byte, error) {
if offset < 0 || offset >= len(s)-1 {
return 0, []byte{}, errors.New("index out of range")
}
var inDoubleQuote bool = false
var inSingleQuote bool = false
var length int = len(s)
for i := offset; i < length; i++ {
if s[i] == '"' {
inDoubleQuote = !inDoubleQuote
}
if s[i] == '\'' {
inSingleQuote = !inSingleQuote
}
if inSingleQuote || inDoubleQuote {
continue
}
if i > offset {
if s[i] == '>' {
return i - offset + 1, s[offset : i+1], nil
} else if s[i] == '<' {
return i - offset, s[offset:i], nil
} else {
continue
}
}
}
return length - offset, []byte{}, nil
}
func ReadTagname(s []byte) (string, error) {
if len(s) < 3 {
return "", NotTagError
}
if s[0] != '<' {
return "", NotTagError
}
for i := 0; i < len(s); i++ {
if s[1] != '/' && (s[i] == ' ' || s[i] == '>' || i == len(s)-1) {
return string(s[1:i]), nil
} else if s[1] == '/' && (s[i] == ' ' || s[i] == '>' || i == len(s)-1) {
return string(s[2:i]), nil
} else {
continue
}
}
return "", NotTagError
}
func IsTag(text []byte) bool {
return len(text) > 0 && text[0] == '<' && text[len(text)-1] == '>'
}
func IsSingleTag(tagName string) bool {
if _, ok := TagsWithoutClose[tagName]; ok {
return true
}
return false
}
func IsOpenTag(text []byte) bool {
return len(text) > 0 && text[0] == '<' && text[len(text)-1] == '>' && text[1] != '/'
}
func IsCloseTag(text []byte) bool {
return len(text) > 0 && text[0] == '<' && text[len(text)-1] == '>' && text[1] == '/'
}
func WrappedBy(str, wrap string) bool {
if len(str)-2*len(wrap) < 0 {
return false
}
if strings.HasPrefix(str, wrap) && strings.HasSuffix(str, wrap) {
return true
}
return false
}