Skip to content

Commit

Permalink
Just need to check the last byte. (#89)
Browse files Browse the repository at this point in the history
  • Loading branch information
robxyy authored Oct 9, 2022
1 parent 1a49bc0 commit 1b855c3
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 10 deletions.
15 changes: 5 additions & 10 deletions id.go
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,10 @@ func decode(id *ID, src []byte) bool {
_ = id[11]

id[11] = dec[src[17]]<<6 | dec[src[18]]<<1 | dec[src[19]]>>4
// check the last byte
if encoding[(id[11]<<4)&0x1F] != src[19] {
return false
}
id[10] = dec[src[16]]<<3 | dec[src[17]]>>2
id[9] = dec[src[14]]<<5 | dec[src[15]]
id[8] = dec[src[12]]<<7 | dec[src[13]]<<2 | dec[src[14]]>>3
Expand All @@ -276,16 +280,7 @@ func decode(id *ID, src []byte) bool {
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]
return bytes.Equal([]byte(src[16:20]), check[:])
return true
}

// Time returns the timestamp part of the id.
Expand Down
17 changes: 17 additions & 0 deletions id_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,23 @@ func TestIDPartsExtraction(t *testing.T) {
}
}

func TestPadding(t *testing.T) {
for i := 0; i < 100000; i++ {
wantBytes := make([]byte, 20)
wantBytes[19] = encoding[0] // 0
copy(wantBytes[0:13], []byte("c6e52g2mrqcjl")[:]) // c6e52g2mrqcjl44hf170
for j := 0; j < 6; j++ {
wantBytes[13+j] = encoding[rand.Intn(32)]
}
want := string(wantBytes)
id, _ := FromString(want)
got := id.String()
if got != want {
t.Errorf("String() = %v, want %v %v", got, want, wantBytes)
}
}
}

func TestNew(t *testing.T) {
// Generate 10 ids
ids := make([]ID, 10)
Expand Down

0 comments on commit 1b855c3

Please sign in to comment.