clzll.h 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Tencent is pleased to support the open source community by making RapidJSON available.
  2. //
  3. // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip.
  4. //
  5. // Licensed under the MIT License (the "License"); you may not use this file except
  6. // in compliance with the License. You may obtain a copy of the License at
  7. //
  8. // http://opensource.org/licenses/MIT
  9. //
  10. // Unless required by applicable law or agreed to in writing, software distributed
  11. // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  12. // CONDITIONS OF ANY KIND, either express or implied. See the License for the
  13. // specific language governing permissions and limitations under the License.
  14. #ifndef RAPIDJSON_CLZLL_H_
  15. #define RAPIDJSON_CLZLL_H_
  16. #include "../rapidjson.h"
  17. #if defined(_MSC_VER) && !defined(UNDER_CE)
  18. #include <intrin.h>
  19. #if defined(_WIN64)
  20. #pragma intrinsic(_BitScanReverse64)
  21. #else
  22. #pragma intrinsic(_BitScanReverse)
  23. #endif
  24. #endif
  25. RAPIDJSON_NAMESPACE_BEGIN
  26. namespace internal {
  27. inline uint32_t clzll(uint64_t x) {
  28. // Passing 0 to __builtin_clzll is UB in GCC and results in an
  29. // infinite loop in the software implementation.
  30. RAPIDJSON_ASSERT(x != 0);
  31. #if defined(_MSC_VER) && !defined(UNDER_CE)
  32. unsigned long r = 0;
  33. #if defined(_WIN64)
  34. _BitScanReverse64(&r, x);
  35. #else
  36. // Scan the high 32 bits.
  37. if (_BitScanReverse(&r, static_cast<uint32_t>(x >> 32)))
  38. return 63 - (r + 32);
  39. // Scan the low 32 bits.
  40. _BitScanReverse(&r, static_cast<uint32_t>(x & 0xFFFFFFFF));
  41. #endif // _WIN64
  42. return 63 - r;
  43. #elif (defined(__GNUC__) && __GNUC__ >= 4) || RAPIDJSON_HAS_BUILTIN(__builtin_clzll)
  44. // __builtin_clzll wrapper
  45. return static_cast<uint32_t>(__builtin_clzll(x));
  46. #else
  47. // naive version
  48. uint32_t r = 0;
  49. while (!(x & (static_cast<uint64_t>(1) << 63))) {
  50. x <<= 1;
  51. ++r;
  52. }
  53. return r;
  54. #endif // _MSC_VER
  55. }
  56. #define RAPIDJSON_CLZLL RAPIDJSON_NAMESPACE::internal::clzll
  57. } // namespace internal
  58. RAPIDJSON_NAMESPACE_END
  59. #endif // RAPIDJSON_CLZLL_H_