Created
November 7, 2014 10:23
-
-
Save mengzhuo/cbe3a000d799c8562ac9 to your computer and use it in GitHub Desktop.
String GZIP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# encoding: utf-8 | |
""" | |
GZIP for String | |
https://www.ietf.org/rfc/rfc1952.txt | |
Yes, I know gzip buildin module | |
""" | |
import logging | |
logger = logging.getLogger(__name__) | |
import zlib | |
import struct | |
import time | |
GZIP_HEAD_STRUCT = '>ili' | |
GZIP_FOOT_STRUCT = '<LL' | |
GZIP_MAGIC = 0x1f8b0808 # No FTEXT/FHCRC/FEXTRA/FNAME/FCOMMENT | |
GZIP_XFLOS_MAGIC = 0x00036d00 # compress fast = 4, 03 = UNIX, 6d = filename, 00 end | |
UNSIGNED_32_MASK = 0xffffffffL | |
def encode(data=''): | |
if data: | |
size = len(data) | |
crc = zlib.crc32(data, 0L) | |
gzip_head = struct.pack(GZIP_HEAD_STRUCT, | |
GZIP_MAGIC, | |
long(time.time()), | |
GZIP_XFLOS_MAGIC) | |
print "HEAD", gzip_head.encode('hex') | |
gzip_body = zlib.compress(data) | |
gzip_foot = struct.pack(GZIP_FOOT_STRUCT, | |
crc & UNSIGNED_32_MASK, | |
size & UNSIGNED_32_MASK) | |
print "FOOT", gzip_foot.encode('hex') | |
return gzip_head + gzip_body + gzip_foot | |
return |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment