ScopeWriter.h

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

#pragma once
#ifndef Ceda_cxUtils_ScopeWriter_H
#define Ceda_cxUtils_ScopeWriter_H

#include "xostream.h"

namespace ceda
{

///////////////////////////////////////////////////////////////////////////////////////////////////
// ScopeWriter

class ScopeWriter
{
    cxNotCloneable(ScopeWriter)
public:
    ScopeWriter(xostream& os, char closingChar = '\0', ssize_t indent = 4) :
        m_os(os),
        m_indent(indent),
        m_closingChar(closingChar)
    {
        m_os << "{\n" << flush;
        m_os.Indent(m_indent);
    }
    
    ~ScopeWriter()
    {    
        m_os.flush(); // must flush any \n's before retracting the indent
        m_os.Indent(-m_indent);
        m_os << '}';
        if (m_closingChar) { m_os << m_closingChar; }
        m_os << '\n';
    }
private:
    xostream& m_os;
    ssize_t m_indent;
    char m_closingChar;
};

// Output of the last linefeed after the '}' in ScopeWriter seems to have been a mistake, 
// this is the preferred version
class ScopeWriter2
{
    cxNotCloneable(ScopeWriter2)
public:
    ScopeWriter2(xostream& os, char closingChar = '\0', ssize_t indent = 4) :
        m_os(os),
        m_indent(indent),
        m_closingChar(closingChar)
    {
        m_os << "{\n" << flush;
        m_os.Indent(m_indent);
    }
    
    ~ScopeWriter2()
    {    
        m_os.flush(); // must flush any \n's before retracting the indent
        m_os.Indent(-m_indent);
        m_os << '}';
        if (m_closingChar) { m_os << m_closingChar; }
    }
private:
    xostream& m_os;
    ssize_t m_indent;
    char m_closingChar;
};


///////////////////////////////////////////////////////////////////////////////////////////////////
// NameSpaceWriter

class NameSpaceWriter
{
    cxNotCloneable(NameSpaceWriter)
public:
    NameSpaceWriter(xostream& os, ConstStringZ name, ssize_t indent = 4) :
        m_os(os),
        m_indent(indent)
    {
        m_os << "namespace " << name << "\n{\n" << flush;
        m_os.Indent(m_indent);
    }
    
    ~NameSpaceWriter()
    {    
        m_os.flush(); // must flush any \n's before retracting the indent
        m_os.Indent(-m_indent);
        m_os << '}' << '\n';
    }
private:
    xostream& m_os;
    ssize_t m_indent;
};

} // namespace ceda

#endif // include guard