]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/util/consumer.py
4128c2006029e17a37146c95509285916b67b39e
[tahoe-lafs/tahoe-lafs.git] / src / allmydata / util / consumer.py
1
2 """This file defines a basic download-to-memory consumer, suitable for use in
3 a filenode's read() method. See download_to_data() for an example of its use.
4 """
5
6 from zope.interface import implements
7 from twisted.internet.interfaces import IConsumer
8
9 class MemoryConsumer:
10     implements(IConsumer)
11     def __init__(self):
12         self.chunks = []
13         self.done = False
14     def registerProducer(self, p, streaming):
15         self.producer = p
16         if streaming:
17             # call resumeProducing once to start things off
18             p.resumeProducing()
19         else:
20             while not self.done:
21                 p.resumeProducing()
22     def write(self, data):
23         self.chunks.append(data)
24     def unregisterProducer(self):
25         self.done = True
26
27 def download_to_data(n, offset=0, size=None):
28     d = n.read(MemoryConsumer(), offset, size)
29     d.addCallback(lambda mc: "".join(mc.chunks))
30     return d