fast_log.h 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /* Copyright 2013 Google Inc. All Rights Reserved.
  2. Distributed under MIT license.
  3. See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
  4. */
  5. /* Utilities for fast computation of logarithms. */
  6. #ifndef BROTLI_ENC_FAST_LOG_H_
  7. #define BROTLI_ENC_FAST_LOG_H_
  8. #include <math.h>
  9. #include "../common/platform.h"
  10. #include <brotli/types.h>
  11. #if defined(__cplusplus) || defined(c_plusplus)
  12. extern "C" {
  13. #endif
  14. static BROTLI_INLINE uint32_t Log2FloorNonZero(size_t n) {
  15. #if defined(BROTLI_BSR32)
  16. return BROTLI_BSR32((uint32_t)n);
  17. #else
  18. uint32_t result = 0;
  19. while (n >>= 1) result++;
  20. return result;
  21. #endif
  22. }
  23. #define BROTLI_LOG2_TABLE_SIZE 256
  24. /* A lookup table for small values of log2(int) to be used in entropy
  25. computation. */
  26. BROTLI_INTERNAL extern const double kBrotliLog2Table[BROTLI_LOG2_TABLE_SIZE];
  27. /* Visual Studio 2012 and Android API levels < 18 do not have the log2()
  28. * function defined, so we use log() and a multiplication instead. */
  29. #if !defined(BROTLI_HAVE_LOG2)
  30. #if ((defined(_MSC_VER) && _MSC_VER <= 1700) || \
  31. (defined(__ANDROID_API__) && __ANDROID_API__ < 18))
  32. #define BROTLI_HAVE_LOG2 0
  33. #else
  34. #define BROTLI_HAVE_LOG2 1
  35. #endif
  36. #endif
  37. #define LOG_2_INV 1.4426950408889634
  38. /* Faster logarithm for small integers, with the property of log2(0) == 0. */
  39. static BROTLI_INLINE double FastLog2(size_t v) {
  40. if (v < BROTLI_LOG2_TABLE_SIZE) {
  41. return kBrotliLog2Table[v];
  42. }
  43. #if !(BROTLI_HAVE_LOG2)
  44. return log((double)v) * LOG_2_INV;
  45. #else
  46. return log2((double)v);
  47. #endif
  48. }
  49. #if defined(__cplusplus) || defined(c_plusplus)
  50. } /* extern "C" */
  51. #endif
  52. #endif /* BROTLI_ENC_FAST_LOG_H_ */