-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhashGenerator.go
More file actions
87 lines (71 loc) · 1.63 KB
/
hashGenerator.go
File metadata and controls
87 lines (71 loc) · 1.63 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
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
87
package goutils
import (
"crypto/rand"
"log"
)
type HashGenerator struct {
hashGetter chan string
length int
}
func (this *HashGenerator) init() {
go func() {
for {
str := ""
for len(str) < this.length {
c := 10
bArr := make([]byte, c)
_, err := rand.Read(bArr)
if err != nil {
log.Println("error:", err)
break
}
for _, b := range bArr {
if len(str) == this.length {
break
}
/**
* Each byte will be in [0, 256), but we only care about:
*
* [48, 57] 0-9
* [65, 90] A-Z
* [97, 122] a-z
*
* Which means that the highest bit will always be zero, since the last byte with high bit
* zero is 01111111 = 127 which is higher than 122. Lower our odds of having to re-roll a byte by
* dividing by two (right bit shift of 1).
*/
b = b >> 1
// The byte is any of 0-9 A-Z a-z
byteIsAllowable := (b >= 48 && b <= 57) || (b >= 65 && b <= 90) || (b >= 97 && b <= 122)
if byteIsAllowable {
str += string(b)
}
}
}
this.hashGetter <- str
}
}()
}
func (this *HashGenerator) Get() string {
return <-this.hashGetter
}
func (this *HashGenerator) New(length int) *HashGenerator {
this.hashGetter = make(chan string)
this.length = length
this.init()
return this
}
func NewHashGen(length int) *HashGenerator {
return newHashGen(length)
}
func newHashGen(length int) *HashGenerator {
if length <= 3 {
panic("args `length` length >= 3 !")
}
hashGen := &HashGenerator{
make(chan string),
length,
}
hashGen.init()
return hashGen
}