/*
  Copyright (C) 2018 David Robillard <d@drobilla.net>
  Copyright (C) 2006-2007 Chris Hamilton <chamilton@cs.dal.ca>

  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, see <https://www.gnu.org/licenses/>.
*/

#ifndef CHILBERT_STATICBITVEC_HPP
#define CHILBERT_STATICBITVEC_HPP

#include "chilbert/BitVecIndex.hpp"
#include "chilbert/BitVecIterator.hpp"
#include "chilbert/BitVecMask.hpp"
#include "chilbert/MultiBitVec.hpp"
#include "chilbert/Operations.hpp"

#include <algorithm>
#include <array>
#include <cassert>
#include <climits>
#include <cstddef>
#include <cstdlib>
#include <cstring>

namespace chilbert {

template <size_t N>
class StaticBitVec : public MultiBitVec<StaticBitVec<N>>
{
public:
	using Rack = typename MultiBitVec<StaticBitVec<N>>::Rack;

	using MultiBitVec<StaticBitVec<N>>::bits_per_rack;

	StaticBitVec() = default;

	/// Constructor for compatibility with DynamicBitVec
	explicit StaticBitVec(const size_t bits)
	{
		assert(bits == size());
	}

	/// Constructor for compatibility with DynamicBitVec
	StaticBitVec(const size_t bits, const Rack value)
	  : StaticBitVec{bits}
	{
		m_racks[0] = value;
	}

	/// Return the size in bits
	size_t size() const { return N; }

	/// Return a reference to the `index`th rack
#ifndef NDEBUG
	const auto& rack(const size_t index) const { return m_racks.at(index); }
	auto&       rack(const size_t index) { return m_racks.at(index); }
#else
	const auto& rack(const size_t index) const { return m_racks[index]; }
	auto&       rack(const size_t index) { return m_racks[index]; }
#endif

	/// Return a raw pointer to the racks
	Rack*       data() { return m_racks.data(); }
	const Rack* data() const { return m_racks.data(); }

	/// Return the total size of all racks in bytes
	static constexpr size_t data_size() { return num_racks() * sizeof(Rack); }

	/// Return the number of racks
	static constexpr size_t num_racks()
	{
		return (std::max(N, size_t(1)) + bits_per_rack - 1) / bits_per_rack;
	}

private:
	std::array<Rack, num_racks()> m_racks{};
};

template <size_t N>
struct is_bitvec<StaticBitVec<N>>
{
	constexpr static bool value = true;
};

template <size_t N>
void
gray_code(StaticBitVec<N>& value)
{
	gray_code(static_cast<MultiBitVec<StaticBitVec<N>>&>(value));
}

template <size_t N>
void
gray_code_inv(StaticBitVec<N>& value)
{
	gray_code_inv(static_cast<MultiBitVec<StaticBitVec<N>>&>(value));
}

} // namespace chilbert

#endif