clzll.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. All rights reserved.
  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)
  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. #if (defined(__GNUC__) && __GNUC__ >= 4) || RAPIDJSON_HAS_BUILTIN(__builtin_clzll)
  28. #define RAPIDJSON_CLZLL __builtin_clzll
  29. #else
  30. inline uint32_t clzll(uint64_t x) {
  31. // Passing 0 to __builtin_clzll is UB in GCC and results in an
  32. // infinite loop in the software implementation.
  33. RAPIDJSON_ASSERT(x != 0);
  34. #if defined(_MSC_VER)
  35. unsigned long r = 0;
  36. #if defined(_WIN64)
  37. _BitScanReverse64(&r, x);
  38. #else
  39. // Scan the high 32 bits.
  40. if (_BitScanReverse(&r, static_cast<uint32_t>(x >> 32)))
  41. return 63 - (r + 32);
  42. // Scan the low 32 bits.
  43. _BitScanReverse(&r, static_cast<uint32_t>(x & 0xFFFFFFFF));
  44. #endif // _WIN64
  45. return 63 - r;
  46. #else
  47. uint32_t r;
  48. while (!(x & (static_cast<uint64_t>(1) << 63))) {
  49. x <<= 1;
  50. ++r;
  51. }
  52. return r;
  53. #endif // _MSC_VER
  54. }
  55. #define RAPIDJSON_CLZLL RAPIDJSON_NAMESPACE::internal::clzll
  56. #endif // (defined(__GNUC__) && __GNUC__ >= 4) || RAPIDJSON_HAS_BUILTIN(__builtin_clzll)
  57. } // namespace internal
  58. RAPIDJSON_NAMESPACE_END
  59. #endif // RAPIDJSON_CLZLL_H_