github.com/yaling888/clash@v1.53.0/common/rand/rand.go (about)

     1  package rand
     2  
     3  import (
     4  	"crypto/rand"
     5  	"encoding/binary"
     6  	"math/big"
     7  )
     8  
     9  const (
    10  	rngMax  = 1 << 63
    11  	rngMask = rngMax - 1
    12  )
    13  
    14  var Reader = rand.Reader
    15  
    16  // Intn returns a uniform random value in [0, max). It panics if max <= 0.
    17  func Intn(max int) int {
    18  	b, err := rand.Int(rand.Reader, big.NewInt(int64(max)))
    19  	if err != nil {
    20  		return 0
    21  	}
    22  	return int(b.Int64())
    23  }
    24  
    25  // IntnRange generates an integer in range [min, max).
    26  // By design this should panic if input is invalid, <= 0.
    27  func IntnRange(min, max int) int {
    28  	return Intn(max-min) + min
    29  }
    30  
    31  func Int() int {
    32  	u := uint(Int63())
    33  	return int(u << 1 >> 1)
    34  }
    35  
    36  func Int31() int32 {
    37  	return int32(Int63() >> 32)
    38  }
    39  
    40  func Int63() int64 {
    41  	return int64(Uint64() & rngMask)
    42  }
    43  
    44  func Uint32() uint32 {
    45  	return uint32(Int63() >> 31)
    46  }
    47  
    48  func Uint64() uint64 {
    49  	b := make([]byte, 8)
    50  	if _, err := rand.Read(b); err != nil {
    51  		return 0
    52  	}
    53  	return binary.NativeEndian.Uint64(b)
    54  }
    55  
    56  func Float32() float32 {
    57  again:
    58  	f := float32(Float64())
    59  	if f == 1 {
    60  		goto again
    61  	}
    62  	return f
    63  }
    64  
    65  func Float64() float64 {
    66  again:
    67  	f := float64(Int63()) / rngMax
    68  	if f == 1 {
    69  		goto again
    70  	}
    71  	return f
    72  }
    73  
    74  func Read(b []byte) (n int, err error) {
    75  	return rand.Read(b)
    76  }