File: rand.go

package info (click to toggle)
golang-github-lucas-clemente-quic-go 0.54.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 4,312 kB
  • sloc: sh: 54; makefile: 7
file content (29 lines) | stat: -rw-r--r-- 623 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package utils

import (
	"crypto/rand"
	"encoding/binary"
)

// Rand is a wrapper around crypto/rand that adds some convenience functions known from math/rand.
type Rand struct {
	buf [4]byte
}

func (r *Rand) Int31() int32 {
	rand.Read(r.buf[:])
	return int32(binary.BigEndian.Uint32(r.buf[:]) & ^uint32(1<<31))
}

// copied from the standard library math/rand implementation of Int63n
func (r *Rand) Int31n(n int32) int32 {
	if n&(n-1) == 0 { // n is power of two, can mask
		return r.Int31() & (n - 1)
	}
	max := int32((1 << 31) - 1 - (1<<31)%uint32(n))
	v := r.Int31()
	for v > max {
		v = r.Int31()
	}
	return v % n
}