Skip to content

Commit

Permalink
Merge pull request #14 from maxpolezhaev/fix-uuid-length-overflow
Browse files Browse the repository at this point in the history
Fix UUID length overflow
  • Loading branch information
lithammer authored Feb 12, 2019
2 parents 6234948 + 8afad84 commit 3d7d0e9
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
4 changes: 3 additions & 1 deletion base57.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,9 +75,11 @@ func (b *base57) stringToNum(s string) (string, error) {

x := fmt.Sprintf("%x", n)

// Pad the most significant bit (MSG) with 0 (zero) if the string is too short.
if len(x) < 32 {
// Pad the most significant bit (MSG) with 0 (zero) if the string is too short.
x = strings.Repeat("0", 32-len(x)) + x
} else if len(x) > 32 {
return "", fmt.Errorf("UUID length overflow for %q", s)
}

return fmt.Sprintf("%s-%s-%s-%s-%s", x[0:8], x[8:12], x[12:16], x[16:20], x[20:32]), nil
Expand Down
22 changes: 22 additions & 0 deletions shortuuid_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,28 @@ func TestDecoding(t *testing.T) {
}
}

func TestDecodingErrors(t *testing.T) {
var (
NotPartOfAlphabetError = "not part of alphabet"
UUIDLengthOverflowError = "UUID length overflow"
)
var tests = []struct {
shortuuid string
error string
}{
{"6B8cwPMGnU6qLbRvo7qEZo", UUIDLengthOverflowError},
{"SiKyfue4VDTKnynXckqVNt", UUIDLengthOverflowError},
{"1lIO022222222222222222", NotPartOfAlphabetError},
{"0a6hrgRGNfQ57QMHZdNYAg", NotPartOfAlphabetError},
}
for _, test := range tests {
_, err := DefaultEncoder.Decode(test.shortuuid)
if err == nil {
t.Errorf("expected %q error for %q", test.error, test.shortuuid)
}
}
}

func TestNewWithAlphabet(t *testing.T) {
abc := DefaultAlphabet[:len(DefaultAlphabet)-1] + "="
enc := base57{newAlphabet(abc)}
Expand Down

0 comments on commit 3d7d0e9

Please sign in to comment.