/*
    libmaus2
    Copyright (C) 2009-2013 German Tischler
    Copyright (C) 2011-2013 Genome Research Limited

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#if ! defined(LIBMAUS2_AIO_COUNTOUTPUTSTREAMBUFFER_HPP)
#define LIBMAUS2_AIO_COUNTOUTPUTSTREAMBUFFER_HPP

#include <ostream>
#include <cmath>

#include <libmaus2/LibMausConfig.hpp>

namespace libmaus2
{
	namespace aio
	{
		struct CountOutputStreamBuffer : public ::std::streambuf
		{
			char B[16];
			uint64_t c;

			void doSync()
			{
				int64_t const n = pptr()-pbase();
				pbump(-n);
				c += n;
			}

			public:
			CountOutputStreamBuffer()
			: c(0)
			{
				setp(&B[0],&B[sizeof(B)]-1);
			}

			int_type overflow(int_type c = traits_type::eof())
			{
				if ( c != traits_type::eof() )
				{
					*pptr() = c;
					pbump(1);
					doSync();
				}

				return c;
			}

			int sync()
			{
				doSync();
				return 0; // no error, -1 for error
			}
		};
	}
}
#endif
