github.com/enetx/g@v1.0.80/pkg/rand/rand.go (about)

     1  package rand
     2  
     3  import (
     4  	"crypto/rand"
     5  	"encoding/binary"
     6  
     7  	"github.com/enetx/g/pkg/constraints"
     8  )
     9  
    10  // N generates a random non-negative integer within the range [0, max).
    11  // The generated integer will be less than the provided maximum value.
    12  // If max is less than or equal to 0, the function will treat it as if max is 1.
    13  //
    14  // Usage:
    15  //
    16  //	n := 10
    17  //	randomInt := rand.N(n)
    18  //	fmt.Printf("Random integer between 0 and %d: %d\n", max, randomInt)
    19  //
    20  // Parameters:
    21  //   - n (int): The maximum bound for the random integer to be generated.
    22  //
    23  // Returns:
    24  //   - int: A random non-negative integer within the specified range.
    25  func N[T constraints.Integer](n T) T {
    26  	// If the provided maximum value is less than or equal to 0,
    27  	// set it to 1 to ensure a valid range.
    28  	if n <= 0 {
    29  		n = 1
    30  	}
    31  
    32  	// Declare a uint64 variable to store the random value.
    33  	var randVal uint64
    34  
    35  	// Read a random value from the rand.Reader (a cryptographically
    36  	// secure random number generator) into the randVal variable,
    37  	// using binary.LittleEndian for byte ordering.
    38  	_ = binary.Read(rand.Reader, binary.LittleEndian, &randVal)
    39  
    40  	// Return the generated random value modulo the maximum value as an integer.
    41  	return T(randVal % uint64(n))
    42  }