randutil

package
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 21, 2025 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

Package randutil provides random number generation utilities.

The package provides two types of generators:

1. Secure generators using crypto/rand (for security-sensitive applications) 2. Fast generators using math/rand/v2 (for non-security applications)

Secure Random Generation

For cryptographic purposes, password generation, or security tokens:

bytes, err := randutil.SecureBytes(32)
str, err := randutil.SecureString(16, randutil.AlphaNumeric)
id := randutil.SecureID()

Fast Random Generation

For non-security purposes like tests, sampling, or simulations:

rng := randutil.NewGenerator()
n := rng.Int(100)           // [0, 100)
f := rng.Float64()          // [0.0, 1.0)
item := rng.Choice(items)   // Random element
rng.Shuffle(items)          // Shuffle in place

Deterministic Generation

For reproducible random sequences in tests:

rng := randutil.NewGeneratorWithSeed(42)
// Always produces the same sequence

Character Sets

Predefined character sets for string generation:

Digits      - "0123456789"
Lowercase   - "abcdefghijklmnopqrstuvwxyz"
Uppercase   - "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Letters     - Lowercase + Uppercase
AlphaNumeric - Letters + Digits
Hex         - "0123456789abcdef"

Index

Constants

View Source
const (
	Digits       = "0123456789"
	Lowercase    = "abcdefghijklmnopqrstuvwxyz"
	Uppercase    = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
	Letters      = Lowercase + Uppercase
	AlphaNumeric = Letters + Digits
	Hex          = "0123456789abcdef"
	Symbols      = "!@#$%^&*()_+-=[]{}|;:,.<>?"
	All          = AlphaNumeric + Symbols
)

Character sets for random string generation.

Variables

View Source
var (
	ErrInvalidLength = errors.New("length must be positive")
	ErrEmptyCharset  = errors.New("charset cannot be empty")
	ErrEmptySlice    = errors.New("slice cannot be empty")
)

Common errors.

Functions

func Choice

func Choice[T any](g *Generator, s []T) T

Choice is a generic function for random selection from a slice.

func ChoiceN

func ChoiceN[T any](g *Generator, s []T, n int) []T

ChoiceN is a generic function returning n random elements (with replacement).

func Range

func Range(start, end int) []int

Range returns a slice of integers from start to end (exclusive).

func RangeStep

func RangeStep(start, end, step int) []int

RangeStep returns a slice of integers from start to end with step.

func Sample

func Sample[T any](g *Generator, s []T, n int) []T

Sample is a generic function returning n random elements (without replacement).

func SecureBytes

func SecureBytes(n int) ([]byte, error)

SecureBytes returns n cryptographically secure random bytes.

Example:

key, err := SecureBytes(32) // 32 random bytes

func SecureChoice

func SecureChoice[T any](s []T) (T, error)

SecureChoice returns a cryptographically secure random element from the slice.

func SecureID

func SecureID() (string, error)

SecureID generates a cryptographically secure random ID. Returns a 32-character hex string (128 bits of entropy).

Example:

id := SecureID() // "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4"

func SecureInt

func SecureInt(max int) (int, error)

SecureInt returns a cryptographically secure random int in [0, max).

func SecureInt64

func SecureInt64(max int64) (int64, error)

SecureInt64 returns a cryptographically secure random int64 in [0, max).

func SecureString

func SecureString(length int, charset string) (string, error)

SecureString returns a cryptographically secure random string of the specified length using characters from the charset.

Example:

password, err := SecureString(16, AlphaNumeric)
token, err := SecureString(32, Hex)

func Sequence

func Sequence(start, n int) []int

Sequence returns a slice of n sequential integers starting from start.

func Shuffle

func Shuffle[T any](g *Generator, s []T)

Shuffle is a generic function that shuffles a slice in place.

func ShuffleCopy

func ShuffleCopy[T any](g *Generator, s []T) []T

ShuffleCopy returns a new shuffled slice (does not modify original).

Types

type Generator

type Generator struct {
	// contains filtered or unexported fields
}

Generator provides fast (non-cryptographic) random generation. Use NewGenerator() for automatic seeding or NewGeneratorWithSeed() for reproducibility.

func NewGenerator

func NewGenerator() *Generator

NewGenerator creates a new Generator with automatic seeding. Uses a cryptographically secure seed for good randomness.

func NewGeneratorWithSeed

func NewGeneratorWithSeed(seed uint64) *Generator

NewGeneratorWithSeed creates a Generator with a specific seed. Useful for reproducible random sequences in tests.

Example:

rng := NewGeneratorWithSeed(42)
// Always produces the same sequence

func (*Generator) AlphaNumericString

func (g *Generator) AlphaNumericString(length int) string

AlphaNumericString returns a random alphanumeric string.

func (*Generator) Bool

func (g *Generator) Bool() bool

Bool returns a random boolean.

func (*Generator) Bytes

func (g *Generator) Bytes(n int) []byte

Bytes returns n random bytes.

func (*Generator) ChoiceInt

func (g *Generator) ChoiceInt(s []int) int

ChoiceInt returns a random element from an int slice. Panics if slice is empty.

func (*Generator) ChoiceString

func (g *Generator) ChoiceString(s []string) string

ChoiceString returns a random element from a string slice. Panics if slice is empty.

func (*Generator) Float32

func (g *Generator) Float32() float32

Float32 returns a random float32 in [0.0, 1.0).

func (*Generator) Float64

func (g *Generator) Float64() float64

Float64 returns a random float64 in [0.0, 1.0).

func (*Generator) Float64Range

func (g *Generator) Float64Range(min, max float64) float64

Float64Range returns a random float64 in [min, max).

func (*Generator) Int

func (g *Generator) Int(max int) int

Int returns a random int in [0, max). Panics if max <= 0.

func (*Generator) Int64

func (g *Generator) Int64(max int64) int64

Int64 returns a random int64 in [0, max).

func (*Generator) Int64Range

func (g *Generator) Int64Range(min, max int64) int64

Int64Range returns a random int64 in [min, max].

func (*Generator) IntRange

func (g *Generator) IntRange(min, max int) int

IntRange returns a random int in [min, max]. Panics if min > max.

func (*Generator) Probability

func (g *Generator) Probability(p float64) bool

Probability returns true with the given probability (0.0 to 1.0).

Example:

if rng.Probability(0.75) {
    // 75% chance of executing
}

func (*Generator) SampleInts

func (g *Generator) SampleInts(s []int, n int) []int

SampleInts returns n random ints from the slice (without replacement). If n > len(s), returns all elements shuffled.

func (*Generator) ShuffleInts

func (g *Generator) ShuffleInts(s []int)

ShuffleInts shuffles an int slice in place.

func (*Generator) ShuffleStrings

func (g *Generator) ShuffleStrings(s []string)

ShuffleStrings shuffles a string slice in place.

func (*Generator) String

func (g *Generator) String(length int, charset string) string

String returns a random string of the specified length using the charset.

func (*Generator) WeightedChoice

func (g *Generator) WeightedChoice(weights []float64) int

WeightedChoice returns a random index based on weights. Weight values don't need to sum to 1.0.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL