import blockwriter_base,blockreader_lseek
import os,mmap

class blockwriter_lseek(blockwriter_base.blockwriter_base):
    """
    See blockwriter_base documentation.
    This blockwriter stores blocks directly into a file, locating
    the correct offset with lseek. As we don't have (yet) 64-bits
    access in a clean way in Python, we have to do ugly hacks. Yuck.
    """
    def __init__(self,filename,blocksize,wholeblocks,lastblocksize):
        blockwriter_base.blockwriter_base.__init__(self,filename,blocksize,
                                                   wholeblocks,lastblocksize)
        self.filedesc = os.open (filename,os.O_RDWR|os.O_CREAT|os.O_TRUNC,0600)
        self.currentseek = 0 # current position (in blocks)
        self.maxseek = 2000000000/blocksize # max seekable offset (in blocks)
        self.locate(wholeblocks)
        try: os.lseek(self.filedesc,lastblocksize-1,1)
        except OSError: pass
        os.write (self.filedesc, "%c"%0)
        try: os.lseek(self.filedesc,-lastblocksize,1)
        except OSError: pass
    def _putblock(self,blocknumber,data):
        self.locate(blocknumber)
        os.write (self.filedesc,data)
        if len(data) != self.blocksize:
            try: os.lseek(self.filedesc,-len(data),1)
            except OSError: pass
        else: self.currentseek += 1
    # the "locate" method is crudely leeched from the lseek blockreader ! :-P
    locate = blockreader_lseek.blockreader_lseek.__dict__["locate"]
