-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnormalize_path.go
More file actions
60 lines (47 loc) · 1.12 KB
/
normalize_path.go
File metadata and controls
60 lines (47 loc) · 1.12 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
package pathutils
import (
"strings"
)
func NormalizePath(path string) (newPath string, ok bool) {
path = replaceMultiSlashes(path)
if !IsPathValid(path) {
return "", false
}
if path == "" || path == "/" {
return "/", true
}
if path[0] == '/' {
path = path[1:]
}
if path[len(path)-1] == '/' {
path = path[0 : len(path)-1]
}
parts := strings.Split(path, "/")
for i, part := range parts {
newPart := NormalizeName(part)
if !IsNameValid(newPart) {
return "", false
}
parts[i] = newPart
}
newPath = "/" + strings.Join(parts, "/")
return newPath, true
}
func replaceMultiSlashes(path string) string {
// regex is slow
// BenchmarkReplaceMultiSlashesRegexp-8 2000000 735 ns/op
// BenchmarkReplaceMultiSlashesRunes-8 10000000 236 ns/op
// BenchmarkReplaceMultiSlashesBytes-8 20000000 82.1 ns/op
pathBytes := []byte(path)
bs := make([]byte, 0, len(pathBytes))
isLastSlash := false
for _, b := range pathBytes {
isSlash := b == '/'
if isSlash && isLastSlash {
continue
}
isLastSlash = isSlash
bs = append(bs, b)
}
return string(bs)
}