Skip to content

Commit 67b6748

Browse files
committed
Segregate CRC16.get_table() from CRC16.calculate() (mjg59#567)
1 parent 4e1e690 commit 67b6748

1 file changed

Lines changed: 13 additions & 8 deletions

File tree

broadlink/helpers.py

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import typing as t
33

44

5-
class CRC16: # pylint: disable=R0903
5+
class CRC16:
66
"""Helps with CRC-16 calculation.
77
88
CRC tables are cached for performance.
@@ -11,13 +11,8 @@ class CRC16: # pylint: disable=R0903
1111
_cache = {}
1212

1313
@classmethod
14-
def calculate(
15-
cls,
16-
sequence: t.Sequence[int],
17-
polynomial: int = 0xA001, # Modbus CRC-16.
18-
init_value: int = 0xFFFF,
19-
) -> int:
20-
"""Calculate the CRC-16 of a sequence of integers."""
14+
def get_table(cls, polynomial: int):
15+
"""Return the CRC-16 table for a polynomial."""
2116
try:
2217
crc_table = cls._cache[polynomial]
2318
except KeyError:
@@ -31,7 +26,17 @@ def calculate(
3126
remainder = remainder >> 1
3227
crc_table.append(remainder)
3328
cls._cache[polynomial] = crc_table
29+
return crc_table
3430

31+
@classmethod
32+
def calculate(
33+
cls,
34+
sequence: t.Sequence[int],
35+
polynomial: int = 0xA001, # CRC-16-ANSI.
36+
init_value: int = 0xFFFF,
37+
) -> int:
38+
"""Calculate the CRC-16 of a sequence of integers."""
39+
crc_table = cls.get_table(polynomial)
3540
crc = init_value
3641
for item in sequence:
3742
crc = crc >> 8 ^ crc_table[(crc ^ item) & 0xFF]

0 commit comments

Comments
 (0)