This repository has been archived by the owner on Oct 2, 2023. It is now read-only.
/
hash.go
77 lines (63 loc) · 1.51 KB
/
hash.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
package imagestore
import (
"crypto/rand"
"log"
)
// Provides a continuous stream of random image "hashes" of a fixed length that is unique (does not exist in the store).
type HashGenerator struct {
hashGetter chan string
length int
store ImageStore
}
func (this *HashGenerator) init() {
go func() {
storeObj := &StoreObject{
"",
"",
"original",
"",
}
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)
}
}
}
storeObj.Id = str
exists, _ := this.store.Exists(storeObj)
if !exists {
this.hashGetter <- str
}
}
}()
}
func (this *HashGenerator) Get() string {
return <-this.hashGetter
}