-
Notifications
You must be signed in to change notification settings - Fork 10
Some more-featured Zlib emulation #14
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Scondo
wants to merge
7
commits into
fonttools:master
Choose a base branch
from
Scondo:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
511af67
Some more-featured Zlib emulation
Scondo 2a09d64
Rename argument to match zlib
Scondo d58e06c
Remove most of my old research code, keep only required part
Scondo f67af1f
Change serialization to struct.pack and add few comments
Scondo b5bfcdc
Change header to match zopfli
Scondo cdf5747
Add support for zdict.
Scondo 40c2190
Function ZopfliDeflatePart required for iterative compression, but it…
Scondo File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,14 +1,240 @@ | ||
| from __future__ import absolute_import | ||
|
|
||
| import zopfli | ||
| import zopfli.zopfli | ||
| from struct import pack | ||
| from zlib import adler32 | ||
| from zlib import error | ||
| # This is mostly for compatibility reasons | ||
| from zlib import crc32 | ||
| from zlib import decompress, decompressobj | ||
| ZLIB_RUNTIME_VERSION = '1.2.8' # Mimic old version to guarantee no extra hopes | ||
| ZLIB_VERSION = '1.2.8' # Mimic old version to guarantee no extra hopes | ||
| try: | ||
| from zlib import Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FULL_FLUSH, Z_FINISH | ||
| from zlib import Z_NO_COMPRESSION, Z_BEST_SPEED, Z_BEST_COMPRESSION | ||
| from zlib import Z_DEFAULT_COMPRESSION | ||
| from zlib import DEFLATED, DEF_MEM_LEVEL, MAX_WBITS, DEF_BUF_SIZE | ||
| from zlib import Z_DEFAULT_STRATEGY | ||
| from zlib import Z_FILTERED, Z_HUFFMAN_ONLY, Z_RLE, Z_FIXED | ||
| except ImportError: | ||
| # We can't work without original zlib in fact, | ||
| # but these constants mentioned there to describe their usage | ||
|
|
||
| def compress(data, **kwargs): | ||
| # Flush modes | ||
| Z_NO_FLUSH = 0 | ||
| # Z_PARTIAL_FLUSH = 1 | ||
| Z_SYNC_FLUSH = 2 | ||
| Z_FULL_FLUSH = 3 | ||
| Z_FINISH = 4 | ||
| # Z_BLOCK = 5 | ||
| # Z_TREES = 6 | ||
| # Compression levels. | ||
| Z_NO_COMPRESSION = 0 # no use for now | ||
| Z_BEST_SPEED = 1 | ||
| Z_BEST_COMPRESSION = 9 | ||
| Z_DEFAULT_COMPRESSION = -1 | ||
| # The deflate compression method (the only one supported in this version). | ||
| DEFLATED = 8 | ||
| DEF_MEM_LEVEL = 8 | ||
| DEF_BUF_SIZE = 16384 | ||
| MAX_WBITS = 15 | ||
| # Compression strategy | ||
| # Not used... | ||
| Z_FILTERED = 1 | ||
| Z_HUFFMAN_ONLY = 2 | ||
| Z_RLE = 3 | ||
| Z_FIXED = 4 | ||
| Z_DEFAULT_STRATEGY = 0 | ||
|
|
||
| levit = {-1: 15, | ||
| 0: 1, | ||
| 1: 1, | ||
| 2: 3, | ||
| 3: 5, | ||
| 4: 10, | ||
| 5: 15, | ||
| 6: 20, | ||
| 7: 30, | ||
| 8: 50, | ||
| 9: 100 | ||
| } | ||
| MASTER_BLOCK_SIZE = 20000000 | ||
|
|
||
|
|
||
| def int2bitseq(data, length): | ||
| res = [] # bytearray() | ||
| nowbyte = data | ||
| for _ in range(length): | ||
| (nowbyte, bit) = divmod(nowbyte, 2) | ||
| res.append(bit) | ||
| return res | ||
|
|
||
|
|
||
| def bitseq2int(data): | ||
| res = 0 | ||
| for bit in reversed(data): | ||
| res = bit + res * 2 | ||
| return res | ||
|
|
||
|
|
||
| class compressobj(object): | ||
| def __init__(self, level=Z_DEFAULT_COMPRESSION, method=DEFLATED, | ||
| wbits=MAX_WBITS, memLevel=DEF_MEM_LEVEL, | ||
| strategy=Z_DEFAULT_STRATEGY, zdict=None, **kwargs): | ||
| '''simulate zlib deflateInit2 | ||
| level - compression level | ||
| method - compression method, only DEFLATED supported | ||
| wbits - should be in the range 8..15, practically ignored | ||
| can also be -8..-15 for raw deflate | ||
| zlib also have gz with "Add 16 to windowBit" | ||
| - not implemented here | ||
| memLevel - originally specifies how much memory should be allocated | ||
| zopfli - ignored | ||
| strategy - originally is used to tune the compression algorithm | ||
| zopfli - ignored | ||
| zdict - a predefined compression dictionary, could be used to | ||
| improve compression. Should be specified during decompression. | ||
| ''' | ||
| if method != DEFLATED: | ||
| raise error | ||
| if abs(wbits) > MAX_WBITS or abs(wbits) < 5: | ||
| raise ValueError | ||
| self.crc = None | ||
| self.prehist = bytearray() | ||
| self.closed = False | ||
| self.lastbyte = b'' | ||
| self.bit = 0 | ||
| if zdict: | ||
| self.buf = bytearray(zdict) | ||
| self.opt = {'numiterations': 1} | ||
| self.raw = True | ||
| self.flush(Z_SYNC_FLUSH) # and omit result | ||
| self.zdict = adler32(zdict) | ||
| else: | ||
| self.zdict = False | ||
| self.buf = bytearray() | ||
| self.raw = wbits < 0 | ||
| self.first = True | ||
| self.opt = kwargs | ||
| if 'numiterations' not in self.opt: | ||
| if level in levit: | ||
| self.opt['numiterations'] = levit[level] | ||
| else: | ||
| raise error | ||
|
|
||
| def _header(self): | ||
| cmf = 120 | ||
| flevel = 3 | ||
| fdict = bool(self.zdict) | ||
| cmfflg = 256 * cmf + fdict * 32 + flevel * 64 | ||
| fcheck = 31 - cmfflg % 31 | ||
| cmfflg += fcheck | ||
| return pack('>H', cmfflg) + (pack('>L', self.zdict) if fdict else b'') | ||
|
|
||
| def _updatecrc(self): | ||
| if self.buf is None or self.raw: | ||
| return | ||
| if self.crc is None: | ||
| self.crc = adler32(bytes(self.buf)) | ||
| else: | ||
| self.crc = adler32(bytes(self.buf), self.crc) | ||
|
|
||
| def _compress(self, final=None): | ||
| self._updatecrc() | ||
| blockfinal = 1 if final else 0 | ||
| indata = self.prehist | ||
| prehist = len(self.prehist) | ||
| indata.extend(self.buf) | ||
| self.buf = bytearray() | ||
| self.prehist = indata[-33000:] | ||
| data = zopfli.zopfli.deflate(bytes(indata), | ||
| old_tail=bytes(self.lastbyte), | ||
| bitpointer=self.bit, | ||
| blockfinal=blockfinal, | ||
| prehist=prehist, **self.opt) | ||
| res = bytearray(data[0]) | ||
| self.bit = data[1] | ||
|
|
||
| if final: | ||
| self.lastbyte = b'' | ||
| return res | ||
| else: | ||
| self.lastbyte = res[-32:] | ||
| return res[:-32] | ||
|
|
||
| def compress(self, string): | ||
| global MASTER_BLOCK_SIZE | ||
| self.buf.extend(bytearray(string)) | ||
| if len(self.buf) > MASTER_BLOCK_SIZE: | ||
| out = bytearray() | ||
| if not self.raw and self.first: | ||
| out.extend(self._header()) | ||
| self.first = False | ||
| out.extend(self._compress()) | ||
| return bytes(out) | ||
| else: | ||
| return b'' | ||
|
|
||
| def flush(self, mode=Z_FINISH): | ||
| def encodedalign(prev): | ||
| res = bytearray() | ||
| z = bytearray(prev) | ||
| # Not final, type 00 | ||
| z.extend([0, 0, 0]) | ||
| # if old tail + header cross byte border | ||
| tgtlen = 8 if len(z) <= 8 else 16 | ||
| # Fit to bytes | ||
| addlen = tgtlen - len(z) | ||
| z.extend((0,) * addlen) | ||
| # Add tail and header to result | ||
| res.append(bitseq2int(z[:8])) | ||
| if tgtlen == 16: | ||
| res.append(bitseq2int(z[8:])) | ||
| # zero length as we only want to align, no data | ||
| res.extend(pack('>H', 0)) # LEN | ||
| res.extend(pack('>H', 65535)) # NLEN | ||
| return res | ||
|
|
||
| if self.closed: | ||
| raise error | ||
| out = bytearray() | ||
| self.closed = mode == Z_FINISH | ||
| if not self.raw and self.first: | ||
| out.extend(self._header()) | ||
| self.first = False | ||
| if mode == Z_NO_FLUSH: | ||
| return bytes(out) | ||
| out.extend(self._compress(mode == Z_FINISH)) | ||
| if mode != Z_FINISH: | ||
| self.bit = self.bit % 8 | ||
| # add void fixed block to align data to bytes | ||
| if self.bit: | ||
| work = int2bitseq(self.lastbyte.pop(), 8)[:self.bit] | ||
| else: | ||
| work = [] | ||
| self.lastbyte.extend(encodedalign(work)) | ||
| out.extend(self.lastbyte) | ||
| self.lastbyte = b'' | ||
| self.bit = 0 | ||
| if mode == Z_FULL_FLUSH: | ||
| self.prehist = bytearray() | ||
|
|
||
| if not self.raw and mode == Z_FINISH: | ||
| out.extend(pack('>L', self.crc)) | ||
| return bytes(out) | ||
|
|
||
|
|
||
| def compress(data, level=-1, **kwargs): | ||
| """zlib.compress(data, **kwargs) | ||
| """ + zopfli.__COMPRESSOR_DOCSTRING__ + """ | ||
|
|
||
| """ + zopfli.__COMPRESSOR_DOCSTRING__ + """ | ||
| Returns: | ||
| String containing a zlib container | ||
| """ | ||
| if 'numiterations' not in kwargs: | ||
| if level not in levit: | ||
| raise error | ||
| kwargs['numiterations'] = levit[level] | ||
|
|
||
| kwargs['gzip_mode'] = 0 | ||
| return zopfli.zopfli.compress(data, **kwargs) | ||
| return zopfli.zopfli.compress(bytes(data), **kwargs) | ||
This file contains hidden or 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
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Change this for some unittest.
Maybe change to 'y' in C code will be better solution, but this depends on compatibility with 2.7