/***************************************************************************
These C++ classes are copyright 1990, by William Herrera.
All those who put this code or its derivatives in a commercial product MUST
mention this copyright in their documentation for users of the products in
which this code or its derivative classes are used.  Otherwise, this code
may be freely distributed and freely used for any purpose.

Enhancements: 1991 by David Orme
	*  General cleanup.
			- I/O now takes advantage of C++ overloading.
			- Serial port I/O functionality now only in Serial class.
			- Modem functionality now only in Modem class.
	*  Possible to easily implement file Xfr prots now.
	*  CCITT CRC-16 class added							-- 2-20-1991
	*  BIOS Timer class added								-- 2-22-1991
	*  Optional timeout on all input routines added	-- 2-25-1991

***************************************************************************/

// file charqueu.cpp class definitions for CharQueue class.

#include <stdio.h>
#include <stdlib.h>

#include "CharQueu.hpp"

static const char mem_out_err[] = "CharQueue error:  Out of memory";

CharQueue::CharQueue(unsigned int bufsize) 
{
	size = bufsize;
	count = 0;
	queue_buffer = new char[size];
	if(queue_buffer == NULL)
	{
		fputs(mem_out_err, stderr);
		exit(-1);
	}
	add_position = 0;
	get_position = 0;	// get_position chases add_position
}

CharQueue::~CharQueue() 
{ 
	delete queue_buffer; 
}

void CharQueue::Purge() 
{ 
	count = 0; 
	add_position = 0; 
	get_position = 0; 
}

unsigned int CharQueue::GetCount() 
{ 
	return count; 
}

boolean CharQueue::IsFull()	
{ 
	return (count == size) ? true : false; 
}

boolean CharQueue::IsEmpty() 
{ 
	return (count == 0) ? true : false; 
}

int CharQueue::Add(char ch) 
{
	if(count == size)
	{
		fputs(mem_out_err, stderr);
		return 1;					// return 1 for error
	}
	else
	{
		++count;
		queue_buffer[add_position] = ch;
		++add_position;
		if(add_position == size)		// end of queue memory
			add_position = 0;		// so wrap to bottom 
		return 0;					// return 0 for success
	}
}

int CharQueue::Get()
{
	// remove and return next char in line.
	int ch = -1;					// -1 return for empty queue
	if(count > 0)
	{
		count--;
		ch = queue_buffer[get_position] & 0xFF;
		++get_position;
		if(get_position == size)
			get_position = 0;		// wrap to bottom
	}
	return ch;
}

int CharQueue::Peek()
{
	// return current character but don't remove from buffer.
	return (count > 0) ? queue_buffer[get_position] & 0xFF : -1;
}


// end of file CharQueu.cpp
