Created
January 25, 2015 00:01
-
-
Save briankassouf/1057fa7aefe71df773e7 to your computer and use it in GitHub Desktop.
Imgur-esque hash generator written in Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"crypto/rand" | |
"fmt" | |
"log" | |
) | |
func main() { | |
hashGetter := make(chan string) | |
length := 7 | |
go func() { | |
for { | |
str := "" | |
for len(str) < 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) == 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) | |
} | |
} | |
} | |
hashGetter <- str | |
} | |
}() | |
for i := 0; i < 5; i++ { | |
fmt.Println(<-hashGetter) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment