Skip to content

Commit

Permalink
fix: overflow
Browse files Browse the repository at this point in the history
The ID should not be allowed to overflow an int64
  • Loading branch information
dnephin committed Apr 26, 2022
1 parent 3cf6d89 commit 8274dc1
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
7 changes: 7 additions & 0 deletions snowflake.go
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,9 @@ func ParseBase32(b []byte) (ID, error) {
return -1, ErrInvalidBase32
}
id = id*32 + int64(decodeBase32Map[b[i]])
if id <= 0 {
return -1, ErrInvalidBase32
}
}

return ID(id), nil
Expand Down Expand Up @@ -277,6 +280,10 @@ func ParseBase58(b []byte) (ID, error) {
return -1, ErrInvalidBase58
}
id = id*58 + int64(decodeBase58Map[b[i]])
if id <= 0 {
// overflow!
return -1, ErrInvalidBase58
}
}

return ID(id), nil
Expand Down
16 changes: 16 additions & 0 deletions snowflake_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package snowflake

import (
"bytes"
"fmt"
"reflect"
"testing"
)
Expand Down Expand Up @@ -512,6 +513,12 @@ func TestParseBase32(t *testing.T) {
want: -1,
wantErr: true,
},
{
name: "overflow is invalid",
arg: "byyyyyyyyyyyyy",
want: -1,
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Expand All @@ -525,6 +532,8 @@ func TestParseBase32(t *testing.T) {
}
})
}

fmt.Println(ID(int64(0xfffffffffffffff) + 1).Base32())
}

func TestParseBase58(t *testing.T) {
Expand Down Expand Up @@ -564,7 +573,14 @@ func TestParseBase58(t *testing.T) {
want: -1,
wantErr: true,
},
{
name: "overflow is invalid",
arg: "JPwcyDCgEuq",
want: -1,
wantErr: true,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := ParseBase58([]byte(tt.arg))
Expand Down

0 comments on commit 8274dc1

Please sign in to comment.