From ca159b2726ac29cf738b9108b34e0ed0f590efd6 Mon Sep 17 00:00:00 2001 From: Jae Kwon Date: Tue, 15 Jul 2014 23:41:40 -0700 Subject: [PATCH] RandStr() is base62 --- common/random.go | 33 +++++++++++++++++++++++++++------ 1 file changed, 27 insertions(+), 6 deletions(-) diff --git a/common/random.go b/common/random.go index 186fb2a40..6e92d96df 100644 --- a/common/random.go +++ b/common/random.go @@ -1,12 +1,33 @@ package common -import "crypto/rand" +import ( + "math/rand" +) +const ( + strChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" // 62 characters +) + +// Construts an alphanumeric string of given length. func RandStr(length int) string { - b := make([]byte, length) - _, err := rand.Read(b) - if err != nil { - return "" + chars := []byte{} +MAIN_LOOP: + for { + val := rand.Int63() + for i := 0; i < 10; i++ { + v := int(val & 0x3f) // rightmost 6 bits + if v >= 62 { // only 62 characters in strChars + val >>= 6 + continue + } else { + chars = append(chars, strChars[v]) + if len(chars) == length { + break MAIN_LOOP + } + val >>= 6 + } + } } - return string(b) + + return string(chars) }