import blockwriter_base
import os,mmap

class blockwriter_mmap(blockwriter_base.blockwriter_base):
    """
    See blockwriter_base documentation.
    This blockwriter stores blocks directly into a memory-mapped file.
    The size of mapped files is limited by mmap itself.
    """
    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.filesize    = wholeblocks*blocksize+lastblocksize
        os.lseek (self.filedesc, self.filesize-1, 0) # 0 = SEEK_SET
        os.write (self.filedesc, "%c"%0)
        self.filemap = mmap.mmap (self.filedesc, self.filesize,
                                  prot=mmap.PROT_WRITE)

    def _putblock(self,blocknumber,data):
        begin = blocknumber*self.blocksize
        if blocknumber<self.wholeblocks: end=begin+self.blocksize
        else: end=self.filesize
        self.filemap[begin:end]=data
