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

« back to all changes in this revision

Viewing changes to twisted/vfs/adapters/stream.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
import os
 
2
 
 
3
from zope.interface import implements
 
4
from twisted.web2.stream import SimpleStream, IByteStream
 
5
from twisted.vfs.ivfs import IFileSystemLeaf, VFSError
 
6
from twisted.python import components
 
7
 
 
8
class FileSystemLeafStream(SimpleStream):
 
9
    implements(IByteStream)
 
10
    """A stream that reads data from a FileSystemLeaf."""
 
11
    # 65K, minus some slack
 
12
    CHUNK_SIZE = 2 ** 2 ** 2 ** 2 - 32
 
13
 
 
14
    def __init__(self, leaf, start=0, length=None):
 
15
        """
 
16
        Create the stream from leaf. If you specify start and length,
 
17
        use only that portion of the leaf.
 
18
        """
 
19
        self.leaf = leaf
 
20
        self.leaf.open(os.O_RDONLY)
 
21
        self.start = start
 
22
        if length is None:
 
23
            self.length = leaf.getMetadata()['size']
 
24
        else:
 
25
            self.length = length
 
26
 
 
27
    def read(self):
 
28
        if self.leaf is None:
 
29
            return None
 
30
 
 
31
        length = self.length
 
32
        if length == 0:
 
33
            self.leaf = None
 
34
            return None
 
35
 
 
36
        readSize = min(length, self.CHUNK_SIZE)
 
37
        b = self.leaf.readChunk(self.start, readSize)
 
38
        bytesRead = len(b)
 
39
 
 
40
        if bytesRead != readSize:
 
41
            raise VFSError(
 
42
                ("Ran out of data reading vfs leaf %r, expected %d more bytes,"
 
43
                 " got %d") % (self.leaf, readSize, bytesRead))
 
44
        else:
 
45
            self.length -= bytesRead
 
46
            self.start += bytesRead
 
47
            return b
 
48
 
 
49
    def close(self):
 
50
        self.leaf.close()
 
51
        self.leaf = None
 
52
        SimpleStream.close(self)
 
53
 
 
54
components.registerAdapter(FileSystemLeafStream, IFileSystemLeaf, IByteStream)