This repository has been archived by the owner on Jan 8, 2019. It is now read-only.
/
rand.go
82 lines (66 loc) · 1.92 KB
/
rand.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
78
79
80
81
82
package rand
import (
"crypto/rand"
"math/big"
"github.com/cosiner/gohper/errors"
)
// Charset of characters to use for generating random strings
const (
ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
NUMERALS = "0123456789"
ALPHANUMERIC = NUMERALS + ALPHABET
ErrNegativeNum = errors.Err("Number cannot be negative")
ErrEmptyCharset = errors.Err("Charset cannot be empty")
)
type (
BytesFunc func(n int, charset string) ([]byte, error)
StringFunc func(n int, charset string) (string, error)
)
// B generate a random bytes in gived charset
var B BytesFunc = func(n int, charset string) ([]byte, error) {
if n <= 0 || len(charset) == 0 {
panic("negative number or empty charset")
}
result := make([]byte, n)
charnum := big.NewInt(int64(len(charset)))
for i := 0; i < n; i++ {
r, err := rand.Int(rand.Reader, charnum)
if err != nil {
return nil, err
}
result[i] = charset[int(r.Int64())]
}
return result, nil
}
// String is same as Bytes, return string
var S StringFunc = func(n int, charset string) (string, error) {
b, err := B(n, charset)
if err != nil {
return "", err
}
return string(b), nil
}
// NumberalBytes generate random ASCII bytes
func (f BytesFunc) Numberal(n int) ([]byte, error) {
return f(n, NUMERALS)
}
// AlphabetBytes generate random ALPHABET bytes
func (f BytesFunc) Alphabet(n int) ([]byte, error) {
return f(n, ALPHABET)
}
// AlphanumericBytes generate random ALPHABET and numberic bytes
func (f BytesFunc) Alphanumeric(n int) ([]byte, error) {
return f(n, ALPHANUMERIC)
}
// Numberal generate random numberal string
func (f StringFunc) Numberal(n int) (string, error) {
return f(n, NUMERALS)
}
// Alphabet generate random ALPHABET string
func (f StringFunc) Alphabet(n int) (string, error) {
return f(n, ALPHABET)
}
// Alphanumeric generate random ALPHABET and numberic string
func (f StringFunc) Alphanumeric(n int) (string, error) {
return f(n, ALPHANUMERIC)
}