import blockreader_base
import os,mmap

class blockreader_mmap(blockreader_base.blockreader_base):
    """
    See blockreader_base documentation.
    This blockreader maps a file into memory, using mmap.
    The size of mapped files is limited by mmap itself.
    """
    def __init__(self,filename,blocksize):
        self.filename    = filename
        self.filedesc    = os.open (self.filename,os.O_RDONLY)
        filesize         = os.stat(self.filename)[6]
        blockreader_base.blockreader_base.__init__(self,filesize,blocksize)
        self.filemap     = mmap.mmap (self.filedesc, self.filesize,
                                      prot=mmap.PROT_READ)
    def getblock(self,blocknumber):
        self.checkblock(blocknumber)
        begin = blocknumber*self.blocksize
        if blocknumber<self.filesize/self.blocksize: end=begin+self.blocksize
        else: end=self.filesize
        return self.filemap[begin:end]
