Skip to content

Commit 789fdcb

Browse files
committed
Merge pull request #171 from cxmcc/lengthEncodedInteger
Fix appendLengthEncodedInteger for large numbers > 0xffffff
2 parents 216197d + 51a8be2 commit 789fdcb

File tree

2 files changed

+43
-2
lines changed

2 files changed

+43
-2
lines changed

utils.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -657,7 +657,7 @@ func readLengthEncodedInteger(b []byte) (uint64, bool, int) {
657657
case 0xfe:
658658
return uint64(b[1]) | uint64(b[2])<<8 | uint64(b[3])<<16 |
659659
uint64(b[4])<<24 | uint64(b[5])<<32 | uint64(b[6])<<40 |
660-
uint64(b[7])<<48 | uint64(b[8])<<54,
660+
uint64(b[7])<<48 | uint64(b[8])<<56,
661661
false, 9
662662
}
663663

@@ -677,5 +677,6 @@ func appendLengthEncodedInteger(b []byte, n uint64) []byte {
677677
case n <= 0xffffff:
678678
return append(b, 0xfd, byte(n), byte(n>>8), byte(n>>16))
679679
}
680-
return b
680+
return append(b, 0xfe, byte(n), byte(n>>8), byte(n>>16), byte(n>>24),
681+
byte(n>>32), byte(n>>40), byte(n>>48), byte(n>>56))
681682
}

utils_test.go

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ package mysql
1111
import (
1212
"fmt"
1313
"testing"
14+
"bytes"
1415
"time"
1516
)
1617

@@ -122,3 +123,42 @@ func TestScanNullTime(t *testing.T) {
122123
}
123124
}
124125
}
126+
127+
func TestLengthEncodedInteger(t *testing.T) {
128+
var integerTests = []struct {
129+
num uint64
130+
encoded []byte
131+
}{
132+
{0x0000000000000000, []byte{0x00}},
133+
{0x0000000000000012, []byte{0x12}},
134+
{0x00000000000000fa, []byte{0xfa}},
135+
{0x0000000000000100, []byte{0xfc, 0x00, 0x01}},
136+
{0x0000000000001234, []byte{0xfc, 0x34, 0x12}},
137+
{0x000000000000ffff, []byte{0xfc, 0xff, 0xff}},
138+
{0x0000000000010000, []byte{0xfd, 0x00, 0x00, 0x01}},
139+
{0x0000000000123456, []byte{0xfd, 0x56, 0x34, 0x12}},
140+
{0x0000000000ffffff, []byte{0xfd, 0xff, 0xff, 0xff}},
141+
{0x0000000001000000, []byte{0xfe, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00}},
142+
{0x123456789abcdef0, []byte{0xfe, 0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12}},
143+
{0xffffffffffffffff, []byte{0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}},
144+
}
145+
146+
for _, tst := range integerTests {
147+
num, isNull, numLen := readLengthEncodedInteger(tst.encoded)
148+
if isNull {
149+
t.Errorf("%x: expected %d, got NULL", tst.encoded, tst.num)
150+
}
151+
if num != tst.num {
152+
t.Errorf("%x: expected %d, got %d", tst.encoded, tst.num, num)
153+
}
154+
if numLen != len(tst.encoded) {
155+
t.Errorf("%x: expected size %d, got %d", tst.encoded, len(tst.encoded), numLen)
156+
}
157+
encoded := appendLengthEncodedInteger(nil, num)
158+
if (!bytes.Equal(encoded, tst.encoded)) {
159+
t.Errorf("%v: expected %x, got %x", num, tst.encoded, encoded)
160+
}
161+
}
162+
163+
164+
}

0 commit comments

Comments
 (0)