countr.h 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. //===----------------------------------------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #ifndef _LIBCPP___BIT_COUNTR_H
  9. #define _LIBCPP___BIT_COUNTR_H
  10. #include <__bit/rotate.h>
  11. #include <__concepts/arithmetic.h>
  12. #include <__config>
  13. #include <limits>
  14. #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
  15. # pragma GCC system_header
  16. #endif
  17. _LIBCPP_PUSH_MACROS
  18. #include <__undef_macros>
  19. _LIBCPP_BEGIN_NAMESPACE_STD
  20. _LIBCPP_NODISCARD inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR
  21. int __libcpp_ctz(unsigned __x) _NOEXCEPT { return __builtin_ctz(__x); }
  22. _LIBCPP_NODISCARD inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR
  23. int __libcpp_ctz(unsigned long __x) _NOEXCEPT { return __builtin_ctzl(__x); }
  24. _LIBCPP_NODISCARD inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR
  25. int __libcpp_ctz(unsigned long long __x) _NOEXCEPT { return __builtin_ctzll(__x); }
  26. #if _LIBCPP_STD_VER >= 20
  27. template <__libcpp_unsigned_integer _Tp>
  28. _LIBCPP_NODISCARD_EXT _LIBCPP_HIDE_FROM_ABI constexpr int countr_zero(_Tp __t) noexcept {
  29. if (__t == 0)
  30. return numeric_limits<_Tp>::digits;
  31. if (sizeof(_Tp) <= sizeof(unsigned int))
  32. return std::__libcpp_ctz(static_cast<unsigned int>(__t));
  33. else if (sizeof(_Tp) <= sizeof(unsigned long))
  34. return std::__libcpp_ctz(static_cast<unsigned long>(__t));
  35. else if (sizeof(_Tp) <= sizeof(unsigned long long))
  36. return std::__libcpp_ctz(static_cast<unsigned long long>(__t));
  37. else {
  38. int __ret = 0;
  39. const unsigned int __ulldigits = numeric_limits<unsigned long long>::digits;
  40. while (static_cast<unsigned long long>(__t) == 0uLL) {
  41. __ret += __ulldigits;
  42. __t >>= __ulldigits;
  43. }
  44. return __ret + std::__libcpp_ctz(static_cast<unsigned long long>(__t));
  45. }
  46. }
  47. template <__libcpp_unsigned_integer _Tp>
  48. _LIBCPP_NODISCARD_EXT _LIBCPP_HIDE_FROM_ABI constexpr int countr_one(_Tp __t) noexcept {
  49. return __t != numeric_limits<_Tp>::max() ? std::countr_zero(static_cast<_Tp>(~__t)) : numeric_limits<_Tp>::digits;
  50. }
  51. #endif // _LIBCPP_STD_VER >= 20
  52. _LIBCPP_END_NAMESPACE_STD
  53. _LIBCPP_POP_MACROS
  54. #endif // _LIBCPP___BIT_COUNTR_H