Skip to content

Commit

Permalink
RandDigits
Browse files Browse the repository at this point in the history
  • Loading branch information
gabriel committed Mar 6, 2021
1 parent 1625591 commit 18a6b2c
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 37 deletions.
41 changes: 41 additions & 0 deletions bytes.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package keys

// Bytes64 converts byte slice to *[64]byte or panics.
func Bytes64(b []byte) *[64]byte {
if len(b) != 64 {
panic("not 64 bytes")
}
var b64 [64]byte
copy(b64[:], b)
return &b64
}

// Bytes32 converts byte slice to *[32]byte or panics.
func Bytes32(b []byte) *[32]byte {
if len(b) != 32 {
panic("not 32 bytes")
}
var b32 [32]byte
copy(b32[:], b)
return &b32
}

// Bytes24 converts byte slice to *[24]byte or panics.
func Bytes24(b []byte) *[24]byte {
if len(b) != 24 {
panic("not 24 bytes")
}
var b24 [24]byte
copy(b24[:], b)
return &b24
}

// Bytes16 converts byte slice to *[16]byte or panics.
func Bytes16(b []byte) *[16]byte {
if len(b) != 16 {
panic("not 16 bytes")
}
var b16 [16]byte
copy(b16[:], b)
return &b16
}
45 changes: 8 additions & 37 deletions rand.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,42 +95,13 @@ func RandFileName() string {
return encoding.MustEncode(RandBytes(16), encoding.Base32, encoding.NoPadding())
}

// Bytes64 converts byte slice to *[64]byte.
func Bytes64(b []byte) *[64]byte {
if len(b) != 64 {
panic("not 64 bytes")
}
var b64 [64]byte
copy(b64[:], b)
return &b64
}

// Bytes32 converts byte slice to *[32]byte.
func Bytes32(b []byte) *[32]byte {
if len(b) != 32 {
panic("not 32 bytes")
}
var b32 [32]byte
copy(b32[:], b)
return &b32
}

// Bytes24 converts byte slice to *[24]byte.
func Bytes24(b []byte) *[24]byte {
if len(b) != 24 {
panic("not 24 bytes")
}
var b24 [24]byte
copy(b24[:], b)
return &b24
}

// Bytes16 converts byte slice to *[16]byte.
func Bytes16(b []byte) *[16]byte {
if len(b) != 16 {
panic("not 16 bytes")
// RandDigits returns string of random digits of length.
// RandDigits(6) => "745566"
func RandDigits(length int) string {
charSet := numbers
b := make([]byte, 0, length)
for i := 0; i < length; i++ {
b = append(b, randomChar(charSet, b))
}
var b16 [16]byte
copy(b16[:], b)
return &b16
return string(b)
}
8 changes: 8 additions & 0 deletions rand_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,11 @@ func TestRandTempPath(t *testing.T) {
p2 := keys.RandTempPath()
require.NotEqual(t, p, p2)
}

func TestRandDigits(t *testing.T) {
p := keys.RandDigits(10)
require.NotEmpty(t, p)
t.Logf("%s", p)
p2 := keys.RandDigits(10)
require.NotEqual(t, p, p2)
}

0 comments on commit 18a6b2c

Please sign in to comment.