Skip to content

Instantly share code, notes, and snippets.

@taichi
Created February 3, 2014 09:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save taichi/8781153 to your computer and use it in GitHub Desktop.
Save taichi/8781153 to your computer and use it in GitHub Desktop.
random string generator written in go
package rand
import (
"crypto/rand"
"math/big"
)
type RandomStringer struct {
proposal []rune
length *big.Int
}
func New(runes []rune) *RandomStringer {
rs := &RandomStringer{
proposal: runes,
length: big.NewInt(int64(len(runes))),
}
return rs
}
func Alnum() *RandomStringer {
b := make([]rune, 0)
b = append(b, Runes('0', '9')...)
b = append(b, Runes('a', 'z')...)
b = append(b, Runes('A', 'Z')...)
return New(b)
}
func Runes(from, to rune) []rune {
s := make([]rune, to-from+1)
for i := to - from; -1 < i; i-- {
s[i] = from + i
}
return s
}
func (rs *RandomStringer) Next(length int) string {
s := make([]rune, length)
for i := 0; i < length; i++ {
r, e := rand.Int(rand.Reader, rs.length)
if e == nil {
s[i] = rs.proposal[uint(r.Uint64())]
} else {
panic(e)
}
}
return string(s)
}
package rand_test
import (
. "."
"crypto/rand"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"strings"
)
var _ = Describe("Rand", func() {
Context("Runes", func() {
It("should work normally", func() {
runes := Runes('a', 'd')
Expect(runes).To(Equal([]rune{'a', 'b', 'c', 'd'}))
})
})
Context("Alnum", func() {
var rs *RandomStringer
BeforeEach(func() {
// fix seed
rand.Reader = strings.NewReader("abcABCxyz123")
rs = Alnum()
})
It("should work normally", func() {
Expect(rs.Next(10)).To(Equal("xyz123UVWN"))
})
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment