1
0
Fork 0
mirror of https://github.com/bolero-MURAKAMI/Sprout synced 2024-11-12 21:09:01 +00:00
Sprout/sprout/bit/popcount.hpp

65 lines
1.8 KiB
C++
Raw Normal View History

2013-08-08 09:54:33 +00:00
/*=============================================================================
Copyright (c) 2011-2017 Bolero MURAKAMI
2013-08-08 09:54:33 +00:00
https://github.com/bolero-MURAKAMI/Sprout
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
2012-06-22 13:56:25 +00:00
#ifndef SPROUT_BIT_POPCOUNT_HPP
#define SPROUT_BIT_POPCOUNT_HPP
#include <type_traits>
#include <sprout/config.hpp>
2015-04-04 16:32:49 +00:00
#include <sprout/type_traits/is_signed.hpp>
#include <sprout/type_traits/is_unsigned.hpp>
2012-06-22 13:56:25 +00:00
namespace sprout {
namespace detail {
# if SPROUT_USE_BUILTIN_BIT_OPERATION
inline SPROUT_CONSTEXPR int
popcount(unsigned n) {
return __builtin_popcount(n);
}
inline SPROUT_CONSTEXPR int
popcount(unsigned long n) {
return __builtin_popcountl(n);
}
inline SPROUT_CONSTEXPR int
popcount(unsigned long long n) {
return __builtin_popcountll(n);
}
# endif
2012-12-17 11:10:17 +00:00
template<typename T>
inline SPROUT_CONSTEXPR typename std::enable_if<
sprout::is_unsigned<T>::value,
2012-12-17 11:10:17 +00:00
int
>::type
2012-06-22 13:56:25 +00:00
popcount(T n) {
return n == 0 ? 0
: 1 + sprout::detail::popcount(static_cast<T>(n & (n - 1)))
;
}
2012-12-17 11:10:17 +00:00
template<typename T>
inline SPROUT_CONSTEXPR typename std::enable_if<
sprout::is_signed<T>::value,
2012-12-17 11:10:17 +00:00
int
>::type
2012-06-22 13:56:25 +00:00
popcount(T n) {
return sprout::detail::popcount(static_cast<typename std::make_unsigned<T>::type>(n));
}
} // namespace detail
//
// popcount
//
2012-12-17 11:10:17 +00:00
template<typename T>
inline SPROUT_CONSTEXPR typename std::enable_if<
std::is_integral<T>::value,
int
>::type
2012-06-22 13:56:25 +00:00
popcount(T n) {
return sprout::detail::popcount(n);
}
} // namespace sprout
#endif // #ifndef SPROUT_BIT_POPCOUNT_HPP