bit_ceil.h 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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 >= 17
  20. template <class _Tp>
  21. _LIBCPP_NODISCARD_EXT _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_UNCATEGORIZED(__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 __ret_val = 1u << (__n + __extra);
  31. return (_Tp)(__ret_val >> __extra);
  32. }
  33. }
  34. # if _LIBCPP_STD_VER >= 20
  35. template <__libcpp_unsigned_integer _Tp>
  36. _LIBCPP_NODISCARD_EXT _LIBCPP_HIDE_FROM_ABI constexpr _Tp bit_ceil(_Tp __t) noexcept {
  37. return std::__bit_ceil(__t);
  38. }
  39. # endif // _LIBCPP_STD_VER >= 20
  40. #endif // _LIBCPP_STD_VER >= 17
  41. _LIBCPP_END_NAMESPACE_STD
  42. #endif // _LIBCPP___BIT_BIT_CEIL_H