~seirdy/moac

moac/pwgen/indexing.go -rw-r--r-- 907 bytes
97035daeRohan Kumar Chore(deps): bump deps 7 months ago
                                                                                
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
package pwgen

// indexing contains a bunch of utilities for working with slice indexes:
// finding indexes, inserting at an index, etc.

import (
	"crypto/rand"
	"log"
	"math/big"
	"strings"
)

func randInt(max int) int {
	newInt, err := rand.Int(rand.Reader, big.NewInt(int64(max)))
	if err != nil {
		log.Panicf("cannot generate passwords: crypto/rand unavailable: %v", err)
	}

	return int(newInt.Int64())
}

func addRuneToEnd(password *strings.Builder, runes []rune) {
	newChar := runes[randInt(len(runes))]
	password.WriteRune(newChar)
}

func addRuneAtRandLoc(pwRunes *[]rune, runesToPickFrom []rune) {
	newChar := runesToPickFrom[randInt(len(runesToPickFrom))]
	index := randInt(len(*pwRunes))
	*pwRunes = append((*pwRunes)[:index+1], (*pwRunes)[index:]...)
	(*pwRunes)[index] = newChar
}

func indexOf(src []int, e int) int {
	for i, a := range src {
		if a == e {
			return i
		}
	}

	return -1
}