bit_ceil.h 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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_BIT_CEIL_H
  9. #define _LIBCPP___BIT_BIT_CEIL_H
  10. #include <__assert>
  11. #include <__bit/countl.h>
  12. #include <__concepts/arithmetic.h>
  13. #include <__config>
  14. #include <limits>
  15. #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
  16. # pragma GCC system_header
  17. #endif
  18. _LIBCPP_BEGIN_NAMESPACE_STD
  19. #if _LIBCPP_STD_VER >= 20
  20. template <__libcpp_unsigned_integer _Tp>
  21. _LIBCPP_HIDE_FROM_ABI constexpr _Tp bit_ceil(_Tp __t) noexcept {
  22. if (__t < 2)
  23. return 1;
  24. const unsigned __n = numeric_limits<_Tp>::digits - std::countl_zero((_Tp)(__t - 1u));
  25. _LIBCPP_ASSERT(__n != numeric_limits<_Tp>::digits, "Bad input to bit_ceil");
  26. if constexpr (sizeof(_Tp) >= sizeof(unsigned))
  27. return _Tp{1} << __n;
  28. else {
  29. const unsigned __extra = numeric_limits<unsigned>::digits - numeric_limits<_Tp>::digits;
  30. const unsigned __retVal = 1u << (__n + __extra);
  31. return (_Tp)(__retVal >> __extra);
  32. }
  33. }
  34. #endif // _LIBCPP_STD_VER >= 20
  35. _LIBCPP_END_NAMESPACE_STD
  36. #endif // _LIBCPP___BIT_BIT_CEIL_H