/** \file
 *
 *  Contains the MappedIOStream class declaration.
 *
 *  Copyright (c) 2007,2008,2009 MBARI
 *  MBARI Proprietary Information.  All Rights Reserved
 *
 */

#ifndef MAPPEDIOSTREAM_H_
#define MAPPEDIOSTREAM_H_

#include "IOStream.h"

#include <cstdio>
#include <sys/stat.h>

/**
 *  Wraps Memory mapped file with an IOStream class.
 *  Should be faster than MappedIOStream, allocates new files in chunks.
 *
 *  Part of an attempt to avoid the
 *  standard template library
 *
 *  \ingroup io
 */
class MappedIOStream : public IOStream
{
public:

    /// Constructor
    MappedIOStream( const Str& filename, bool clobber, size_t chunkSize );

    virtual ~MappedIOStream();

    void close();

    /// reads num bytes from buffer to the output buffer/stream
    virtual IOStream& read( char* buffer, size_t num );

    bool seek( unsigned int location );

    virtual bool eof();

    bool isReadable()
    {
        return NULL != ptr_;
    }

    const char* getName()
    {
        return filename_.cStr();
    }

    const Str& getFilename()
    {
        return filename_;
    }

    const struct stat getStat();

    /// writes num bytes from buffer to the output buffer/stream
    IOStream& write( const char* buffer, size_t num );

    /// writes zero-terminated buffer to the output buffer/stream
    virtual IOStream& write( const char* buffer )
    {
        return write( buffer, strlen( buffer ) );
    }

    int tell();

    void flush();

    bool open( bool clobber );

    bool isWritable()
    {
        return NULL != ptr_;
    }

protected:

    bool checkSize( size_t num );

    int file_;
    Str filename_;
    size_t chunkSize_;
    size_t size_;
    unsigned char* ptr_;
    size_t pos_; // for ftell and sequential output

private:
    // Note that the copy constructor below is private and not given a body.
    // Any attempt to call it will return a compiler error.
    MappedIOStream( const MappedIOStream& old ); // disallow copy constructor
};

#endif /*MAPPEDIOSTREAM_H_*/
