-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathunique.go
59 lines (43 loc) · 1.05 KB
/
unique.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
package slug
import (
"strconv"
"sync"
)
var (
uniqueCache = make(map[string]struct{})
uniqueCacheMutex sync.Mutex
)
func uniqueFormatText(slug string, options *Options) (uniqueSlug string, err error) {
defer uniqueCacheMutex.Unlock()
uniqueCacheMutex.Lock()
potentialSlug := slug
var suffixValue uint64 = 1
for i := options.UniqueAttempts; i > 0; i-- {
if _, found := uniqueCache[potentialSlug]; !found {
uniqueCache[potentialSlug] = struct{}{}
uniqueSlug = potentialSlug
return
}
suffixValue++
suffix := strconv.FormatUint(suffixValue, 16)
slugLen := len(slug)
replacementLen := len(options.Replacement)
suffixLen := len(suffix)
for {
totalLen := slugLen + suffixLen
if slug[slugLen-replacementLen:] != options.Replacement {
totalLen += replacementLen
}
if totalLen <= options.MaxLen {
break
}
if slugLen--; slugLen == 0 {
err = ErrUniqueLength
return
}
}
potentialSlug = formatText(slug[:slugLen]+options.Replacement+suffix, options)
}
err = ErrUniqueAttempts
return
}