/*
    libmaus2
    Copyright (C) 2020 German Tischler-Höhle

    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_GAMMA_GAMMAGENERICCLZ_HPP)
#define LIBMAUS2_GAMMA_GAMMAGENERICCLZ_HPP

#include <climits>

namespace libmaus2
{
	namespace gamma
	{
		template<typename num_type>
		struct GammaGenericClz
		{
			template<typename base_type>
			static unsigned int clz(num_type const n, base_type const & B)
			{
				return CHAR_BIT * sizeof(num_type) - B.getLength(n);
			}
		};

		#if defined(__GNUC__)
		template<>
		struct GammaGenericClz<unsigned char>
		{
			template<typename base_type>
			static unsigned int clz(unsigned int const n, base_type const &)
			{
				return __builtin_clz(n) - CHAR_BIT * (sizeof(unsigned int) - sizeof(unsigned char));
			}
		};

		template<>
		struct GammaGenericClz<unsigned short>
		{
			template<typename base_type>
			static unsigned int clz(unsigned int const n, base_type const &)
			{
				return __builtin_clz(n) - CHAR_BIT * (sizeof(unsigned int) - sizeof(unsigned short));
			}
		};

		template<>
		struct GammaGenericClz<unsigned int>
		{
			template<typename base_type>
			static unsigned int clz(unsigned int const n, base_type const &)
			{
				return __builtin_clz(n);
			}
		};

		template<>
		struct GammaGenericClz<unsigned long>
		{
			template<typename base_type>
			static unsigned int clz(unsigned int const n, base_type const &)
			{
				return __builtin_clzl(n);
			}
		};

		template<>
		struct GammaGenericClz<unsigned long long>
		{
			template<typename base_type>
			static unsigned int clz(unsigned int const n, base_type const &)
			{
				return __builtin_clzll(n);
			}
		};
		#endif
	}
}
#endif
