/*
    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_ATOMICPTRQUEUE_HPP)
#define LIBMAUS2_PARALLEL_ATOMICPTRQUEUE_HPP

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

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

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

			void push(libmaus2::util::shared_ptr<type> T)
			{
				std::lock_guard<decltype(lock)> slock(lock);

				std::size_t const ll = l.load();
				std::size_t const lh = h.load();
				std::size_t const lf = lh - ll;
				std::size_t const ln = n.load();

				if ( lf == ln )
				{
					std::size_t const old_n = ln;
					std::size_t const new_n = old_n ? (2*old_n) : 1;

					libmaus2::util::shared_ptr<
						libmaus2::util::atomic_shared_ptr<type>[]
					> nptr(new libmaus2::util::atomic_shared_ptr<type>[new_n]);

					libmaus2::util::atomic_shared_ptr<type> * tptr = nptr.get();
					libmaus2::util::atomic_shared_ptr<type> * optr = p.load().get();

					for ( std::size_t i = 0; i < lf; ++i )
						tptr[i].store(optr[(ll + i)%ln].load());

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

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

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

				std::size_t const ll = l.load();
				std::size_t const lh = h.load();
				std::size_t const lf = lh - ll;
				std::size_t const ln = n.load();

				if ( ! lf )
					return false;

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

				return true;
			}
		};
	}
}
#endif
