From 626867d4180a56966006aa6df695eb3a0d19b4e4 Mon Sep 17 00:00:00 2001 From: Harald Ovsthus Date: Fri, 15 Aug 2025 14:42:10 +0200 Subject: [PATCH] algorithms: generate table on init Generate table for table driven CRC on init. This speeds up the python version of table driven CRC check by a factor of six. --- src/pycrc/algorithms.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/pycrc/algorithms.py b/src/pycrc/algorithms.py index 500abb1..c231c61 100644 --- a/src/pycrc/algorithms.py +++ b/src/pycrc/algorithms.py @@ -91,6 +91,8 @@ def __init__(self, width, poly, reflect_in, xor_in, reflect_out, xor_out, else: self.crc_shift = 0 + self.tbl = self.gen_table() + def __get_nondirect_init(self, init): """ return the non-direct init if the direct algorithm has been selected. @@ -211,20 +213,18 @@ def table_driven(self, in_data): if isinstance(in_data, str): in_data = bytearray(in_data, 'utf-8') - tbl = self.gen_table() - if not self.reflect_in: reg = self.direct_init << self.crc_shift for octet in in_data: tblidx = ((reg >> (self.width - self.tbl_idx_width + self.crc_shift)) ^ octet) & 0xff reg = ((reg << (self.tbl_idx_width - self.crc_shift)) ^ - (tbl[0][tblidx] << self.crc_shift)) & (self.mask << self.crc_shift) + (self.tbl[0][tblidx] << self.crc_shift)) & (self.mask << self.crc_shift) reg = reg >> self.crc_shift else: reg = self.reflect(self.direct_init, self.width) for octet in in_data: tblidx = (reg ^ octet) & 0xff - reg = ((reg >> self.tbl_idx_width) ^ tbl[0][tblidx]) & self.mask + reg = ((reg >> self.tbl_idx_width) ^ self.tbl[0][tblidx]) & self.mask reg = self.reflect(reg, self.width) & self.mask if self.reflect_out: