randutil

package module
v2.1.1 Latest Latest
Warning

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

Go to latest
Published: Oct 1, 2025 License: MIT Imports: 7 Imported by: 0

README

randutil

CSPRNG-first random utilities for Go. One small package that does the common random things: bias-free integers, bytes, strings/tokens, emails, shuffle/sample for slices, and realistic date/time helpers.

Install

go get github.com/aatuh/randutil/v2

Quick start

package main

import (
  "fmt"

  "github.com/aatuh/randutil/v2/numeric"
  "github.com/aatuh/randutil/v2/collection"
  "github.com/aatuh/randutil/v2/randstring"
  "github.com/aatuh/randutil/v2/email"
  "github.com/aatuh/randutil/v2/randtime"
  "github.com/aatuh/randutil/v2/uuid"
)

func main() {
  // Numbers
  n := numeric.MustIntRange(10, 20)     // inclusive
  f := numeric.MustFloat64()            // [0,1)
  b := numeric.MustBytes(16)            // 16 random bytes
  ok := numeric.MustBool()

  // Strings / tokens
  s   := randstring.MustString(12)                  // lower-case alnum
  hex := randstring.MustHex(32)                     // 32 hex chars (16 bytes)
  b64 := randstring.MustBase64(24)                  // encodes 24 random bytes
  tok := randstring.MustTokenURLSafe(24)            // URL-safe base64
  
  // Email addresses
  mail := email.MustEmailSimple(16)                 // exact-length local@domain.com
  mail2 := email.MustEmail(email.EmailOptions{TLD: "org"}) // options

  // Collections
  arr := []int{1,2,3,4,5}
  collection.MustShuffle(arr)                       // in-place Fisher–Yates
  top2 := collection.MustSample(arr, 2)             // k without replacement
  pick := collection.MustSlicePickOne(arr)
  pickedMany := collection.MustPickByProbability([]string{"a","b","c"}, 0.5)

  // Time
  t  := randtime.MustDatetime()
  p  := randtime.MustTimeInNearPast()
  fu := randtime.MustTimeInNearFuture()

  // UUIDs
  u4 := uuid.MustV4()
  u7 := uuid.MustV7()

  fmt.Println(n, f, len(b), ok, s, hex, b64, tok, mail, mail2, arr, top2, pick, pickedMany, t, p, fu, u4, u7)
}

Note: Every MustX(...) has a non-panicking X(...) variant that returns (T, error) for use in servers/CLIs where you want to handle errors.

API overview

Numbers

Uniform integers without modulo bias (rejection sampling under the hood), [0,1) float64, and byte helpers. Range functions are inclusive.

  • Uint64()
  • Uint64n(n uint64) → [0,n)
  • Intn(n int), Int64n(n int64) → [0,n)
  • IntRange(min, max), Int32Range, Int64Range (inclusive)
  • AnyInt*, Positive*, Negative*
  • Float64()
  • Bytes(n), Fill(b)
Booleans
  • Bool() / MustBool()
Strings & tokens

Lower-case alnum by default; hex/base64 helpers.

  • String(n) and StringWithCharset(n, charset)
  • Hex(len) where len must be even (2 chars per byte)
  • Base64(byteLen), TokenHex(byteLen), TokenBase64(byteLen), TokenURLSafe(byteLen)
Email addresses

Random email generation with customizable local parts, domains, and TLDs.

  • Email(opts) - Full control with EmailOptions
  • EmailSimple(totalLength) - Legacy exact-length emails
  • EmailWithCustomLocal(localPart)
  • EmailWithCustomDomain(domainPart)
  • EmailWithCustomTLD(tld)
  • EmailWithRandomTLD()
  • EmailWithoutTLD()
Collections (slices)

Unbiased Fisher–Yates shuffle, sampling without replacement, and simple picks.

  • Shuffle[T]([]T)
  • Sample[T]([]T, k) – returns a new slice, no duplicates
  • Perm(n) – random permutation of 0..n-1
  • SlicePickOne[T]([]T)
  • PickByProbability[T]([]T, p float64) – picks each item with prob p (SlicePickMany with 0..100 threshold remains for legacy use)
Time

Calendar-correct random datetimes and near-past/future helpers.

  • Datetime() → between years 1..9999 (UTC), month/day validity handled
  • TimeInNearPast() / TimeInNearFuture() → a few minutes around now

Documentation

Overview

Package randutil provides cryptographically secure random number generation and related utilities organized into focused sub-packages:

  • core: Basic random number generation primitives and entropy source management
  • numeric: Random number generation for various numeric types and booleans
  • randstring: Random string generation and token creation
  • email: Random email address generation with customizable options
  • collection: Random sampling, shuffling, and weighted selection for slices
  • randtime: Random datetime generation functions
  • uuid: UUID generation

All functions use crypto/rand by default for cryptographically secure randomness.

Index

Constants

This section is empty.

Variables

View Source
var Collection = collection.Default

Collection provides access to the default collection generator.

View Source
var Core = core.New(nil)

Core provides access to the default core generator.

View Source
var Email = email.Default

Email provides access to the default email generator.

String provides access to the default string generator.

Time provides access to the default time generator.

View Source
var UUID = uuid.Default

UUID provides access to the default UUID generator.

Functions

This section is empty.

Types

type Rand

type Rand struct {
	// Core provides basic random number generation primitives.
	Core *core.Generator

	// String provides random string and token generation.
	String *randstring.Generator

	// UUID provides UUID v4 and v7 generation.
	UUID *uuid.Generator

	// Collection provides slice operations like shuffle and sampling.
	Collection *collection.Generator

	// Time provides random datetime generation.
	Time *randtime.Generator

	// Email provides random email address generation.
	Email *email.Generator
}

Rand provides access to all default generators from the subpackages, bound to a single entropy source. This eliminates the need to duplicate all the methods from each subpackage.

func Default

func Default() Rand

Default returns a Rand using the current secure source (crypto/rand by default).

Returns:

  • Rand: A new Rand using the current secure source.

func New

func New(src io.Reader) Rand

New returns a Rand with all generators bound to src. Pass nil to use crypto/rand via the package default.

Parameters:

  • src: The entropy source to use.

Returns:

  • Rand: A new Rand with all generators bound to src.

func Secure

func Secure() Rand

Secure is an alias for Default, provided for clarity when the caller wants to emphasize security properties.

Returns:

  • Rand: A new Rand using the current secure source.

func (Rand) Reader

func (r Rand) Reader() io.Reader

Reader exposes the underlying entropy source.

Returns:

  • io.Reader: The current entropy source.

Directories

Path Synopsis
Package collection provides random sampling, shuffling, and weighted selection functions for slices and collections.
Package collection provides random sampling, shuffling, and weighted selection functions for slices and collections.
Package core provides basic random number generation primitives and entropy source management for the randutil package.
Package core provides basic random number generation primitives and entropy source management for the randutil package.
internal
Package numeric provides random number generation functions for various numeric types and boolean values.
Package numeric provides random number generation functions for various numeric types and boolean values.
Package randstring provides random string generation and token helpers.
Package randstring provides random string generation and token helpers.
Package randtime provides random datetime generation functions.
Package randtime provides random datetime generation functions.
Package uuid provides RFC 4122 v4 (random) and RFC 9562 v7 (time-ordered) UUID helpers built on randutil.
Package uuid provides RFC 4122 v4 (random) and RFC 9562 v7 (time-ordered) UUID helpers built on randutil.

Jump to

Keyboard shortcuts

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