diff --git a/id.go b/id.go index 40c8c99..9426dcb 100644 --- a/id.go +++ b/id.go @@ -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 @@ -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. diff --git a/id_test.go b/id_test.go index 6da1e8f..06ccdfc 100644 --- a/id_test.go +++ b/id_test.go @@ -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)