Skip to content

Commit

Permalink
#49 fix: generating with size 1
Browse files Browse the repository at this point in the history
Backport updated `getMask` func from v2 to fix inifinite
loop if alphabet size is 1.

Fixes: #49
  • Loading branch information
matoous committed Oct 9, 2024
1 parent 554e6f8 commit 44a7dd3
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 22 deletions.
31 changes: 9 additions & 22 deletions gonanoid.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
)

var defaultAlphabet = []rune("_-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")

const (
defaultSize = 21
defaultMaskSize = 5
Expand All @@ -19,26 +20,13 @@ type Generator func([]byte) (int, error)
// BytesGenerator is the default bytes generator
var BytesGenerator Generator = rand.Read

func initMasks(params ...int) []uint {
var size int
if len(params) == 0 {
size = defaultMaskSize
} else {
size = params[0]
}
masks := make([]uint, size)
for i := 0; i < size; i++ {
shift := 3 + i
masks[i] = (2 << uint(shift)) - 1
}
return masks
}

func getMask(alphabet []rune, masks []uint) int {
for i := 0; i < len(masks); i++ {
curr := int(masks[i])
if curr >= len(alphabet)-1 {
return curr
// getMask generates bit mask used to obtain bits from the random bytes that are used to get index of random character
// from the alphabet. Example: if the alphabet has 6 = (110)_2 characters it is sufficient to use mask 7 = (111)_2
func getMask(alphabetSize int) int {
for i := 1; i <= 8; i++ {
mask := (2 << uint(i)) - 1
if mask >= alphabetSize-1 {
return mask
}
}
return 0
Expand All @@ -55,8 +43,7 @@ func Generate(rawAlphabet string, size int) (string, error) {
return "", fmt.Errorf("size must be positive integer")
}

masks := initMasks(size)
mask := getMask(alphabet, masks)
mask := getMask(len(alphabet))
ceilArg := 1.6 * float64(mask*size) / float64(len(alphabet))
step := int(math.Ceil(ceilArg))

Expand Down
5 changes: 5 additions & 0 deletions gonanoid_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -170,3 +170,8 @@ func TestID(t *testing.T) {
})
}
}

func TestSize1(t *testing.T) {
prefixAlphabet := "abcdefghijklmnopqrstuvwxyz"
_, _ = Generate(prefixAlphabet, 1)
}

0 comments on commit 44a7dd3

Please sign in to comment.