/*
Copyright (C) 2006 - 2009 Evan Teran
                   eteran@alum.rit.edu

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 2 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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

#ifndef BYTESTREAM_20060628_H_
#define BYTESTREAM_20060628_H_

#include <cstddef>	// for std::size_t
#include <QtGlobal>

class ByteStream {
public:
	virtual ~ByteStream() {}
	
public:
	typedef std::size_t	size_type;
	typedef quint8		value_type;
	
private:
	class reference {
		friend class ByteStream;
	protected:
		reference(ByteStream &s, size_type i) : m_BS(s), m_Index(i) {}
		
	public:
		~reference() {}
		
		reference &operator=(value_type value) {
			m_BS.write(m_Index, value);
			return *this;
		}
	private:
		ByteStream	&m_BS;
		size_type	m_Index;
	};
	
	class const_iterator {
		friend class ByteStream;
	protected:
		const_iterator(const const_iterator &it) : m_BS(it.m_BS), m_Index(it.m_Index) {
		}
		
		const_iterator(const ByteStream &bs, size_type index) : m_BS(bs), m_Index(index) {
		}

	public:
		const_iterator operator++() { ++m_Index; return *this; }
		const_iterator operator--() { --m_Index; return *this; }
		
		const_iterator operator++(int) {
			const_iterator t(*this);
			++m_Index;
			return t;
		}

		const_iterator operator--(int) {
			const_iterator t(*this);
			--m_Index;
			return t;
		}
		
		value_type operator*() {
			return m_BS[m_Index];
		}

	private:
		const ByteStream	&m_BS;
		size_type			m_Index;
		
	};

public:	// element access	
	value_type operator[](size_type i) const {
		return read(i);
	}
	
	reference operator[](size_type i) {
		return reference(*this, i);
	}
	
	const_iterator begin() const	{ return const_iterator(*this, 0); }
	const_iterator end() const		{ return const_iterator(*this, size()); }
		
public:	// container information
	virtual size_type size() const = 0;
	virtual size_type max_size() const = 0;
	virtual bool empty() const = 0;
	
protected:
	virtual value_type read(size_type i) const = 0;
	virtual void write(size_type i, const value_type &v) = 0;
	
public:
	virtual void clear() = 0;
};

#endif

