github.com/niubaoshu/goutils@v0.0.0-20180828035119-e8e576f66c2b/rand/randBytes.go (about) 1 package rand 2 3 import ( 4 "math/rand" 5 "time" 6 7 "github.com/niubaoshu/goutils" 8 ) 9 10 var r = rand.New(rand.NewSource(time.Now().UnixNano())) 11 12 const ( 13 NUM = 1 << iota 14 LOWER 15 UPPER 16 17 ALL = NUM | LOWER | UPPER 18 19 num = "1234567890" 20 lower = "abcdefghijklmnopqrstuvwxyz" 21 upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 22 ) 23 24 var ( 25 chars = [...][]byte{ 26 0: []byte{}, // 0 27 NUM: []byte(num), // 001 28 LOWER: []byte(lower), // 010 29 UPPER: []byte(upper), // 100 30 LOWER | NUM: []byte(num + lower), // 011 31 UPPER | NUM: []byte(num + upper), // 101 32 LOWER | UPPER: []byte(lower + upper), // 110 33 NUM | LOWER | UPPER: []byte(num + upper + lower), // 111 34 } 35 lens = [...]int{ 36 0: 0, 37 NUM: len(num), 38 LOWER: len(lower), 39 UPPER: len(upper), 40 LOWER | NUM: len(num + lower), 41 UPPER | NUM: len(num + upper), 42 LOWER | UPPER: len(lower + upper), 43 NUM | LOWER | UPPER: len(num + upper + lower), 44 } 45 ) 46 47 // 48 func BytesToBuff(l int, buff []byte) []byte { 49 for i := 0; i < l; i++ { 50 buff[i] = byte(r.Intn(1 << 8)) 51 } 52 return buff 53 } 54 55 func Bytes(l int) []byte { 56 return BytesToBuff(l, nil) 57 } 58 59 func RandStringAWithChars(l int, chars []byte, data []byte) []byte { 60 buf, n := goutils.EnlargeByte(data, l) 61 ret := buf[n:] 62 for i := 0; i < l; i++ { 63 ret[i] = chars[r.Intn(len(chars))] 64 } 65 return buf 66 } 67 68 func RandStringWithChars(l int, chars []byte) []byte { 69 return RandStringAWithChars(l, chars, nil) 70 } 71 72 func RandStringAWithType(l int, typ int, data []byte) []byte { 73 return RandStringAWithChars(l, chars[typ], data) 74 } 75 func RandStringWithType(l int, typ int) []byte { 76 return RandStringAWithType(l, typ, nil) 77 } 78 79 func RandString(l int) []byte { 80 return RandStringWithType(l, ALL) 81 } 82 func RandStringA(l int, data []byte) []byte { 83 return RandStringAWithType(l, ALL, data) 84 }