Skip to content

Commit

Permalink
Parse: do prefix check before len check
Browse files Browse the repository at this point in the history
  • Loading branch information
ucarion committed Oct 23, 2024
1 parent 97d04d6 commit 734f4c8
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 4 deletions.
8 changes: 4 additions & 4 deletions prettyuuid.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,14 +80,14 @@ func (f *Format) Format(uuid [16]byte) string {

// Parse converts a pretty string to a UUID.
func (f *Format) Parse(s string) ([16]byte, error) {
if len(s) != f.len() {
return [16]byte{}, fmt.Errorf("%q does not have expected length %v", s, f.len())
}

if !strings.HasPrefix(s, f.prefix) {
return [16]byte{}, fmt.Errorf("%q does not have expected prefix %q", s, f.prefix)
}

if len(s) != f.len() {
return [16]byte{}, fmt.Errorf("%q does not have expected length %v", s, f.len())
}

var n big.Int
for i := len(f.prefix); i < len(s); i++ {
d := strings.IndexByte(f.alphabet, s[i])
Expand Down
6 changes: 6 additions & 0 deletions prettyuuid_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,12 @@ func TestFormat_Parse(t *testing.T) {
ID: "0000000000000000000000000000000x",
WantErr: `"0000000000000000000000000000000x" contains illegal char at position 31`,
},
{
Name: "bad length and bad prefix",
Format: prettyuuid.MustNewFormat("prefix_", "0123456789abcdef"),
ID: "notprefix_00000000000000000000000000000000x",
WantErr: `"notprefix_00000000000000000000000000000000x" does not have expected prefix "prefix_"`,
},
}

for _, tt := range testCases {
Expand Down

0 comments on commit 734f4c8

Please sign in to comment.