Add check of truncated length (#5109)

This commit is contained in:
Jim Kalafut 2018-08-15 13:16:17 -07:00 committed by GitHub
parent 1a518deed5
commit d5403f7fe9
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 24 additions and 15 deletions

View file

@ -9,6 +9,9 @@ import (
)
// Encode converts buf into a base62 string
//
// Note: this should only be used for reducing a string's character set range.
// It is not for use with arbitrary data since leading 0 bytes will be dropped.
func Encode(buf []byte) string {
var encoder big.Int
@ -29,15 +32,20 @@ func Decode(input string) []byte {
// 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
}
for {
buf, err := uuid.GenerateRandomBytes(length)
if err != nil {
return "", err
}
result := Encode(buf)
if truncate {
result = result[:length]
}
result := Encode(buf)
return result, nil
if truncate {
if len(result) < length {
continue
}
result = result[:length]
}
return result, nil
}
}

View file

@ -96,14 +96,15 @@ func TestRandom(t *testing.T) {
t.Fatalf("Expected different random values. Got duplicate: %s", a)
}
c, _ := Random(4738, true)
if len(c) != 4738 {
t.Fatalf("Expected length 4738, got: %d", len(c))
for i := 0; i < 3000; i++ {
c, _ := Random(i, true)
if len(c) != i {
t.Fatalf("Expected length %d, got: %d", i, len(c))
}
}
d, _ := Random(100, false)
if len(d) < 134 || len(d) > 135 {
t.Fatalf("Expected length 134 or 135, got: %d", len(d))
if len(d) < 133 || len(d) > 135 {
t.Fatalf("Expected length 133-135, got: %d", len(d))
}
}