Skip to content

Commit 4592499

Browse files
committed
Improve _size_from_ctrl_byte slightly
This seems to provide a 1-2% performance improvement.
1 parent b5e16c8 commit 4592499

File tree

1 file changed

+12
-11
lines changed

1 file changed

+12
-11
lines changed

maxminddb/decoder.py

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99

1010
import struct
1111

12-
from maxminddb.compat import byte_from_int, int_from_bytes
12+
from maxminddb.compat import byte_from_int, int_from_byte, int_from_bytes
1313
from maxminddb.errors import InvalidDatabaseError
1414

1515

@@ -164,21 +164,22 @@ def _verify_size(self, expected, actual):
164164

165165
def _size_from_ctrl_byte(self, ctrl_byte, offset, type_num):
166166
size = ctrl_byte & 0x1f
167-
if type_num == 1:
167+
if type_num == 1 or size < 29:
168168
return size, offset
169-
bytes_to_read = 0 if size < 29 else size - 28
170-
171-
new_offset = offset + bytes_to_read
172-
size_bytes = self._buffer[offset:new_offset]
173169

174170
# Using unpack rather than int_from_bytes as it is about 200 lookups
175171
# per second faster here.
176172
if size == 29:
177-
size = 29 + struct.unpack(b'!B', size_bytes)[0]
178-
elif size == 30:
173+
size = 29 + int_from_byte(self._buffer[offset])
174+
return size, offset + 1
175+
176+
if size == 30:
177+
new_offset = offset + 2
178+
size_bytes = self._buffer[offset:new_offset]
179179
size = 285 + struct.unpack(b'!H', size_bytes)[0]
180-
elif size > 30:
181-
size = struct.unpack(b'!I', size_bytes.rjust(4,
182-
b'\x00'))[0] + 65821
180+
return size, new_offset
183181

182+
new_offset = offset + 3
183+
size_bytes = self._buffer[offset:new_offset]
184+
size = struct.unpack(b'!I', b'\x00' + size_bytes)[0] + 65821
184185
return size, new_offset

0 commit comments

Comments
 (0)