MCPcopy Index your code
hub / github.com/coder/coder / unbiasedModulo32

Function unbiasedModulo32

cryptorand/strings.go:44–68  ·  view source on GitHub ↗

unbiasedModulo32 uniformly modulos v by n over a sufficiently large data set, regenerating v if necessary. n must be > 0. All input bits in v must be fully random, you cannot cast a random uint8/uint16 for input into this function. See more details on this algorithm here: https://lemire.me/blog/201

(v uint32, n int32)

Source from the content-addressed store, hash-verified

42// See more details on this algorithm here:
43// https://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction/
44func unbiasedModulo32(v uint32, n int32) (int32, error) {
45 // #nosec G115 - These conversions are safe within the context of this algorithm
46 // The conversions here are part of an unbiased modulo algorithm for random number generation
47 // where the values are properly handled within their respective ranges.
48 prod := uint64(v) * uint64(n)
49 // #nosec G115 - Safe conversion as part of the unbiased modulo algorithm
50 low := uint32(prod)
51 // #nosec G115 - Safe conversion as part of the unbiased modulo algorithm
52 if low < uint32(n) {
53 // #nosec G115 - Safe conversion as part of the unbiased modulo algorithm
54 thresh := uint32(-n) % uint32(n)
55 for low < thresh {
56 err := binary.Read(rand.Reader, binary.BigEndian, &v)
57 if err != nil {
58 return 0, err
59 }
60 // #nosec G115 - Safe conversion as part of the unbiased modulo algorithm
61 prod = uint64(v) * uint64(n)
62 // #nosec G115 - Safe conversion as part of the unbiased modulo algorithm
63 low = uint32(prod)
64 }
65 }
66 // #nosec G115 - Safe conversion as part of the unbiased modulo algorithm
67 return int32(prod >> 32), nil
68}
69
70// StringCharset generates a random string using the provided charset and size.
71func StringCharset(charSetStr string, size int) (string, error) {

Callers 1

StringCharsetFunction · 0.85

Calls 1

ReadMethod · 0.65

Tested by

no test coverage detected