Skip to content

Commit d7bd714

Browse files
committed
Replace compress function with simpler CPython 3.13 variant
1 parent 017f748 commit d7bd714

File tree

1 file changed

+8
-30
lines changed

1 file changed

+8
-30
lines changed

src/zlib_ng/gzip_ng.py

Lines changed: 8 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -180,42 +180,20 @@ def write(self, data):
180180
_GzipNGReader = _GzipReader
181181

182182

183-
def _create_simple_gzip_header(compresslevel: int,
184-
mtime=None) -> bytes:
185-
"""
186-
Write a simple gzip header with no extra fields.
187-
:param compresslevel: Compresslevel used to determine the xfl bytes.
188-
:param mtime: The mtime (must support conversion to a 32-bit integer).
189-
:return: A bytes object representing the gzip header.
190-
"""
191-
if mtime is None:
192-
mtime = time.time()
193-
if compresslevel == _COMPRESS_LEVEL_BEST:
194-
xfl = 2
195-
elif compresslevel == _COMPRESS_LEVEL_FAST:
196-
xfl = 4
197-
else:
198-
xfl = 0
199-
# Pack ID1 and ID2 magic bytes, method (8=deflate), header flags (no extra
200-
# fields added to header), mtime, xfl and os (255 for unknown OS).
201-
return struct.pack("<BBBBLBB", 0x1f, 0x8b, 8, 0, int(mtime), xfl, 255)
202-
203-
204183
def compress(data, compresslevel=_COMPRESS_LEVEL_BEST, *, mtime=None):
205184
"""Compress data in one shot and return the compressed string.
206185
compresslevel sets the compression level in range of 0-9.
207186
mtime can be used to set the modification time. The modification time is
208187
set to the current time by default.
209188
"""
210-
if mtime == 0:
211-
# Use zlib as it creates the header with 0 mtime by default.
212-
# This is faster and with less overhead.
213-
return zlib_ng.compress(data, level=compresslevel, wbits=31)
214-
header = _create_simple_gzip_header(compresslevel, mtime)
215-
trailer = struct.pack("<LL", zlib_ng.crc32(data), (len(data) & 0xffffffff))
216-
# Wbits=-15 creates a raw deflate block.
217-
return (header + zlib_ng.compress(data, level=compresslevel, wbits=-15) +
218-
trailer)
189+
# Wbits=31 automatically includes a gzip header and trailer.
190+
gzip_data = zlib_ng.compress(data, level=compresslevel, wbits=31)
191+
if mtime is None:
192+
mtime = time.time()
193+
# Reuse gzip header created by zlib_ng, replace mtime and OS byte for
194+
# consistency.
195+
header = struct.pack("<4sLBB", gzip_data, int(mtime), gzip_data[8], 255)
196+
return header + gzip_data[10:]
219197

220198

221199
def decompress(data):

0 commit comments

Comments
 (0)