/*
 *
 *
 *    dgqueue.h
 *
 *    C++ source code for queue class for datagram data.
 *
 *    =========================================================================
 *
 *    Copyright (C) 2003 by Matt Roberts, KK5JY.
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License as published by the Free Software Foundation; either
 *    version 2.1 of the License, or (at your option) any later version.
 *
 *    This library 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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 *    =========================================================================
 *
 *
 */


#ifndef __DGQUEUE_H
#define __DGQUEUE_H

#include <queue>

namespace my {
	template <typename T>
		class dgqueue {
			private:
				typedef std::deque<T> queue_t;
				typedef typename queue_t::iterator iterator_t;
				typedef std::deque<iterator_t> iterator_queue_t;

				queue_t data;
				iterator_queue_t limits;

			public:
				dgqueue (void) { /* noop */ };
				~dgqueue (void) { /* noop */ };

				void push (const T *buf, size_t len);
				size_t pop (T *buf, size_t len);

				size_t size (void) const { return limits.size(); };
				size_t size (void)       { return limits.size(); };
		};

	template <typename T>
		inline void dgqueue<T>::push (const T *buf, size_t len) {
			while (len-- > 0)
				data.push_back(*buf++);
			limits.push_back(data.end());
		}

	template <typename T>
		inline size_t dgqueue<T>::pop (T *buf, size_t len) {
			size_t rtn = 0;

			if (limits.size() > 0) {
				/* find the limit of the datagram in the buffer */
				iterator_t limit = limits.front();
				limits.pop_front();

				for (rtn = 0; ( (len-- > 0) && (data.begin() != limit) ); ++rtn) {
					*buf++ = data.front();
					data.pop_front();
				}

				while (data.begin() != limit)
					data.pop_front();
			} else {
				// technically, this is an error, but we just gracefully recover
				for (rtn = 0; (len-- > 0) && (data.size() > 0); ++rtn) {
					*buf++ = data.front();
					data.pop_front();
				}

				// and clear out the contents
				data.clear();
			}

			return rtn;
		}
}

#endif /* __DGQUEUE_H */
