github.com/seeker-insurance/kit@v0.0.13/random/random.go (about)

     1  //Package random provides tools for generating cryptographically secure random elements. it uses golang's built in `crypto/rand` for it's RNG.
     2  package random
     3  
     4  import (
     5  	"crypto/rand"
     6  	"encoding/base64"
     7  	"math"
     8  )
     9  
    10  //RandomBytes returns a random slice of n bytes
    11  func RandomBytes(n int) ([]byte, error) {
    12  	b := make([]byte, n)
    13  	_, err := rand.Read(b)
    14  	if err != nil {
    15  		return nil, err
    16  	}
    17  
    18  	return b, nil
    19  }
    20  
    21  //RandomString returns a random string comprised of n bytes
    22  func RandomString(n int) (string, error) {
    23  	b, err := RandomBytes(n)
    24  	return base64.URLEncoding.EncodeToString(b), err
    25  }
    26  
    27  //Int64s returns a slice containing n random int64s
    28  func Int64s(n int) ([]int64, error) {
    29  	bytes, err := RandomBytes(8 * n)
    30  	if err != nil {
    31  		return nil, err
    32  	}
    33  
    34  	ints := make([]int64, 0, n)
    35  	for i := 0; i < len(bytes); i += 8 {
    36  		ints = append(ints, int64(_uint64(bytes[i:i+8])))
    37  	}
    38  
    39  	return ints, nil
    40  }
    41  
    42  //Uint64s returns a slice containing n random uint64s
    43  func Uint64s(n int) ([]uint64, error) {
    44  	bytes, err := RandomBytes(8 * n)
    45  	if err != nil {
    46  		return nil, err
    47  	}
    48  	uints := make([]uint64, 0, n)
    49  	for i := 0; i < len(bytes); i += 8 {
    50  		uints = append(uints, _uint64(bytes[i:i+8]))
    51  	}
    52  
    53  	return uints, nil
    54  }
    55  
    56  //_uint64 converts the first 8 bytes in the slice into a uint64 (bigendian)
    57  //this is NOT safe and will panic given a slice of too little length.
    58  func _uint64(a []byte) (u uint64) {
    59  	for i := uint64(0); i < 8; i++ {
    60  		u |= uint64(a[i]) << (i * 8)
    61  	}
    62  	return u
    63  }
    64  
    65  //Float64s returns a slice containing n random float64s
    66  func Float64s(n int) ([]float64, error) {
    67  	bytes, err := RandomBytes(8 * n)
    68  	if err != nil {
    69  		return nil, err
    70  	}
    71  	floats := make([]float64, 0, n)
    72  	for i := 0; i < len(bytes); i += 8 {
    73  		u := _uint64(bytes[i : i+8])
    74  		floats = append(floats, math.Float64frombits(u))
    75  	}
    76  	return floats, nil
    77  }