rand/main.go

69 lines
1.3 KiB
Go

package rand
import (
"fmt"
crand "crypto/rand"
"math/big"
)
type Generator func() (byte,error)
var chars []byte = []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789~`!@#$%^&*()_+-=[]{}\\|;:'\",./<>?")
var letters []byte = chars[0:52]
var digits []byte = chars[52:62]
var letdig []byte = chars[0:62]
var symbols []byte = chars[62:94]
var digsym []byte = chars[52:94]
var letsym []byte = []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~`!@#$%^&*()_+-=[]{}\\|;:'\",./<>?")
func gen(s []byte) (byte,error) {
nBig, err := crand.Int(crand.Reader, big.NewInt(int64(len(s))))
if err != nil {
return 0, fmt.Errorf("Error in crypto/rand: %s",err)
}
x := nBig.Int64()
return s[x], nil
}
func Letter() (byte,error) {
return gen(letters)
}
func Digit() (byte,error) {
return gen(digits)
}
func Symbol() (byte,error) {
return gen(symbols)
}
func LetterDigits() (byte,error) {
return gen(letdig)
}
func DigitsSymbols() (byte,error) {
return gen(digsym)
}
func LettersSymbols() (byte, error) {
return gen(letsym)
}
func Char() (byte,error) {
return gen(chars)
}
func Slice(Generator, n int) ([]byte,error) {
ret := make([]byte,0)
for i := 0; i < n; i++ {
x,err := f()
if err != nil {
return ret, err
}
ret = append(ret,x)
}
return ret, nil
}