Skip to content

Commit 2c8748c

Browse files
ofekdpkp
authored andcommitted
optimize util.crc32 (#1304)
1 parent 009290d commit 2c8748c

File tree

1 file changed

+15
-8
lines changed

1 file changed

+15
-8
lines changed

kafka/util.py

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,14 +12,21 @@
1212
from kafka.errors import BufferUnderflowError
1313

1414

15-
def crc32(data):
16-
crc = binascii.crc32(data)
17-
# py2 and py3 behave a little differently
18-
# CRC is encoded as a signed int in kafka protocol
19-
# so we'll convert the py3 unsigned result to signed
20-
if six.PY3 and crc >= 2**31:
21-
crc -= 2**32
22-
return crc
15+
if six.PY3:
16+
MAX_INT = 2 ** 31
17+
TO_SIGNED = 2 ** 32
18+
19+
def crc32(data):
20+
crc = binascii.crc32(data)
21+
# py2 and py3 behave a little differently
22+
# CRC is encoded as a signed int in kafka protocol
23+
# so we'll convert the py3 unsigned result to signed
24+
if crc >= MAX_INT:
25+
crc -= TO_SIGNED
26+
return crc
27+
else:
28+
def crc32(data):
29+
return binascii.crc32(data)
2330

2431

2532
def write_int_string(s):

0 commit comments

Comments
 (0)