/*
    libmaus2
    Copyright (C) 2021 German Tischler

    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_PARALLEL_ATOMICQUEUE_HPP)
#define LIBMAUS2_PARALLEL_ATOMICQUEUE_HPP

#include <libmaus2/util/atomic_shared_ptr.hpp>
#include <mutex>

namespace libmaus2
{
	namespace parallel
	{
		template<typename type>
		struct AtomicQueue
		{
			std::mutex lock;
			libmaus2::util::atomic_shared_ptr<
				std::atomic<type>[]
			> p;
			std::atomic<std::size_t> l;
			std::atomic<std::size_t> h;
			std::atomic<std::size_t> n;

			AtomicQueue()
			: p(), l(0), h(0), n(0)
			{
			}

			void push(type const & T)
			{
				std::lock_guard<decltype(lock)> slock(lock);

				// current fill state
				std::size_t const f = h.load() - l.load();

				// if queue is full
				if ( f == n.load() )
				{
					// old size
					std::size_t const old_n = n.load();
					// new size
					std::size_t const new_n = old_n ? 2*old_n : 1;

					// allocate new array
					libmaus2::util::shared_ptr<
						std::atomic<type>[]
					> nptr(new std::atomic<type>[new_n]);

					// get array pointers for new and old
					std::atomic<type> * tptr = nptr.get();
					std::atomic<type> * optr = p.load().get();

					// low pointer in old array
					std::size_t const ll = l.load();

					// copy elements
					for ( std::size_t i = 0; i < f; ++i )
						tptr[i].store(
							optr[(ll + i) % old_n].load()
						);

					p.store(nptr);
					n.store(new_n);
					l.store(0);
					h.store(f);
				}

				// add new object
				(p.load().get())[h++ % n.load()].store(T);
			}

			bool pop(type & T)
			{
				std::lock_guard<decltype(lock)> slock(lock);

				std::size_t const f = h.load() - l.load();

				if ( ! f )
					return false;

				T = p.load().get()[l++ % n.load()].load();

				return true;
			}
		};
	}
}
#endif
