find_match_length.h 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /* Copyright 2010 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. /* Function to find maximal matching prefixes of strings. */
  6. #ifndef BROTLI_ENC_FIND_MATCH_LENGTH_H_
  7. #define BROTLI_ENC_FIND_MATCH_LENGTH_H_
  8. #include "../common/platform.h"
  9. #include <brotli/types.h>
  10. #if defined(__cplusplus) || defined(c_plusplus)
  11. extern "C" {
  12. #endif
  13. /* Separate implementation for little-endian 64-bit targets, for speed. */
  14. #if defined(__GNUC__) && defined(_LP64) && defined(BROTLI_LITTLE_ENDIAN)
  15. static BROTLI_INLINE size_t FindMatchLengthWithLimit(const uint8_t* s1,
  16. const uint8_t* s2,
  17. size_t limit) {
  18. size_t matched = 0;
  19. size_t limit2 = (limit >> 3) + 1; /* + 1 is for pre-decrement in while */
  20. while (BROTLI_PREDICT_TRUE(--limit2)) {
  21. if (BROTLI_PREDICT_FALSE(BROTLI_UNALIGNED_LOAD64LE(s2) ==
  22. BROTLI_UNALIGNED_LOAD64LE(s1 + matched))) {
  23. s2 += 8;
  24. matched += 8;
  25. } else {
  26. uint64_t x = BROTLI_UNALIGNED_LOAD64LE(s2) ^
  27. BROTLI_UNALIGNED_LOAD64LE(s1 + matched);
  28. size_t matching_bits = (size_t)__builtin_ctzll(x);
  29. matched += matching_bits >> 3;
  30. return matched;
  31. }
  32. }
  33. limit = (limit & 7) + 1; /* + 1 is for pre-decrement in while */
  34. while (--limit) {
  35. if (BROTLI_PREDICT_TRUE(s1[matched] == *s2)) {
  36. ++s2;
  37. ++matched;
  38. } else {
  39. return matched;
  40. }
  41. }
  42. return matched;
  43. }
  44. #else
  45. static BROTLI_INLINE size_t FindMatchLengthWithLimit(const uint8_t* s1,
  46. const uint8_t* s2,
  47. size_t limit) {
  48. size_t matched = 0;
  49. const uint8_t* s2_limit = s2 + limit;
  50. const uint8_t* s2_ptr = s2;
  51. /* Find out how long the match is. We loop over the data 32 bits at a
  52. time until we find a 32-bit block that doesn't match; then we find
  53. the first non-matching bit and use that to calculate the total
  54. length of the match. */
  55. while (s2_ptr <= s2_limit - 4 &&
  56. BrotliUnalignedRead32(s2_ptr) ==
  57. BrotliUnalignedRead32(s1 + matched)) {
  58. s2_ptr += 4;
  59. matched += 4;
  60. }
  61. while ((s2_ptr < s2_limit) && (s1[matched] == *s2_ptr)) {
  62. ++s2_ptr;
  63. ++matched;
  64. }
  65. return matched;
  66. }
  67. #endif
  68. #if defined(__cplusplus) || defined(c_plusplus)
  69. } /* extern "C" */
  70. #endif
  71. #endif /* BROTLI_ENC_FIND_MATCH_LENGTH_H_ */