Skip to content

Commit

Permalink
Add Bytes() function
Browse files Browse the repository at this point in the history
  • Loading branch information
hslatman committed Feb 28, 2022
1 parent 2dc253d commit d67e21a
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
10 changes: 10 additions & 0 deletions randutil/random.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,16 @@ func Salt(size int) ([]byte, error) {
return salt, nil
}

// Bytes generates a new byte slice of the given size.
func Bytes(size int) ([]byte, error) {
bytes := make([]byte, size)
_, err := io.ReadFull(rand.Reader, bytes)
if err != nil {
return nil, errors.Wrap(err, "error generating bytes")
}
return bytes, nil
}

// String returns a random string of a given length using the characters in
// the given string. It splits the string on runes to support UTF-8
// characters.
Expand Down
12 changes: 12 additions & 0 deletions randutil/random_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,18 @@ func TestSalt(t *testing.T) {
}
}

func TestBytes(t *testing.T) {
sizes := []int{4, 8, 16, 32, 64, 128}
for _, size := range sizes {
a, err := Bytes(size)
assert.NoError(t, err)
b, err := Bytes(size)
assert.NoError(t, err)
// Most of the time
assert.NotEquals(t, a, b)
}
}

func TestString(t *testing.T) {
re := regexp.MustCompilePOSIX(`^[0-9世界ñçàèìòù]+$`)
chars := "0123456789世界ñçàèìòù"
Expand Down

0 comments on commit d67e21a

Please sign in to comment.