prefix.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. /* Functions for encoding of integers into prefix codes the amount of extra
  6. bits, and the actual values of the extra bits. */
  7. #ifndef BROTLI_ENC_PREFIX_H_
  8. #define BROTLI_ENC_PREFIX_H_
  9. #include "../common/constants.h"
  10. #include "../common/platform.h"
  11. #include <brotli/types.h>
  12. #include "./fast_log.h"
  13. #if defined(__cplusplus) || defined(c_plusplus)
  14. extern "C" {
  15. #endif
  16. /* Here distance_code is an intermediate code, i.e. one of the special codes or
  17. the actual distance increased by BROTLI_NUM_DISTANCE_SHORT_CODES - 1. */
  18. static BROTLI_INLINE void PrefixEncodeCopyDistance(size_t distance_code,
  19. size_t num_direct_codes,
  20. size_t postfix_bits,
  21. uint16_t* code,
  22. uint32_t* extra_bits) {
  23. if (distance_code < BROTLI_NUM_DISTANCE_SHORT_CODES + num_direct_codes) {
  24. *code = (uint16_t)distance_code;
  25. *extra_bits = 0;
  26. return;
  27. } else {
  28. size_t dist = ((size_t)1 << (postfix_bits + 2u)) +
  29. (distance_code - BROTLI_NUM_DISTANCE_SHORT_CODES - num_direct_codes);
  30. size_t bucket = Log2FloorNonZero(dist) - 1;
  31. size_t postfix_mask = (1u << postfix_bits) - 1;
  32. size_t postfix = dist & postfix_mask;
  33. size_t prefix = (dist >> bucket) & 1;
  34. size_t offset = (2 + prefix) << bucket;
  35. size_t nbits = bucket - postfix_bits;
  36. *code = (uint16_t)((nbits << 10) |
  37. (BROTLI_NUM_DISTANCE_SHORT_CODES + num_direct_codes +
  38. ((2 * (nbits - 1) + prefix) << postfix_bits) + postfix));
  39. *extra_bits = (uint32_t)((dist - offset) >> postfix_bits);
  40. }
  41. }
  42. #if defined(__cplusplus) || defined(c_plusplus)
  43. } /* extern "C" */
  44. #endif
  45. #endif /* BROTLI_ENC_PREFIX_H_ */