import blockwriter_base
import os,mmap

class blockwriter_stream(blockwriter_base.blockwriter_base):
    """
    See blockwriter_base documentation.
    This blockwriter stores blocks linearly, using a buffer. It outputs
    blocks as soon as possible, respecting block numbers.
    It allows "streaming", or on-the-fly handling of data.
    """
    def __init__(self,filename,blocksize,wholeblocks,lastblocksize):
        blockwriter_base.blockwriter_base.__init__(self,filename,blocksize,
                                                   wholeblocks,lastblocksize)
        self.filedesc    = os.open (self.filename,
                                    os.O_RDWR|os.O_CREAT|os.O_TRUNC,0600)
        self.buffers     = {}
        self.nextblock   = 0
    def _putblock(self,blocknumber,data):
        # check if we already had this block
        if blocknumber<self.nextblock:
            print "STREAM: block %d already written."%blocknumber
            return
        # queue block
        self.buffers[blocknumber]=data
        # check if there are blocks to dequeue
        while self.buffers.has_key(self.nextblock):
            os.write(self.filedesc,self.buffers[self.nextblock])
            del self.buffers[self.nextblock]
            self.nextblock += 1

