Make base62.Random truncation optional (#5100)

This commit is contained in:
Jim Kalafut 2018-08-14 09:38:25 -07:00 committed by Jeff Mitchell
parent 5f86155e6a
commit 09e9a7a203
3 changed files with 20 additions and 7 deletions

View File

@ -25,12 +25,19 @@ func Decode(input string) []byte {
return decoder.Bytes()
}
// Random generates a random base62-encoded string of the given length.
func Random(length int) (string, error) {
// Random generates a random base62-encoded string.
// If truncate is true, the result will be a string of the requested length.
// Otherwise, it will be the encoded result of length bytes of random data.
func Random(length int, truncate bool) (string, error) {
buf, err := uuid.GenerateRandomBytes(length)
if err != nil {
return "", err
}
return Encode(buf)[:length], nil
result := Encode(buf)
if truncate {
result = result[:length]
}
return result, nil
}

View File

@ -85,8 +85,8 @@ func TestInvalid(t *testing.T) {
}
func TestRandom(t *testing.T) {
a, err1 := Random(16)
b, err2 := Random(16)
a, err1 := Random(16, true)
b, err2 := Random(16, true)
if err1 != nil || err2 != nil {
t.Fatalf("Unexpected errors: %v, %v", err1, err2)
@ -96,8 +96,14 @@ func TestRandom(t *testing.T) {
t.Fatalf("Expected different random values. Got duplicate: %s", a)
}
c, _ := Random(4738)
c, _ := Random(4738, true)
if len(c) != 4738 {
t.Fatalf("Expected length 4738, got: %d", len(c))
}
d, _ := Random(100, false)
if len(d) < 134 || len(d) > 135 {
t.Fatalf("Expected length 134 or 135, got: %d", len(d))
}
}

View File

@ -37,7 +37,7 @@ func RandomAlphaNumeric(length int, prependA1a bool) (string, error) {
prefix = reqStr
}
randomStr, err := base62.Random(length - len(prefix))
randomStr, err := base62.Random(length-len(prefix), true)
if err != nil {
return "", err
}