/*
    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_ATOMICSTACK_HPP)
#define LIBMAUS2_PARALLEL_ATOMICSTACK_HPP

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

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

			AtomicStack()
			: p(), f(0), n(0)
			{
			}

			void reset()
			{
				f.store(0);
			}

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

				if ( f.load() == n.load() )
				{
					std::size_t const old_n = n.load();
					std::size_t const new_n = old_n ? 2*old_n : 1;

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

					std::atomic<type> * tptr = nptr.get();
					std::atomic<type> * optr = p.load().get();

					for ( std::size_t i = 0; i < old_n; ++i )
						tptr[i].store(optr[i].load());

					p.store(nptr);
					n.store(new_n);
				}

				(p.load().get())[f++].store(T);
			}

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

				if ( ! f.load() )
					return false;

				T = p.load().get()[--f].load();

				return true;
			}
		};
	}
}
#endif
