~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tuned_gzip.py

  • Committer: Robert Collins
  • Date: 2007-09-13 03:16:07 UTC
  • mto: (2839.1.1 ianc-integration2)
  • mto: This revision was merged to the branch mainline in revision 2841.
  • Revision ID: robertc@robertcollins.net-20070913031607-fit1cj291o8yu1z2
* New helper ``bzrlib.tuned_gzip.bytes_to_gzip`` which takes a byte string
  and returns a gzipped version of the same. This is used to avoid a bunch
  of api friction during adding of knit hunks. (Robert Collins)

Show diffs side-by-side

added added

removed removed

Lines of Context:
29
29
# we want a \n preserved, break on \n only splitlines.
30
30
import bzrlib
31
31
 
32
 
__all__ = ["GzipFile"]
 
32
__all__ = ["GzipFile", "bytes_to_gzip"]
 
33
 
 
34
 
 
35
def bytes_to_gzip(bytes, factory=zlib.compressobj,
 
36
    level=zlib.Z_DEFAULT_COMPRESSION, method=zlib.DEFLATED,
 
37
    width=-zlib.MAX_WBITS, mem=zlib.DEF_MEM_LEVEL,
 
38
    crc32=zlib.crc32):
 
39
    """Create a gzip file containing bytes and return its content."""
 
40
    result = [
 
41
        '\037\213'  # self.fileobj.write('\037\213')  # magic header
 
42
        '\010'      # self.fileobj.write('\010')      # compression method
 
43
                    # fname = self.filename[:-3]
 
44
                    # flags = 0
 
45
                    # if fname:
 
46
                    #     flags = FNAME
 
47
        '\x00'      # self.fileobj.write(chr(flags))
 
48
        '\0\0\0\0'  # write32u(self.fileobj, long(time.time()))
 
49
        '\002'      # self.fileobj.write('\002')
 
50
        '\377'      # self.fileobj.write('\377')
 
51
                    # if fname:
 
52
        ''          #     self.fileobj.write(fname + '\000')
 
53
        ]
 
54
    # using a compressobj avoids a small header and trailer that the compress()
 
55
    # utility function adds.
 
56
    compress = factory(level, method, width, mem, 0)
 
57
    result.append(compress.compress(bytes))
 
58
    result.append(compress.flush())
 
59
    result.append(struct.pack("<L", LOWU32(crc32(bytes))))
 
60
    # size may exceed 2GB, or even 4GB
 
61
    result.append(struct.pack("<L", LOWU32(len(bytes))))
 
62
    return ''.join(result)
33
63
 
34
64
 
35
65
class GzipFile(gzip.GzipFile):