Add scoped ostream indenter class

This commit is contained in:
Danny Robson 2012-04-12 14:06:26 +10:00
parent 40267cad05
commit f75c514d96
2 changed files with 60 additions and 1 deletions

40
io.cpp
View File

@ -68,10 +68,48 @@ fd_ref::operator int (void) const
{ return fd; }
//----------------------------------------------------------------------------
int
indenter::overflow (int ch) {
if (m_line_start && ch != '\n')
m_dest->sputn (m_indent.data (), sign_cast<std::streamsize> (m_indent.size ()));
m_line_start = ch == '\n';
return m_dest->sputc (ch);
}
indenter::indenter (std::streambuf* _dest, size_t _indent)
: m_dest (_dest)
, m_line_start (true)
, m_indent (_indent, ' ')
, m_owner (NULL)
{ ; }
indenter::indenter (std::ostream& _dest, size_t _indent)
: m_dest (_dest.rdbuf())
, m_line_start (true)
, m_indent (_indent, ' ')
, m_owner (&_dest)
{
m_owner->rdbuf (this);
}
indenter::~indenter ()
{
if (m_owner != NULL)
m_owner->rdbuf (m_dest);
}
//----------------------------------------------------------------------------
#if defined(HAVE_MMAP)
#include <sys/mman.h>
//----------------------------------------------------------------------------
mapped_file::mapped_file (const char *_path):
m_fd (open (_path, O_RDONLY))
{ load_fd (); }

21
io.hpp
View File

@ -21,6 +21,7 @@
#define __UTIL_IO_HPP
#include "annotations.hpp"
#include "types.hpp"
#include <cstdio>
#include <cstdint>
@ -54,6 +55,26 @@ namespace util {
};
class indenter : public std::streambuf
{
protected:
std::streambuf* m_dest;
bool m_line_start;
std::string m_indent;
std::ostream* m_owner;
protected:
virtual int overflow (int ch);
public:
explicit indenter (std::streambuf* _dest, size_t _indent = 4);
explicit indenter (std::ostream& _dest, size_t _indent = 4);
virtual ~indenter ();
};
#if defined(HAVE_MMAP)
/// Wraps a mechanism to map a file into memory. Read only.
class mapped_file {