Version: v0.1.0 Latest Latest

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

Go to latest
Published: Jun 25, 2020 License: Apache-2.0 Imports: 4 Imported by: 0



Package rand provides primitives and utilities for generating and working with secure random numbers. Including generating non-uniform random number distributions.



This section is empty.


This section is empty.


func NewCryptoRand

func NewCryptoRand() *mrand.Rand

NewCryptoRand is used to construct a new `math/rand` instance that is backed by `crypto/rand`. This allows the user to securely generate random values, and use the utility methods provided by `math/rand`.


type WeightedRandomEntry

type WeightedRandomEntry struct {
	Character rune
	Weight    float64

WeightedRandomEntry is an entry in the weighted random set.

type WeightedRandomSet

type WeightedRandomSet struct {
	// contains filtered or unexported fields

WeightedRandomSet is a weighted random set that can be used to select elements in a non-uniformally distributed fashion. This will typically be weighted to match the desired composition of a generated password.

The algorithm and data structure used here is based around an interval tree [1] of accumulated weights. We take an unordered collection of entries, and for each entry we insert it into the interval tree in the interval total <= x < total + entry_weight where total is the sum of all of the previous weights already stored in the tree. The insertion order is not important. The end result of this is an interval tree containing a sequence of immediately adjacent intervals of varying width / weight. By generating a random value in the range 0 <= x < total we guarantee an interval exists in the tree which contains the value. The probability that the random value will fall in any individual interval is equal to the ratio of its width to the total width of the tree. This is the mechanism that allows us to weight/bias the resulting random distribution.

[1] https://en.wikipedia.org/wiki/Interval_tree

func NewWeightedRandomSet

func NewWeightedRandomSet(entries []WeightedRandomEntry) WeightedRandomSet

NewWeightedRandomSet is used to construct a new weighted random set from a collection of entries.

func (WeightedRandomSet) Next

func (rs WeightedRandomSet) Next() rune

Next returns the next value in the weighted random sequence.

Jump to

Keyboard shortcuts

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