~certify-web-dev/twisted/certify-trunk

« back to all changes in this revision

Viewing changes to twisted/conch/mixin.py

  • Committer: Bazaar Package Importer
  • Author(s): Matthias Klose
  • Date: 2007-01-17 14:52:35 UTC
  • mfrom: (1.1.5 upstream) (2.1.2 etch)
  • Revision ID: james.westby@ubuntu.com-20070117145235-btmig6qfmqfen0om
Tags: 2.5.0-0ubuntu1
New upstream version, compatible with python2.5.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# -*- test-case-name: twisted.conch.test.test_mixin -*-
 
2
# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
 
3
# See LICENSE for details.
 
4
 
 
5
"""Experimental optimization
 
6
 
 
7
This module provides a single mixin class which allows protocols to
 
8
collapse numerous small writes into a single larger one.
 
9
 
 
10
API Stability: Unstable
 
11
 
 
12
@author: U{Jp Calderone<mailto:exarkun@twistedmatrix.com>}
 
13
"""
 
14
 
 
15
from twisted.internet import reactor
 
16
 
 
17
class BufferingMixin:
 
18
    """Mixin which adds write buffering.
 
19
    """
 
20
    _delayedWriteCall = None
 
21
    bytes = None
 
22
 
 
23
    DELAY = 0.0
 
24
 
 
25
    def schedule(self):
 
26
        return reactor.callLater(self.DELAY, self.flush)
 
27
 
 
28
    def reschedule(self, token):
 
29
        token.reset(self.DELAY)
 
30
 
 
31
    def write(self, bytes):
 
32
        """Buffer some bytes to be written soon.
 
33
 
 
34
        Every call to this function delays the real write by C{self.DELAY}
 
35
        seconds.  When the delay expires, all collected bytes are written
 
36
        to the underlying transport using L{ITransport.writeSequence}.
 
37
        """
 
38
        if self._delayedWriteCall is None:
 
39
            self.bytes = []
 
40
            self._delayedWriteCall = self.schedule()
 
41
        else:
 
42
            self.reschedule(self._delayedWriteCall)
 
43
        self.bytes.append(bytes)
 
44
 
 
45
    def flush(self):
 
46
        """Flush the buffer immediately.
 
47
        """
 
48
        self._delayedWriteCall = None
 
49
        self.transport.writeSequence(self.bytes)
 
50
        self.bytes = None