/
slugify.go
80 lines (63 loc) · 1.51 KB
/
slugify.go
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
/*
Copyright 2017 caicloud authors. All rights reserved.
*/
package slugify
import (
"math/rand"
"strings"
"time"
"github.com/mozillazg/go-slugify"
)
const randLen = 5
const letterBytes = "abcdefghijklmnopqrstuvwxyz"
const (
letterIdxBits = 6
letterIdxMask = 1<<letterIdxBits - 1
letterIdxMax = 63 / letterIdxBits
)
var src = rand.NewSource(time.Now().UnixNano())
// randString return a string with n characters
func randString(n int) string {
b := make([]byte, n)
for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; {
if remain == 0 {
cache, remain = src.Int63(), letterIdxMax
}
if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
b[i] = letterBytes[idx]
i--
}
cache >>= letterIdxBits
remain--
}
return string(b)
}
// Slugify converts input 'str' to a string only containing alphameric and "-".
// if withSuffix is true, will append a random string
// maxIDlen controls the max length of the string
func Slugify(str string, withSuffix bool, maxIDlen int) string {
s := slugify.Slugify(str)
if len(s) == 0 {
s = randString(9)
}
if withSuffix {
s = appendRandString(s, randLen)
}
if maxIDlen == -1 {
return s
}
if len(s) < 2 {
s = appendRandString(s, 9)
}
if maxIDlen > randLen+1 && len(s) > maxIDlen {
cutoff := maxIDlen - randLen - 1
return appendRandString(s[:cutoff], randLen)
}
return s
}
func appendRandString(s string, n int) string {
if strings.HasSuffix(s, "-") || len(s) == 0 {
return s + randString(n)
}
return s + "-" + randString(n)
}