Skip to content

Commit b4a7332

Browse files
authored
Merge pull request #518 from anacrolix/bsi-uuid-fix
Fix flaky TestSetAndGetUUIDValue: big.Int drops leading zero bytes
2 parents 6e38489 + ea854f5 commit b4a7332

File tree

1 file changed

+31
-1
lines changed

1 file changed

+31
-1
lines changed

roaring64/bsi64_test.go

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,12 +86,42 @@ func TestSetAndGetUUIDValue(t *testing.T) {
8686
bv, _ := bsi.GetBigValue(1)
8787
assert.Equal(t, bigUUID, bv)
8888

89-
newUUID, err := uuid.FromBytes(bv.Bytes())
89+
// big.Int.Bytes() drops leading zero bytes; use FillBytes to restore the
90+
// original length so uuid.FromBytes receives exactly len(b) bytes.
91+
bvBytes := make([]byte, len(b))
92+
bv.FillBytes(bvBytes)
93+
newUUID, err := uuid.FromBytes(bvBytes)
9094
assert.Nil(t, err)
9195

9296
assert.Equal(t, uuidVal.String(), newUUID.String())
9397
}
9498

99+
// TestSetAndGetUUIDValueLeadingZero is a deterministic regression test for the
100+
// case where the UUID binary representation has a leading zero byte, which
101+
// big.Int.Bytes() would silently drop.
102+
func TestSetAndGetUUIDValueLeadingZero(t *testing.T) {
103+
// Construct a UUID whose MarshalBinary starts with 0x00.
104+
var uuidVal uuid.UUID
105+
uuidVal[0] = 0x00
106+
uuidVal[6] = 0x40 // version 4
107+
uuidVal[8] = 0x80 // variant bits
108+
b, errx := uuidVal.MarshalBinary()
109+
require.Nil(t, errx)
110+
require.Equal(t, 0x00, int(b[0]), "test requires leading zero byte")
111+
112+
bigUUID := new(big.Int)
113+
bigUUID.SetBytes(b)
114+
bsi := NewDefaultBSI()
115+
bsi.SetBigValue(1, bigUUID)
116+
bv, _ := bsi.GetBigValue(1)
117+
118+
bvBytes := make([]byte, len(b))
119+
bv.FillBytes(bvBytes)
120+
newUUID, err := uuid.FromBytes(bvBytes)
121+
assert.Nil(t, err)
122+
assert.Equal(t, uuidVal.String(), newUUID.String())
123+
}
124+
95125
func secondsAndNanosToBigInt(seconds int64, nanos int32) *big.Int {
96126
b := make([]byte, 12)
97127
binary.BigEndian.PutUint64(b[:8], uint64(seconds))

0 commit comments

Comments
 (0)