github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/perf/fastrand/fastrand.go (about)

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package fastrand
     6  
     7  import (
     8  	"github.com/jxskiss/gopkg/v2/internal/constraints"
     9  	"github.com/jxskiss/gopkg/v2/internal/linkname"
    10  )
    11  
    12  // runtimeSource is a Source that uses the runtime fastrand functions.
    13  type runtimeSource struct{}
    14  
    15  func (*runtimeSource) Uint64() uint64 {
    16  	return linkname.Runtime_fastrand64()
    17  }
    18  
    19  // globalRand is the source of random numbers for the top-level
    20  // convenience functions.
    21  var globalRand = &Rand{src: &runtimeSource{}}
    22  
    23  // Uint64 returns a pseudo-random 64-bit value as a uint64.
    24  func Uint64() (x uint64) { return globalRand.Uint64() }
    25  
    26  // Int64 returns a non-negative pseudo-random 63-bit integer as an int64.
    27  func Int64() int64 { return globalRand.Int64() }
    28  
    29  // Uint32 returns a pseudo-random 32-bit value as a uint32.
    30  func Uint32() uint32 { return globalRand.Uint32() }
    31  
    32  // Int32 returns a non-negative pseudo-random 31-bit integer as an int32.
    33  func Int32() int32 { return globalRand.Int32() }
    34  
    35  // Int returns a non-negative pseudo-random int from the default Source.
    36  func Int() int { return globalRand.Int() }
    37  
    38  // Float64 returns, as a float64, a pseudo-random number in the half-open interval [0.0,1.0).
    39  func Float64() float64 { return globalRand.Float64() }
    40  
    41  // Perm returns, as a slice of n ints, a pseudo-random permutation of the integers
    42  // in the half-open interval [0,n).
    43  func Perm(n int) []int { return globalRand.Perm(n) }
    44  
    45  // Shuffle pseudo-randomizes the order of elements.
    46  // n is the number of elements. Shuffle panics if n < 0.
    47  // swap swaps the elements with indexes i and j.
    48  func Shuffle(n int, swap func(i, j int)) { globalRand.Shuffle(n, swap) }
    49  
    50  // N returns a pseudo-random number in the half-open interval [0,n) from the default Source.
    51  // The type parameter Int can be any integer type.
    52  // It panics if n <= 0.
    53  func N[Int constraints.Integer](n Int) Int {
    54  	if n <= 0 {
    55  		panic("invalid argument to N")
    56  	}
    57  	return Int(uint64n(globalRand, uint64(n)))
    58  }