/
seed_generator.go
85 lines (71 loc) · 1.5 KB
/
seed_generator.go
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package seed
import (
"crypto/sha256"
"fmt"
"github.com/markbates/pkger"
"io/ioutil"
"math"
"math/rand"
"strconv"
"strings"
"time"
)
type Seed struct {
Code string
Seed int64
}
func New() Seed {
return NewWords(3)
}
func NewPreset(text string) Seed {
seed := computeSeed(text)
return Seed{
Code: text,
Seed: seed,
}
}
func NewWords(number int) Seed {
words := randomWords(number)
text := strings.Join(words, "-")
seed := computeSeed(text)
return Seed{
Code: text,
Seed: seed,
}
}
func computeSeed(words string) int64 {
sha256 := sha256.New()
sha256.Write([]byte(words))
hash := sha256.Sum(nil)
// There are probably faster ways, but for now it suffices. We also ignore overflows, etc. since it's simply important
// that the results are reproducible.
k := fmt.Sprintf("%x", hash)
numbers := k
for _, c := range "abcdef" {
numbers = strings.ReplaceAll(numbers, string(c), "")
}
numbers = numbers[:len(fmt.Sprintf("%d", math.MaxInt64))-1]
seed, err := strconv.ParseInt(numbers, 10, 64)
if err != nil {
panic(err)
}
return seed
}
func randomWords(number int) []string {
f, err := pkger.Open("/assets/words")
if err != nil {
panic(err)
}
file, err := ioutil.ReadAll(f)
if err != nil {
panic(err)
}
rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
words := strings.Split(string(file), "\n")
result := make([]string, number)
for i := 0; i < number; i++ {
result[i] = words[rnd.Int()%len(words)]
result[i] = strings.ToLower(result[i])
}
return result
}