Skip to content

Commit

Permalink
fix implementation of FromString
Browse files Browse the repository at this point in the history
  • Loading branch information
smyrman committed Mar 10, 2022
1 parent f288272 commit c49b848
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
4 changes: 4 additions & 0 deletions error.go
Expand Up @@ -3,6 +3,10 @@ package xid
const (
// ErrInvalidID is returned when trying to unmarshal an invalid ID.
ErrInvalidID strErr = "xid: invalid ID"

// ErrInvalidPadding is returned when trying to unmarshal an ID with invalid
// padding.
ErrInvalidPadding strErr = "xid: invalid padding"
)

// strErr allows declaring errors as constants.
Expand Down
20 changes: 16 additions & 4 deletions id.go
Expand Up @@ -238,8 +238,7 @@ func (id *ID) UnmarshalText(text []byte) error {
return ErrInvalidID
}
}
decode(id, text)
return nil
return decode(id, text)
}

// UnmarshalJSON implements encoding/json Unmarshaler interface
Expand All @@ -256,8 +255,8 @@ func (id *ID) UnmarshalJSON(b []byte) error {
return id.UnmarshalText(b[1 : len(b)-1])
}

// decode by unrolling the stdlib base32 algorithm + removing all safe checks
func decode(id *ID, src []byte) {
// decode by unrolling the stdlib base32 algorithm + customized safe check.
func decode(id *ID, src []byte) error {
_ = src[19]
_ = id[11]

Expand All @@ -273,6 +272,19 @@ func decode(id *ID, src []byte) {
id[2] = dec[src[3]]<<4 | dec[src[4]]>>1
id[1] = dec[src[1]]<<6 | dec[src[2]]<<1 | dec[src[3]]>>4
id[0] = dec[src[0]]<<3 | dec[src[1]]>>2

// Validate that there are no discarer bits (padding) in src that would
// cause the string-encoded id not to equal src.
var check [4]byte

check[3] = encoding[(id[11]<<4)&0x1F]
check[2] = encoding[(id[11]>>1)&0x1F]
check[1] = encoding[(id[11]>>6)&0x1F|(id[10]<<2)&0x1F]
check[0] = encoding[id[10]>>3]
if !bytes.Equal([]byte(src[16:20]), check[:]) {
return ErrInvalidPadding
}
return nil
}

// Time returns the timestamp part of the id.
Expand Down

0 comments on commit c49b848

Please sign in to comment.