github.com/iDigitalFlame/xmt@v0.5.4/util/rand.go (about)

     1  // Copyright (C) 2020 - 2023 iDigitalFlame
     2  //
     3  // This program is free software: you can redistribute it and/or modify
     4  // it under the terms of the GNU General Public License as published by
     5  // the Free Software Foundation, either version 3 of the License, or
     6  // any later version.
     7  //
     8  // This program is distributed in the hope that it will be useful,
     9  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    10  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    11  // GNU General Public License for more details.
    12  //
    13  // You should have received a copy of the GNU General Public License
    14  // along with this program.  If not, see <https://www.gnu.org/licenses/>.
    15  //
    16  
    17  // Package util is a very generic package that is used to contain simple
    18  // functions that may be used in multiple packages, such as the simple random
    19  // number generator.
    20  //
    21  // Generic re-implementations of built-in Golang structs or functions also
    22  // sometimes land in here.
    23  //
    24  // This package is affected by the "stdrand" build tag, which will replace the
    25  // "fastrand" implementation with the "math/rand" random struct.
    26  package util
    27  
    28  import (
    29  	// Import unsafe to use faster "fastrand" function
    30  	_ "unsafe"
    31  )
    32  
    33  // Rand is the custom Random number generator, based on the current time as a
    34  // seed.
    35  //
    36  // This struct is overridden by the tag "stdrand". By default, it will use the
    37  // "unsafe" fastrand() implementation which is faster, but contains less entropy
    38  // than the built-in, 'rand.Rand', which requires more memory and binary storage
    39  // space.
    40  var Rand random
    41  
    42  //go:linkname fastRand runtime.fastrand
    43  func fastRand() uint32
    44  
    45  // FastRand is a fast thread local random function. This should be used in place
    46  // instead of 'Rand.Uint32()'.
    47  //
    48  // Taken from https://github.com/dgraph-io/ristretto/blob/master/z/rtutil.go
    49  // Thanks!
    50  func FastRand() uint32 {
    51  	// NOTE(dij): For some reason, older Go versions don't like calling a linked
    52  	//            function directly.
    53  	return fastRand()
    54  }
    55  
    56  // FastRandN is a fast thread local random function. This should be used in
    57  // place instead of 'Rand.Uint32n()'.
    58  //
    59  // This function will take a max value to specify.
    60  func FastRandN(n int) uint32 {
    61  	// return FastRand() % uint32(n)
    62  	// NOTE(dij): The below code is supposed to be faster.
    63  	return uint32(uint64(fastRand()) * uint64(n) >> 32)
    64  }