From 311c071ae60b8246abd4faf58c9c23a94063dd95 Mon Sep 17 00:00:00 2001 From: Pat Whittingslow Date: Mon, 6 Jul 2026 22:35:41 -0300 Subject: [PATCH] add runtime.fastrandn (#5502) --- src/runtime/algorithm.go | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/runtime/algorithm.go b/src/runtime/algorithm.go index fda226c03..cdc0eceb1 100644 --- a/src/runtime/algorithm.go +++ b/src/runtime/algorithm.go @@ -15,6 +15,14 @@ func fastrand() uint32 { return xorshift32State } +// fastrandn is the equivalent of fastrand()%n, but faster. Some packages +// (e.g. wireguard-go's device/timers.go) reach it via +// //go:linkname ... runtime.fastrandn, so it must exist in the runtime. +func fastrandn(n uint32) uint32 { + // See https://lemire.me/blog/2016/06/30/fast-random-shuffling/ + return uint32(uint64(fastrand()) * uint64(n) >> 32) +} + func initRand() { r, _ := hardwareRand() xorshift64State = uint64(r | 1) // protect against 0