From 18a6b2c7fa6246117d85e7766c7e4e5e59346ebf Mon Sep 17 00:00:00 2001 From: Gabriel Handford Date: Sat, 6 Mar 2021 12:32:42 -0800 Subject: [PATCH] RandDigits --- bytes.go | 41 +++++++++++++++++++++++++++++++++++++++++ rand.go | 45 ++++++++------------------------------------- rand_test.go | 8 ++++++++ 3 files changed, 57 insertions(+), 37 deletions(-) create mode 100644 bytes.go diff --git a/bytes.go b/bytes.go new file mode 100644 index 0000000..06e815f --- /dev/null +++ b/bytes.go @@ -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 +} diff --git a/rand.go b/rand.go index b23fd93..559281b 100644 --- a/rand.go +++ b/rand.go @@ -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) } diff --git a/rand_test.go b/rand_test.go index 1eca3f9..96b6e1b 100644 --- a/rand_test.go +++ b/rand_test.go @@ -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) +}