go.x2ox.com/sorbifolia/random@v0.0.0-20240520090142-6d8be5c4ed59/safe.go (about)

     1  package random
     2  
     3  import (
     4  	"crypto/rand"
     5  	"unsafe"
     6  
     7  	pn "go.x2ox.com/sorbifolia/pyrokinesis"
     8  )
     9  
    10  type safeRand struct{ *randString }
    11  
    12  func Safe() Random {
    13  	return &safeRand{defaultRandString}
    14  }
    15  
    16  func (r safeRand) RandString(length int) string {
    17  	arr := make([]byte, length)
    18  	arr1 := make([]int, length)
    19  	_, _ = rand.Read(arr)
    20  	for i := range arr {
    21  		arr1[i] = int(uint64(arr[i]) * uint64(r.randBytesLen) >> 8)
    22  	}
    23  	return r.randString.RandString(arr1)
    24  }
    25  
    26  func (r safeRand) SetRandBytes(data []byte) Random {
    27  	return &safeRand{r.randString.SetRandBytes(data)}
    28  }
    29  
    30  func (r safeRand) Uint() uint     { return pn.Bytes.ToUint(r.read(_intSize)) }
    31  func (r safeRand) Uint64() uint64 { return pn.Bytes.ToUint64(r.read(8)) }
    32  func (r safeRand) Uint32() uint32 { return pn.Bytes.ToUint32(r.read(4)) }
    33  func (r safeRand) Uint16() uint16 { return pn.Bytes.ToUint16(r.read(2)) }
    34  func (r safeRand) Uint8() uint8   { return pn.Bytes.ToUint8(r.read(1)) }
    35  
    36  func (r safeRand) Int() int     { return pn.Bytes.ToInt(r.read(_intSize)) }
    37  func (r safeRand) Int64() int64 { return pn.Bytes.ToInt64(r.read(8)) }
    38  func (r safeRand) Int32() int32 { return pn.Bytes.ToInt32(r.read(4)) }
    39  func (r safeRand) Int16() int16 { return pn.Bytes.ToInt16(r.read(2)) }
    40  func (r safeRand) Int8() int8   { return pn.Bytes.ToInt8(r.read(1)) }
    41  
    42  func (r safeRand) Uintn(n uint) uint       { return remainder(n, r.Uint()) }
    43  func (r safeRand) Uint64n(n uint64) uint64 { return remainder(n, r.Uint64()) }
    44  func (r safeRand) Uint32n(n uint32) uint32 { return remainder(n, r.Uint32()) }
    45  func (r safeRand) Uint16n(n uint16) uint16 { return remainder(n, r.Uint16()) }
    46  func (r safeRand) Uint8n(n uint8) uint8    { return remainder(n, r.Uint8()) }
    47  
    48  func (r safeRand) Intn(n int) int       { return remainder(n, r.Int()) }
    49  func (r safeRand) Int64n(n int64) int64 { return remainder(n, r.Int64()) }
    50  func (r safeRand) Int32n(n int32) int32 { return remainder(n, r.Int32()) }
    51  func (r safeRand) Int16n(n int16) int16 { return remainder(n, r.Int16()) }
    52  func (r safeRand) Int8n(n int8) int8    { return remainder(n, r.Int8()) }
    53  
    54  func (r safeRand) read(num int) []byte {
    55  	arr := make([]byte, num)
    56  	_, _ = rand.Read(arr)
    57  	return arr
    58  }
    59  
    60  const _intSize = int(unsafe.Sizeof(int(0)))