Skip to content

Latest commit

 

History

History
70 lines (53 loc) · 2.13 KB

README.md

File metadata and controls

70 lines (53 loc) · 2.13 KB

XKCD Rand

A Go utility for fake random number generators.

XKCD comic 221: "Random Number". Licensed for non-commercial use at https://xkcd.com/license.html

Purpose

Code is more testable when it isolates itself from external dependencies. For example, developers can avoid sleeps or timing issues in unit tests if they replace the time library's global methods with a clock library that supports fakes.

Similarly, stochastic algorithms depend on random number generators, which can make unit testing difficult. This library allows developers to fake random numbers generated by the rand.Rand struct.

Usage

Test Code

// A fixed RNG implementation
func getRandomNumber() uint64 {
    // Chosen by fair dice roll. Guaranteed to be random.
    return xkcd.Rand(4).Uint63()
}

var (
  // A repeating sequence RNG
  bitmaskRng = xckd.Rand(0, 1, 2, 4, 8, 16))

  // A sequence that uses floats:
  mixedRng = xkcd.Rand(5, 0.5)

  // Int64s should automatically work with overflows, but
  // you can be explicit by casting to a uint64
  largeRng = xkcd.Rand(uint64(0xFFFFFFFFFFFFFFFF))
)

Production code

// This library creates an object that has the same methods as the `Rand`
// struct in `math.Rand`. Unfortunately the struct is very hard to fake,
// so a matching interface is available at github.com/inlined/rand. This
// package defines an interface compatible with xkcd.Rand and default
// implementations built atop `math/rand`.

import (
  "github.com/inlined/rand"
)

var rng

func() {}
  // Default, unseeded, behavior of the top-level rand library functions:
  // As a global, it's best to use locking. If you have goroutine affinity,
  // you can save mutexes by using rand.New()
  rng = rand.NewLocking()

  // Recommended way to have different behavior across executions:
  rand.NewSource(time.Now().UTC().UnixNano())

Caveats

  1. To avoid type issues, xkcd.Rand can only return uint63 numbers.
  2. Some methods (Read, Seed, Shuffle) are not implemented.