countr.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 int __libcpp_ctz(unsigned __x) _NOEXCEPT {
  21. return __builtin_ctz(__x);
  22. }
  23. _LIBCPP_NODISCARD inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR int __libcpp_ctz(unsigned long __x) _NOEXCEPT {
  24. return __builtin_ctzl(__x);
  25. }
  26. _LIBCPP_NODISCARD inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR int __libcpp_ctz(unsigned long long __x) _NOEXCEPT {
  27. return __builtin_ctzll(__x);
  28. }
  29. template <class _Tp>
  30. _LIBCPP_NODISCARD _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX14 int __countr_zero(_Tp __t) _NOEXCEPT {
  31. if (__t == 0)
  32. return numeric_limits<_Tp>::digits;
  33. if (sizeof(_Tp) <= sizeof(unsigned int))
  34. return std::__libcpp_ctz(static_cast<unsigned int>(__t));
  35. else if (sizeof(_Tp) <= sizeof(unsigned long))
  36. return std::__libcpp_ctz(static_cast<unsigned long>(__t));
  37. else if (sizeof(_Tp) <= sizeof(unsigned long long))
  38. return std::__libcpp_ctz(static_cast<unsigned long long>(__t));
  39. else {
  40. int __ret = 0;
  41. const unsigned int __ulldigits = numeric_limits<unsigned long long>::digits;
  42. while (static_cast<unsigned long long>(__t) == 0uLL) {
  43. __ret += __ulldigits;
  44. __t >>= __ulldigits;
  45. }
  46. return __ret + std::__libcpp_ctz(static_cast<unsigned long long>(__t));
  47. }
  48. }
  49. #if _LIBCPP_STD_VER >= 20
  50. template <__libcpp_unsigned_integer _Tp>
  51. _LIBCPP_NODISCARD_EXT _LIBCPP_HIDE_FROM_ABI constexpr int countr_zero(_Tp __t) noexcept {
  52. return std::__countr_zero(__t);
  53. }
  54. template <__libcpp_unsigned_integer _Tp>
  55. _LIBCPP_NODISCARD_EXT _LIBCPP_HIDE_FROM_ABI constexpr int countr_one(_Tp __t) noexcept {
  56. return __t != numeric_limits<_Tp>::max() ? std::countr_zero(static_cast<_Tp>(~__t)) : numeric_limits<_Tp>::digits;
  57. }
  58. #endif // _LIBCPP_STD_VER >= 20
  59. _LIBCPP_END_NAMESPACE_STD
  60. _LIBCPP_POP_MACROS
  61. #endif // _LIBCPP___BIT_COUNTR_H