go-pwgen/pwgen.go
2023-04-25 15:56:11 +02:00

51 lines
1.5 KiB
Go

package pwgen
var (
_ Generator = (*DefaultGenerator)(nil)
Default DefaultGenerator
lowerCase = alphabet('a', 'z')
upperCase = alphabet('A', 'Z')
letters = merge(lowerCase, upperCase)
digits = alphabet('0', '9')
)
type DefaultGenerator struct {
}
func (d DefaultGenerator) Generate(opts ...GeneratorOption) (string, error) {
compiledOptions := defaultOptions(opts...)
fullAlphabet := merge(lowerCase, upperCase, digits, []rune(compiledOptions.SpecialsAlphabet))
effectiveLength, err := compiledOptions.effectiveLength()
if err != nil {
return "", err
}
generated := make([]rune, 0, effectiveLength)
for i := uint(0); i < compiledOptions.Lowercase; i++ {
generated = append(generated, runeFor(lowerCase, compiledOptions.PRNG))
}
for i := uint(0); i < compiledOptions.Uppercase; i++ {
generated = append(generated, runeFor(upperCase, compiledOptions.PRNG))
}
for i := uint(0); i < compiledOptions.Digits; i++ {
generated = append(generated, runeFor(digits, compiledOptions.PRNG))
}
for i := uint(0); i < compiledOptions.Specials; i++ {
generated = append(generated, runeFor([]rune(compiledOptions.SpecialsAlphabet), compiledOptions.PRNG))
}
for i := compiledOptions.Lowercase + compiledOptions.Uppercase; i < compiledOptions.Letters; i++ {
generated = append(generated, runeFor(letters, compiledOptions.PRNG))
}
for i := uint(len(generated)); i < effectiveLength; i++ {
generated = append(generated, runeFor(fullAlphabet, compiledOptions.PRNG))
}
return string(shuffle(generated, compiledOptions.PRNG)), nil
}