-
Notifications
You must be signed in to change notification settings - Fork 0
/
uniqueid.go
86 lines (73 loc) · 2.53 KB
/
uniqueid.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
81
82
83
84
85
86
package useless
import "time"
// UniqueID is a wrapping for a somehow unique id generator
//
type UniqueID struct {
randomizer *RandASCII
}
// NewUniqueID returns a new UniqueID instance
//
func NewUniqueID(charRandomizer *RandASCII) *UniqueID {
return &UniqueID{charRandomizer}
}
// GetUniqueString returns a unique string generated from the current timestamp mixed with some random characters
// and adds an additional random chars to it if needed :)
//
func (uid *UniqueID) GetUniqueString(additionalLength ...int) string {
return uid.getUniqueString(additionalLength...)
}
// GetUniqueStringWithPrefix same as GetUniqueString but adds a prefix to the generated string
//
func (uid *UniqueID) GetUniqueStringWithPrefix(prefix string, additionalLength ...int) string {
return prefix + uid.getUniqueString(additionalLength...)
}
// getUniqueString returns a unique string generated from the current timestamp mixed with some random characters
// and adds an additional random chars to it if needed :)
func (uid *UniqueID) getUniqueString(additionalLength ...int) string {
if additionalLength == nil {
additionalLength = make([]int, 1)
}
return uid.convertTimestampToString(time.Now().Unix()) +
uid.randomizer.GetRandomAlphanumString(additionalLength[0])
}
// getAlphanumCharFromInt returns an alphanumeric character from a given integer,
// when the integer actually represents an alphanumeric character it returns it as is,
// otherwise it shifts it to a known alphanumeric characters range,
// and when it can't be shifted it returns a random alphanumeric character
//
func (uid *UniqueID) getAlphanumCharFromInt(n int) uint8 {
if n >= '0' && n <= '9' ||
n >= 'A' && n <= 'Z' ||
n >= 'a' && n <= 'z' {
return uint8(n)
}
other := uint8(n%'z' + '0')
if other < '0' {
return other + ('0' - other)
} else if other > '9' && other < 'A' {
return other - (other - '9')
}
if other < 'A' && other > '9' {
return other + ('A' - other)
} else if other > 'Z' && other < 'a' {
return other - (other - 'Z')
}
if other < 'a' && other > 'Z' {
return other + ('a' - other)
} else if other > 'z' {
return other - (other - 'z')
}
return uid.randomizer.GetRandomAlphanumChar()
}
// convertTimestampToString partitions a given timestamp to a string
// where each character consists of 3 digits from the timestamp
//
func (uid *UniqueID) convertTimestampToString(ts int64) string {
str := ""
for ; ts > 0; ts /= 100 {
str += string(uid.getAlphanumCharFromInt(
int(ts%100) + 23), // +23 when the value=99 so add 23 to reach 'z'
)
}
return str
}