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

     1  package random
     2  
     3  import (
     4  	_ "runtime"
     5  	"unsafe"
     6  	_ "unsafe"
     7  )
     8  
     9  type fastRand struct{ *randString }
    10  
    11  func Fast() Random {
    12  	return &fastRand{defaultRandString}
    13  }
    14  
    15  func (r fastRand) RandString(length int) string {
    16  	arr := make([]int, length)
    17  	for i := range arr {
    18  		arr[i] = int(uint64(_fastRand()) * uint64(r.randString.randBytesLen) >> 32)
    19  	}
    20  	return r.randString.RandString(arr)
    21  }
    22  
    23  func (r fastRand) SetRandBytes(data []byte) Random {
    24  	return &fastRand{r.randString.SetRandBytes(data)}
    25  }
    26  
    27  func (r fastRand) Uint() uint     { return uint(_fastRand64()) }
    28  func (r fastRand) Uint64() uint64 { return _fastRand64() }
    29  func (r fastRand) Uint32() uint32 { return _fastRand() }
    30  func (r fastRand) Uint16() uint16 { return uint16(_fastRand()) }
    31  func (r fastRand) Uint8() uint8   { return uint8(_fastRand()) }
    32  
    33  func (r fastRand) Int() int     { return toPtr[int](r.Uint()) }
    34  func (r fastRand) Int64() int64 { return toPtr[int64](r.Uint64()) }
    35  func (r fastRand) Int32() int32 { return toPtr[int32](r.Uint32()) }
    36  func (r fastRand) Int16() int16 { return toPtr[int16](r.Uint16()) }
    37  func (r fastRand) Int8() int8   { return toPtr[int8](r.Uint8()) }
    38  
    39  func (r fastRand) Uintn(n uint) uint       { return remainder(n, r.Uint()) }
    40  func (r fastRand) Uint64n(n uint64) uint64 { return remainder(n, r.Uint64()) }
    41  func (r fastRand) Uint32n(n uint32) uint32 { return remainder(n, r.Uint32()) }
    42  func (r fastRand) Uint16n(n uint16) uint16 { return remainder(n, r.Uint16()) }
    43  func (r fastRand) Uint8n(n uint8) uint8    { return remainder(n, r.Uint8()) }
    44  
    45  func (r fastRand) Intn(n int) int       { return remainder(n, r.Int()) }
    46  func (r fastRand) Int64n(n int64) int64 { return remainder(n, r.Int64()) }
    47  func (r fastRand) Int32n(n int32) int32 { return remainder(n, r.Int32()) }
    48  func (r fastRand) Int16n(n int16) int16 { return remainder(n, r.Int16()) }
    49  func (r fastRand) Int8n(n int8) int8    { return remainder(n, r.Int8()) }
    50  
    51  func toPtr[T int | int64 | int32 | int16 | int8, N uint | uint64 | uint32 | uint16 | uint8](n N) T {
    52  	return *(*T)(unsafe.Pointer(&n))
    53  }
    54  
    55  func remainder[T uint | uint64 | uint32 | uint16 | uint8 | int | int64 | int32 | int16 | int8](n, r T) T {
    56  	if n == 0 {
    57  		return r
    58  	}
    59  	return r % n
    60  }