-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathutils.go
More file actions
57 lines (53 loc) · 1.41 KB
/
utils.go
File metadata and controls
57 lines (53 loc) · 1.41 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
package wrap
import "unicode/utf8"
// isASCII returns true if the string contains only ASCII characters.
func isASCII(s string) bool {
for i := 0; i < len(s); i++ {
if s[i] >= utf8.RuneSelf {
return false
}
}
return true
}
// runeIndexToByte returns the byte index for a given rune index in s.
// If runeIndex exceeds the string length, returns len(s).
func runeIndexToByte(s string, runeIndex int) int {
if runeIndex >= len(s) {
if isASCII(s) {
return len(s)
}
} else if isASCII(s[:runeIndex]) {
return runeIndex
}
byteIndex := 0
for i := 0; i < runeIndex && byteIndex < len(s); i++ {
_, size := utf8.DecodeRuneInString(s[byteIndex:])
byteIndex += size
}
return byteIndex
}
// runeIndexToByteWithShortCheck returns the byte index for a given rune index.
// Returns -1 if the string has fewer than runeIndex runes.
func runeIndexToByteWithShortCheck(s string, runeIndex int) int {
if runeIndex > len(s) {
// String can't have enough runes if byte length is less
if isASCII(s) {
return -1
}
// Count actual runes for non-ASCII
if utf8.RuneCountInString(s) < runeIndex {
return -1
}
} else if isASCII(s[:runeIndex]) {
return runeIndex
}
byteIndex := 0
for i := 0; i < runeIndex && byteIndex < len(s); i++ {
_, size := utf8.DecodeRuneInString(s[byteIndex:])
byteIndex += size
}
if byteIndex >= len(s) && utf8.RuneCountInString(s) < runeIndex {
return -1
}
return byteIndex
}