/*

Copyright (c) 2002-2005, Yauheni Akhotnikau
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

- Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

- Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.

- The name of the author may not be used to endorse or promote products derived
from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.

*/

#include <stdexcept>

#include <string.h>
#include <stdio.h>

#include <oess_1/defs/h/ex.hpp>

#include <oess_1/defs/log/h/out.hpp>

#include <oess_1/io/h/errno.hpp>
#include <oess_1/io/h/mem_buf.hpp>

using namespace std;

namespace oess_1 {

namespace io {

inline void
expand_buffer(
	auto_ptr_3::vect_ptr_t< char > & buf,
	size_t cur_pos, size_t data_size ) {
	if( cur_pos + data_size >= buf.size() ) {
		// Должен быть увеличен.
		size_t new_capacity = buf.size() + data_size;
		auto_ptr_3::vect_ptr_t< char > new_buf(
			new char[ new_capacity ], new_capacity );

		memcpy( new_buf.query(), buf.query(), buf.size() );
		buf.swap( new_buf );
	}
}

//
// mem_buf_t
//

mem_buf_t::mem_buf_t() :
	m_size( 0 ), m_pos( 0 ) {
	m_buf.set( new char[ e_initial_capacity ],
		e_initial_capacity );
}

mem_buf_t::mem_buf_t(
	size_t capacity ) :
	m_size( 0 ), m_pos( 0 ) {
	m_buf.set( new char[ capacity ], capacity );
}

mem_buf_t::mem_buf_t(
	const mem_buf_t & o ) {
	(*this) = o;
}

mem_buf_t::~mem_buf_t() {
}

mem_buf_t &
mem_buf_t::operator=(
	const mem_buf_t & o ) {
	if( &o != this ) {
		m_buf.destroy();
		m_buf.set( new char[ o.m_buf.size() ],
			o.m_buf.size() );
		memcpy( m_buf.query(), o.m_buf.query(), m_buf.size() );

		m_size = o.m_size;
		m_pos = o.m_pos;
	}

	return *this;
}

size_t
mem_buf_t::capacity() const {
	return m_buf.size();
}

void
mem_buf_t::change_capacity(
	size_t new_capacity,
	bool save_contents ) {
	auto_ptr_3::vect_ptr_t< char > new_buf(
		new char[ new_capacity ], new_capacity );

	if( save_contents ) {
		size_t max_capacity = new_capacity;
		if( max_capacity > m_buf.size() )
			max_capacity = m_buf.size();

		memcpy( new_buf.query(), m_buf.query(),
			max_capacity );
	}

	m_buf.swap( new_buf );
	if( m_size > new_capacity )
		m_size = new_capacity;
	m_pos = 0;
}

size_t
mem_buf_t::size() const {
	return m_size;
}

void
mem_buf_t::change_size(
	size_t new_size ) {
	m_pos = 0;
	if( new_size <= m_buf.size() )
		m_size = new_size;
}

size_t
mem_buf_t::pos() const {
	return m_pos;
}

void
mem_buf_t::set_pos( size_t pos ) {
	if( pos <= m_size )
		m_pos = pos;
}

bool
mem_buf_t::eof() const
{
	return ( pos() == size() );
}

const oess_1::char_t *
mem_buf_t::ptr() const {
	return m_buf.query();
}

const oess_1::char_t *
mem_buf_t::current_ptr() const {
	return ( m_buf.query() + m_pos );
}

void
mem_buf_t::subbuf(
	size_t from_pos,
	mem_buf_t & to,
	size_t to_pos,
	size_t count ) const {
	to.set_pos( to_pos );
	to.write( m_buf.query() + from_pos, count );
}

void
mem_buf_t::subbuf(
	size_t from_pos,
	void * to,
	size_t count ) const {
	memcpy( to, m_buf.query() + from_pos, count );
}

void
mem_buf_t::insert(
	size_t to_pos,
	const mem_buf_t & from,
	size_t from_pos,
	size_t count )
{
	if( to_pos > m_size )
	{
		char tmp[ 96 ];
		sprintf( tmp, "mem_buf_t::insert: to_pos:%u, m_size:%u",
			to_pos, m_size );
		throw std::length_error( tmp );
	}

	expand_buffer( m_buf, m_size, count );
	memmove( m_buf.query() + to_pos + count,
		m_buf.query() + to_pos, m_size - to_pos );
	memcpy( m_buf.query() + to_pos,
		from.m_buf.query() + from_pos, count );

	m_size += count;
	m_pos = 0;
}

void
mem_buf_t::insert(
	size_t to_pos,
	const void * from,
	size_t count )
{
	if( to_pos > m_size )
	{
		char tmp[ 96 ];
		sprintf( tmp, "mem_buf_t::insert: to_pos:%u, m_size:%u",
			to_pos, m_size );
		throw std::length_error( tmp );
	}

	expand_buffer( m_buf, m_size, count );
	memmove( m_buf.query() + to_pos + count,
		m_buf.query() + to_pos, m_size - to_pos );
	memcpy( m_buf.query() + to_pos, from, count );

	m_size += count;
	m_pos = 0;
}

void
mem_buf_t::erase(
	size_t from_offs,
	size_t count )
{
	if( from_offs > m_size )
	{
		char tmp[ 96 ];
		sprintf( tmp, "mem_buf_t::erase: from_offs:%u, m_size:%u",
			from_offs, m_size );
		throw std::length_error( tmp );
	}
	if( count > m_size - from_offs )
	{
		char tmp[ 128 ];
		sprintf( tmp, "mem_buf_t::erase: count:%u, m_size:%u, from_offs:%u",
			count, m_size, from_offs );
		throw std::length_error( tmp );
	}

	memmove( m_buf.query() + from_offs,
		m_buf.query() + from_offs + count,
		m_size - from_offs - count );

	m_size -= count;
	m_pos = 0;
}

void
mem_buf_t::swap(
	mem_buf_t & o ) {

	if( &o != this ) {
		size_t old_size = m_size;
		size_t old_pos = m_pos;

		m_pos = o.m_pos;
		m_size = o.m_size;
		m_buf.swap( o.m_buf );

		o.m_pos = old_pos;
		o.m_size = old_size;
	}
}

const oess_1::char_t *
mem_buf_t::in_reserve(
	size_t item_count,
	size_t item_size,
	size_t & item_available )
{
	// Определяем, сколько полных элементов
	// помещается между текущей позицией и
	// концом данных.
	item_available = ( m_size - m_pos ) / item_size;
	if( !item_available )
		OESS_THROW_LOGIC( oess_1::io::err::c_eof,
			"size: " << m_size << ", pos: " << m_pos
			<< ", item count: " << item_count
			<< ", item size: " << item_size )
	else
		if( item_available > item_count )
			item_available = item_count;

	return m_buf.query() + m_pos;
}

void
mem_buf_t::in_shift(
	size_t item_count,
	size_t item_size )
{
	set_pos( pos() + item_count * item_size );
}

oess_1::char_t *
mem_buf_t::out_reserve(
	size_t item_count,
	size_t item_size,
	size_t & item_available )
{
	// Определяем, сколько элементов может поместиться
	// между текущей позицией и концом буфера.
	expand_buffer( m_buf, m_pos, item_count * item_size );
	item_available = item_count;

	return m_buf.query() + m_pos;
}

void
mem_buf_t::out_shift(
	size_t item_count,
	size_t item_size )
{
	m_pos += item_count * item_size;
	if( m_pos > m_size )
		m_size = m_pos;
}

} /* namespace io */

} /* namespace oess_1 */
