Skip to content

Commit 7aa3cd8

Browse files
committed
Update leb128.py
1 parent b467867 commit 7aa3cd8

1 file changed

Lines changed: 23 additions & 13 deletions

File tree

pywasm/leb128.py

Lines changed: 23 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -6,18 +6,19 @@ class _U:
66
def encode(i: int) -> bytearray:
77
# Encode the int i using unsigned leb128 and return the encoded bytearray.
88
assert i >= 0
9-
r = []
9+
r = bytearray()
1010
while True:
11-
byte = i & 0x7f
11+
b = i & 0x7f
1212
i = i >> 7
1313
if i == 0:
14-
r.append(byte)
15-
return bytearray(r)
16-
r.append(0x80 | byte)
14+
r.append(b)
15+
return r
16+
r.append(0x80 | b)
1717

1818
@staticmethod
1919
def decode(b: bytearray) -> int:
2020
# Decode the unsigned leb128 encoded bytearray.
21+
assert len(b) > 0
2122
r = 0
2223
for i, e in enumerate(b):
2324
r = r + ((e & 0x7f) << (i * 7))
@@ -29,7 +30,10 @@ def decode_reader(r: typing.BinaryIO) -> typing.Tuple[int, int]:
2930
# of bytes read.
3031
a = bytearray()
3132
while True:
32-
b = ord(r.read(1))
33+
b = r.read(1)
34+
if len(b) != 1:
35+
raise EOFError
36+
b = ord(b)
3337
a.append(b)
3438
if (b & 0x80) == 0:
3539
break
@@ -40,21 +44,24 @@ class _I:
4044
@staticmethod
4145
def encode(i: int) -> bytearray:
4246
# Encode the int i using signed leb128 and return the encoded bytearray.
43-
r = []
47+
r = bytearray()
4448
while True:
45-
byte = i & 0x7f
49+
b = i & 0x7f
4650
i = i >> 7
47-
if (i == 0 and byte & 0x40 == 0) or (i == -1 and byte & 0x40 != 0):
48-
r.append(byte)
49-
return bytearray(r)
50-
r.append(0x80 | byte)
51+
if (i == 0 and b & 0x40 == 0) or (i == -1 and b & 0x40 != 0):
52+
r.append(b)
53+
return r
54+
r.append(0x80 | b)
5155

5256
@staticmethod
5357
def decode(b: bytearray) -> int:
5458
# Decode the signed leb128 encoded bytearray.
59+
assert len(b) > 0
5560
r = 0
5661
for i, e in enumerate(b):
5762
r = r + ((e & 0x7f) << (i * 7))
63+
i = len(b) - 1
64+
e = b[i]
5865
if e & 0x40 != 0:
5966
r |= - (1 << (i * 7) + 7)
6067
return r
@@ -65,7 +72,10 @@ def decode_reader(r: typing.BinaryIO) -> typing.Tuple[int, int]:
6572
# of bytes read.
6673
a = bytearray()
6774
while True:
68-
b = ord(r.read(1))
75+
b = r.read(1)
76+
if len(b) != 1:
77+
raise EOFError
78+
b = ord(b)
6979
a.append(b)
7080
if (b & 0x80) == 0:
7181
break

0 commit comments

Comments
 (0)