util.go 708 Bytes
Newer Older
Anders Jensen Løvig's avatar
Anders Jensen Løvig committed
1
2
3
4
package util

import (
	"crypto/rand"
5
	"encoding/binary"
Anders Jensen Løvig's avatar
Anders Jensen Løvig committed
6
7
	"io"
	"math/big"
8
	mathRand "math/rand"
Anders Jensen Løvig's avatar
Anders Jensen Løvig committed
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
)

var one = big.NewInt(1)

// RandInt returns a random integer in the range [1, n).
func RandInt(random io.Reader, n *big.Int) (r *big.Int, err error) {
	tmp := new(big.Int).Set(n)
	tmp.Sub(tmp, one)

	r, err = rand.Int(random, tmp)
	if err != nil {
		return
	}
	r.Add(r, one)

	return
}
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

func Perm(n int) []int {
	return mathRand.New(&cryptoSource{}).Perm(n)
}

type cryptoSource [8]byte

func (s *cryptoSource) Int63() int64 {
	_, err := rand.Read(s[:])
	if err != nil {
		panic(err)
	}
	return int64(binary.BigEndian.Uint64(s[:]) & (1<<63 - 1))
}

func (s *cryptoSource) Seed(seed int64) {
	panic("seed")
}