PagedMemoryFile.h

// PagedMemoryFile.h
//
// Author David Barrett-Lennard
// (C)opyright Cedanet Pty Ltd 2004

#pragma once
#ifndef Ceda_cxUtils_PagedMemoryFile_H
#define Ceda_cxUtils_PagedMemoryFile_H

#include "cxUtils.h"
#include "xstring.h"
#include "File.h"
#include "PagedBuffer.h"

namespace ceda
{
class xostream;

///////////////////////////////////////////////////////////////////////////////////////////////////
// PagedMemoryFile

/*
Implementation of a memory file that uses a daisy chained set of pages, allowing it to grow
efficiently

Initially the paged file is ready for writing.  After writing the file has been completed, call 
SeekToBegin() to change the direction to reading, to prepare for reading the file.

The same file can be read many times - simply call SeekToBegin() to read the file again.

Closing the file deletes all its content and puts it back into writing mode.  It is equivalent to 
a freshly constructed PagedMemoryFile.

There is no provision for writing the file, reading it, then continuing to write it from where it left 
off.
*/

class cxUtils_API PagedMemoryFile : public IFile
{
public:
    PagedMemoryFile(ssize_t pageSize = 4096);
    
    // Makes an independent copy of a PagedMemoryFile,  that is in FD_READING mode and the read 
    // position is at the start of the file.
    PagedMemoryFile(const PagedMemoryFile& other);
    PagedMemoryFile& operator=(const PagedMemoryFile& other);

    // Implementation of IInputStream
    virtual ssize_t ReadStream(void* buffer, ssize_t numBytes);

    // Implementation of ISeekableInputStream
    virtual ssize_t GetStreamLength() const;
    virtual ssize_t GetStreamPosition() const;
    virtual void SetStreamPosition(ssize_t pos);

    // Implementation of IOutputInputStream
    virtual void WriteStream(const void* buffer, ssize_t numBytes);
    virtual void FlushStream();
    
    // Implementation of IFile
    virtual void Close();
    virtual EFileDirection Direction() const;

    // Must be called before reading the file can begin.   This function can be called many times
    // to read the file again and again
    void SeekToBegin();

    // Write the entire file to the given string
    void GetString(xstring& s);

private:
    EFileDirection m_direction;
    PagedBuffer m_pb;
    PagedBuffer::Reader m_reader;
};

cxUtils_API xostream& operator<<(xostream& os, const PagedMemoryFile& file);

} // namespace ceda

#endif // include guard