forked from dhondta/python-codext
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgzipp.py
More file actions
executable file
·44 lines (32 loc) · 1.13 KB
/
Copy pathgzipp.py
File metadata and controls
executable file
·44 lines (32 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# -*- coding: UTF-8 -*-
"""Gzip Codec - gzip content compression.
NB: Not an encoding properly speaking.
This codec:
- en/decodes strings from str to str
- en/decodes strings from bytes to bytes
- decodes file content to str (read)
- encodes file content from str to bytes (write)
"""
import zlib
from gzip import GzipFile
from ..__common__ import *
__examples__ = {'enc-dec(gzip)': ["test", "This is a test", "@random{512,1024,2048}"]}
def gzip_compress(text, errors="strict"):
out = BytesIO()
with GzipFile(fileobj=out, mode="wb") as f:
f.write(b(text))
return out.getvalue(), len(text)
def gzip_decompress(data, errors="strict"):
# then try decompressing considering the file signature
try:
with GzipFile(fileobj=BytesIO(b(data)), mode="rb") as f:
r = f.read()
except:
pass
# try decompressing without considering the file signature
try:
r = zlib.decompress(b(data), 16 + zlib.MAX_WBITS)
except:
return handle_error("gzip", errors, decode=True)(data[0], 0) if len(data) > 0 else "", len(data)
return r, len(r)
add("gzip", gzip_compress, gzip_decompress)