prng

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Oct 12, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package prng provides the keyed random streams every generated value is drawn from.

There is no global generator. Each consumer derives its own key from the run's root key and a path of names (the operation's identity, the field, the token), and draws from a ChaCha8 stream seeded with that key. So a value depends only on the seed and its own name: adding, removing or reordering an unrelated operation, field or token never changes it.

The mapping from stream output to values (text, hex, integers in a range, UUIDs) is defined here rather than taken from math/rand, whose derived methods are not promised to stay stable across Go releases. ChaCha8's own output is fixed by its specification (c2sp.org/chacha8rand).

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Key

type Key [32]byte

Key identifies one stream.

func Root

func Root(seed int64) Key

Root is the key for a run with the given seed.

func (Key) Derive

func (k Key) Derive(parts ...string) Key

Derive returns the key for the named child of k. Parts are length-prefixed, so ("ab", "c") and ("a", "bc") name different children.

func (Key) Stream

func (k Key) Stream() *Stream

Stream starts a new stream for k. Two streams from the same key produce the same values.

func (Key) String

func (k Key) String() string

String shows a key in logs and test failures.

type Stream

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

Stream is a sequence of random values. It is not safe for concurrent use; give each goroutine its own key instead.

func (*Stream) Bytes

func (s *Stream) Bytes(n int) []byte

Bytes returns n bytes: each Uint64, little-endian, in turn. The unused bytes of the last word are discarded.

func (*Stream) Hex

func (s *Stream) Hex(n int) string

Hex returns n lowercase hex digits, one per byte (the low four bits).

func (*Stream) IntN

func (s *Stream) IntN(n int) int

IntN returns a uniform integer in [0, n), by rejection sampling. It panics if n <= 0.

func (*Stream) Text

func (s *Stream) Text(n int) string

Text returns n characters from the base32 alphabet, one per byte (the low five bits, which are uniform).

func (*Stream) UUID

func (s *Stream) UUID() string

UUID returns a well-formed RFC 4122 version 4 UUID.

func (*Stream) Uint64

func (s *Stream) Uint64() uint64

Uint64 returns the next 64 bits of the stream.

Jump to

Keyboard shortcuts

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