|
1 | 1 | import struct |
2 | 2 | import zlib |
3 | | -from typing import Literal |
| 3 | +from collections.abc import Callable |
| 4 | +from contextlib import suppress |
| 5 | +from types import ModuleType |
| 6 | +from typing import TYPE_CHECKING, Literal, Optional |
4 | 7 |
|
5 | 8 | import numpy as np |
6 | 9 |
|
7 | 10 | from .abc import Codec |
8 | 11 | from .compat import ensure_contiguous_ndarray, ndarray_copy |
9 | 12 | from .jenkins import jenkins_lookup3 |
10 | 13 |
|
| 14 | +_crc32c: Optional[ModuleType] = None |
| 15 | +with suppress(ImportError): |
| 16 | + import crc32c as _crc32c # type: ignore[no-redef] |
| 17 | + |
| 18 | +if TYPE_CHECKING: # pragma: no cover |
| 19 | + from typing_extensions import Buffer |
| 20 | + |
11 | 21 | CHECKSUM_LOCATION = Literal['start', 'end'] |
12 | 22 |
|
13 | 23 |
|
14 | 24 | class Checksum32(Codec): |
15 | 25 | # override in sub-class |
16 | | - checksum = None |
| 26 | + checksum: Callable[["Buffer", int], int] | None = None |
17 | 27 | location: CHECKSUM_LOCATION = 'start' |
18 | 28 |
|
19 | 29 | def __init__(self, location: CHECKSUM_LOCATION | None = None): |
@@ -72,28 +82,6 @@ class CRC32(Checksum32): |
72 | 82 | location = 'start' |
73 | 83 |
|
74 | 84 |
|
75 | | -class CRC32C(Checksum32): |
76 | | - """Codec add a crc32c checksum to the buffer. |
77 | | -
|
78 | | - Parameters |
79 | | - ---------- |
80 | | - location : 'start' or 'end' |
81 | | - Where to place the checksum in the buffer. |
82 | | - """ |
83 | | - |
84 | | - codec_id = 'crc32c' |
85 | | - |
86 | | - def checksum(self, buf): |
87 | | - try: |
88 | | - from crc32c import crc32c as crc32c_ |
89 | | - |
90 | | - return crc32c_(buf) |
91 | | - except ImportError: # pragma: no cover |
92 | | - raise ImportError("crc32c must be installed to use the CRC32C checksum codec.") |
93 | | - |
94 | | - location = 'end' |
95 | | - |
96 | | - |
97 | 85 | class Adler32(Checksum32): |
98 | 86 | """Codec add a adler32 checksum to the buffer. |
99 | 87 |
|
@@ -164,3 +152,19 @@ def decode(self, buf, out=None): |
164 | 152 | out.view("uint8")[:] = b[:-4] |
165 | 153 | return out |
166 | 154 | return memoryview(b[:-4]) |
| 155 | + |
| 156 | + |
| 157 | +if _crc32c: |
| 158 | + |
| 159 | + class CRC32C(Checksum32): |
| 160 | + """Codec add a crc32c checksum to the buffer. |
| 161 | +
|
| 162 | + Parameters |
| 163 | + ---------- |
| 164 | + location : 'start' or 'end' |
| 165 | + Where to place the checksum in the buffer. |
| 166 | + """ |
| 167 | + |
| 168 | + codec_id = 'crc32c' |
| 169 | + checksum = _crc32c.crc32c # type: ignore[union-attr] |
| 170 | + location = 'end' |
0 commit comments