PagedBufferAsArchive.h

// PagedBufferAsArchive.h
//
// Author David Barrett-Lennard
// (C)opyright Cedanet Pty Ltd 2008

#pragma once
#ifndef Ceda_cxUtils_PagedBufferAsArchive_H
#define Ceda_cxUtils_PagedBufferAsArchive_H

#include "cxUtils.h"
#include "PagedBuffer.h"
#include "PagedBufferAsStream.h"
#include "Archive.h"

namespace ceda
{
///////////////////////////////////////////////////////////////////////////////////////////////////

class OutputArchiveOnPagedBuffer : public Archive
{
public:
    OutputArchiveOnPagedBuffer(PagedBuffer& pb) :
        Archive(&m_os),
        m_os(pb)
    {
    }
    ~OutputArchiveOnPagedBuffer()
    {
        Archive::Flush();
    }

private:
    PagedBufferToOutputStreamAdapter m_os;
};

///////////////////////////////////////////////////////////////////////////////////////////////////
// ContiguousBufferOnPagedBuffer

class ContiguousBufferOnPagedBuffer
{
public:
    ContiguousBufferOnPagedBuffer(PagedBuffer& pb)
    {
        buffer_.resize(pb.GetSize());
        PagedBuffer::Reader reader(pb);
        cxVerify(reader.Read(buffer_.data(), buffer_.size()) == buffer_.size());
    }

    const octet_t* data() const { return buffer_.data(); }
    const octet_t* data_end() const { return buffer_.data() + buffer_.size(); }
    ssize_t size() const { return buffer_.size(); }

private:
    xvector<octet_t> buffer_;
};

template < typename T >
void AssignSerialisable(T& dest, const T& src)
{
    PagedBuffer pb;
    {
        OutputArchiveOnPagedBuffer arOut(pb);
        arOut << src;
    }

    ContiguousBufferOnPagedBuffer buffer(pb);
    InputArchive arIn(buffer.data());
    arIn >> dest;
    cxVerify(arIn == buffer.data_end());
}

} // namespace ceda

#endif // include guard