find_match_length.h (2167B)
1 /* Copyright 2010 Google Inc. All Rights Reserved. 2 3 Distributed under MIT license. 4 See file LICENSE for detail or copy at https://opensource.org/licenses/MIT 5 */ 6 7 /* Function to find maximal matching prefixes of strings. */ 8 9 #ifndef BROTLI_ENC_FIND_MATCH_LENGTH_H_ 10 #define BROTLI_ENC_FIND_MATCH_LENGTH_H_ 11 12 #include "../common/platform.h" 13 14 #if defined(__cplusplus) || defined(c_plusplus) 15 extern "C" { 16 #endif 17 18 /* Separate implementation for little-endian 64-bit targets, for speed. */ 19 #if defined(BROTLI_TZCNT64) && BROTLI_64_BITS && BROTLI_LITTLE_ENDIAN 20 static BROTLI_INLINE size_t FindMatchLengthWithLimit(const uint8_t* s1, 21 const uint8_t* s2, 22 size_t limit) { 23 const uint8_t *s1_orig = s1; 24 for (; limit >= 8; limit -= 8) { 25 uint64_t x = BROTLI_UNALIGNED_LOAD64LE(s2) ^ 26 BROTLI_UNALIGNED_LOAD64LE(s1); 27 s2 += 8; 28 if (x != 0) { 29 size_t matching_bits = (size_t)BROTLI_TZCNT64(x); 30 return (size_t)(s1 - s1_orig) + (matching_bits >> 3); 31 } 32 s1 += 8; 33 } 34 while (limit && *s1 == *s2) { 35 limit--; 36 ++s2; 37 ++s1; 38 } 39 return (size_t)(s1 - s1_orig); 40 } 41 #else 42 static BROTLI_INLINE size_t FindMatchLengthWithLimit(const uint8_t* s1, 43 const uint8_t* s2, 44 size_t limit) { 45 size_t matched = 0; 46 const uint8_t* s2_limit = s2 + limit; 47 const uint8_t* s2_ptr = s2; 48 /* Find out how long the match is. We loop over the data 32 bits at a 49 time until we find a 32-bit block that doesn't match; then we find 50 the first non-matching bit and use that to calculate the total 51 length of the match. */ 52 while (s2_ptr <= s2_limit - 4 && 53 BrotliUnalignedRead32(s2_ptr) == 54 BrotliUnalignedRead32(s1 + matched)) { 55 s2_ptr += 4; 56 matched += 4; 57 } 58 while ((s2_ptr < s2_limit) && (s1[matched] == *s2_ptr)) { 59 ++s2_ptr; 60 ++matched; 61 } 62 return matched; 63 } 64 #endif 65 66 #if defined(__cplusplus) || defined(c_plusplus) 67 } /* extern "C" */ 68 #endif 69 70 #endif /* BROTLI_ENC_FIND_MATCH_LENGTH_H_ */