countr.h 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. #if _LIBCPP_STD_VER >= 20
  30. template <__libcpp_unsigned_integer _Tp>
  31. _LIBCPP_NODISCARD_EXT _LIBCPP_HIDE_FROM_ABI constexpr int countr_zero(_Tp __t) noexcept {
  32. if (__t == 0)
  33. return numeric_limits<_Tp>::digits;
  34. if (sizeof(_Tp) <= sizeof(unsigned int))
  35. return std::__libcpp_ctz(static_cast<unsigned int>(__t));
  36. else if (sizeof(_Tp) <= sizeof(unsigned long))
  37. return std::__libcpp_ctz(static_cast<unsigned long>(__t));
  38. else if (sizeof(_Tp) <= sizeof(unsigned long long))
  39. return std::__libcpp_ctz(static_cast<unsigned long long>(__t));
  40. else {
  41. int __ret = 0;
  42. const unsigned int __ulldigits = numeric_limits<unsigned long long>::digits;
  43. while (static_cast<unsigned long long>(__t) == 0uLL) {
  44. __ret += __ulldigits;
  45. __t >>= __ulldigits;
  46. }
  47. return __ret + std::__libcpp_ctz(static_cast<unsigned long long>(__t));
  48. }
  49. }
  50. template <__libcpp_unsigned_integer _Tp>
  51. _LIBCPP_NODISCARD_EXT _LIBCPP_HIDE_FROM_ABI constexpr int countr_one(_Tp __t) noexcept {
  52. return __t != numeric_limits<_Tp>::max() ? std::countr_zero(static_cast<_Tp>(~__t)) : numeric_limits<_Tp>::digits;
  53. }
  54. #endif // _LIBCPP_STD_VER >= 20
  55. _LIBCPP_END_NAMESPACE_STD
  56. _LIBCPP_POP_MACROS
  57. #endif // _LIBCPP___BIT_COUNTR_H