~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tuned_gzip.py

  • Committer: Vincent Ladeuil
  • Date: 2010-03-02 10:21:39 UTC
  • mfrom: (4797.2.24 2.1)
  • mto: This revision was merged to the branch mainline in revision 5069.
  • Revision ID: v.ladeuil+lp@free.fr-20100302102139-b5cba7h6xu13mekg
Merge 2.1 into trunk including fixes for #331095, #507557, #185103, #524184 and #369501

Show diffs side-by-side

added added

removed removed

Lines of Context:
13
13
#
14
14
# You should have received a copy of the GNU General Public License
15
15
# along with this program; if not, write to the Free Software
16
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
17
 
18
18
"""Bzrlib specific gzip tunings. We plan to feed these to the upstream gzip."""
19
19
 
21
21
 
22
22
# make GzipFile faster:
23
23
import gzip
24
 
from gzip import U32, LOWU32, FEXTRA, FCOMMENT, FNAME, FHCRC
 
24
from gzip import FEXTRA, FCOMMENT, FNAME, FHCRC
25
25
import sys
26
26
import struct
27
27
import zlib
32
32
__all__ = ["GzipFile", "bytes_to_gzip"]
33
33
 
34
34
 
 
35
def U32(i):
 
36
    """Return i as an unsigned integer, assuming it fits in 32 bits.
 
37
 
 
38
    If it's >= 2GB when viewed as a 32-bit unsigned int, return a long.
 
39
    """
 
40
    if i < 0:
 
41
        i += 1L << 32
 
42
    return i
 
43
 
 
44
 
 
45
def LOWU32(i):
 
46
    """Return the low-order 32 bits of an int, as a non-negative int."""
 
47
    return i & 0xFFFFFFFFL
 
48
 
 
49
 
35
50
def bytes_to_gzip(bytes, factory=zlib.compressobj,
36
51
    level=zlib.Z_DEFAULT_COMPRESSION, method=zlib.DEFLATED,
37
52
    width=-zlib.MAX_WBITS, mem=zlib.DEF_MEM_LEVEL,
38
53
    crc32=zlib.crc32):
39
54
    """Create a gzip file containing bytes and return its content."""
 
55
    return chunks_to_gzip([bytes])
 
56
 
 
57
 
 
58
def chunks_to_gzip(chunks, factory=zlib.compressobj,
 
59
    level=zlib.Z_DEFAULT_COMPRESSION, method=zlib.DEFLATED,
 
60
    width=-zlib.MAX_WBITS, mem=zlib.DEF_MEM_LEVEL,
 
61
    crc32=zlib.crc32):
 
62
    """Create a gzip file containing chunks and return its content.
 
63
 
 
64
    :param chunks: An iterable of strings. Each string can have arbitrary
 
65
        layout.
 
66
    """
40
67
    result = [
41
68
        '\037\213'  # self.fileobj.write('\037\213')  # magic header
42
69
        '\010'      # self.fileobj.write('\010')      # compression method
54
81
    # using a compressobj avoids a small header and trailer that the compress()
55
82
    # utility function adds.
56
83
    compress = factory(level, method, width, mem, 0)
57
 
    result.append(compress.compress(bytes))
 
84
    crc = 0
 
85
    total_len = 0
 
86
    for chunk in chunks:
 
87
        crc = crc32(chunk, crc)
 
88
        total_len += len(chunk)
 
89
        zbytes = compress.compress(chunk)
 
90
        if zbytes:
 
91
            result.append(zbytes)
58
92
    result.append(compress.flush())
59
 
    result.append(struct.pack("<L", LOWU32(crc32(bytes))))
60
93
    # size may exceed 2GB, or even 4GB
61
 
    result.append(struct.pack("<L", LOWU32(len(bytes))))
 
94
    result.append(struct.pack("<LL", LOWU32(crc), LOWU32(total_len)))
62
95
    return ''.join(result)
63
96
 
64
97
 
99
132
        """A tuned version of gzip._write_gzip_header
100
133
 
101
134
        We have some extra constrains that plain Gzip does not.
102
 
        1) We want to write the whole blob at once. rather than multiple 
 
135
        1) We want to write the whole blob at once. rather than multiple
103
136
           calls to fileobj.write().
104
137
        2) We never have a filename
105
138
        3) We don't care about the time
121
154
 
122
155
    def _read(self, size=1024):
123
156
        # various optimisations:
124
 
        # reduces lsprof count from 2500 to 
 
157
        # reduces lsprof count from 2500 to
125
158
        # 8337 calls in 1272, 365 internal
126
159
        if self.fileobj is None:
127
160
            raise EOFError, "Reached EOF"
149
182
 
150
183
        if buf == "":
151
184
            self._add_read_data(self.decompress.flush())
152
 
            assert len(self.decompress.unused_data) >= 8, "what does flush do?"
 
185
            if len(self.decompress.unused_data) < 8:
 
186
                raise AssertionError("what does flush do?")
153
187
            self._gzip_tail = self.decompress.unused_data[0:8]
154
188
            self._read_eof()
155
189
            # tell the driving read() call we have stuffed all the data
175
209
                self._gzip_tail = self.decompress.unused_data[0:8]
176
210
            elif seek_length < 0:
177
211
                # we haven't read enough to check the checksum.
178
 
                assert -8 < seek_length, "too great a seek."
 
212
                if not (-8 < seek_length):
 
213
                    raise AssertionError("too great a seek")
179
214
                buf = self.fileobj.read(-seek_length)
180
215
                self._gzip_tail = self.decompress.unused_data + buf
181
216
            else:
190
225
        """tuned to reduce function calls and eliminate file seeking:
191
226
        pass 1:
192
227
        reduces lsprof count from 800 to 288
193
 
        4168 in 296 
 
228
        4168 in 296
194
229
        avoid U32 call by using struct format L
195
230
        4168 in 200
196
231
        """
197
 
        # We've read to the end of the file, so we should have 8 bytes of 
 
232
        # We've read to the end of the file, so we should have 8 bytes of
198
233
        # unused data in the decompressor. If we don't, there is a corrupt file.
199
234
        # We use these 8 bytes to calculate the CRC and the recorded file size.
200
235
        # We then check the that the computed CRC and size of the
201
236
        # uncompressed data matches the stored values.  Note that the size
202
237
        # stored is the true file size mod 2**32.
203
 
        assert len(self._gzip_tail) == 8, "gzip trailer is incorrect length."
 
238
        if not (len(self._gzip_tail) == 8):
 
239
            raise AssertionError("gzip trailer is incorrect length.")
204
240
        crc32, isize = struct.unpack("<LL", self._gzip_tail)
205
241
        # note that isize is unsigned - it can exceed 2GB
206
242
        if crc32 != U32(self.crc):
210
246
 
211
247
    def _read_gzip_header(self, bytes=None):
212
248
        """Supply bytes if the minimum header size is already read.
213
 
        
 
249
 
214
250
        :param bytes: 10 bytes of header data.
215
251
        """
216
252
        """starting cost: 300 in 3998
253
289
 
254
290
    def readline(self, size=-1):
255
291
        """Tuned to remove buffer length calls in _unread and...
256
 
        
 
292
 
257
293
        also removes multiple len(c) calls, inlines _unread,
258
294
        total savings - lsprof 5800 to 5300
259
295
        phase 2:
263
299
        leading to a drop to:
264
300
        4168 calls in 1977
265
301
        4168 call to read() in 1646
266
 
        - i.e. just reduced the function call overhead. May be worth 
 
302
        - i.e. just reduced the function call overhead. May be worth
267
303
          keeping.
268
304
        """
269
305
        if size < 0: size = sys.maxint
311
347
        # to :
312
348
        # 4168 calls in 417.
313
349
        # Negative numbers result in reading all the lines
314
 
        
 
350
 
315
351
        # python's gzip routine uses sizehint. This is a more efficient way
316
352
        # than python uses to honor it. But it is even more efficient to
317
353
        # just read the entire thing and use cStringIO to split into lines.
324
360
 
325
361
    def _unread(self, buf, len_buf=None):
326
362
        """tuned to remove unneeded len calls.
327
 
        
 
363
 
328
364
        because this is such an inner routine in readline, and readline is
329
365
        in many inner loops, this has been inlined into readline().
330
366
 
331
367
        The len_buf parameter combined with the reduction in len calls dropped
332
 
        the lsprof ms count for this routine on my test data from 800 to 200 - 
 
368
        the lsprof ms count for this routine on my test data from 800 to 200 -
333
369
        a 75% saving.
334
370
        """
335
371
        if len_buf is None:
353
389
            self.offset += data_len
354
390
 
355
391
    def writelines(self, lines):
356
 
        # profiling indicated a significant overhead 
 
392
        # profiling indicated a significant overhead
357
393
        # calling write for each line.
358
394
        # this batch call is a lot faster :).
359
395
        # (4 seconds to 1 seconds for the sample upgrades I was testing).