# define zng_first_diff_byte64(diff) (zng_ctz64(diff) / 8)
#endif
+/* Builds a mask of the first n bytes (1..8) so an XOR diff can be tested for
+ * a leading n-byte match with a single AND. */
+#if BYTE_ORDER == BIG_ENDIAN
+# define zng_first_bytes_mask64(n) (UINT64_MAX << ((8 - (n)) * 8))
+#else
+# define zng_first_bytes_mask64(n) (UINT64_MAX >> ((8 - (n)) * 8))
+#endif
+
Z_FORCEINLINE static uint16_t zng_bitreverse16(uint16_t value) {
#if __has_builtin(__builtin_bitreverse16)
return (uint16_t)__builtin_bitreverse16(value);
/* Peel the first candidate out of the loop. A full 8-byte match falls straight
* through to compare256, and single-candidate chains (barely-compressible data)
* run with no loop overhead. */
+ uint64_t first_mask = zng_first_bytes_mask64(best_len + 1);
uint64_t diff = scan_start ^ cand_start;
- len = zng_first_diff_byte64(diff);
- if (len > best_len)
+ /* A candidate beats best_len only when its first best_len+1 bytes match, i.e.
+ * those bytes of the XOR are zero. The masked test rejects without running ctz. */
+ if (UNLIKELY((diff & first_mask) == 0)) {
+ len = zng_first_diff_byte64(diff);
goto short_match_accept;
+ }
if (--chain_length == 0 || (cur_match = prev[cur_match & wmask]) <= limit)
return best_len;
cand_start = zng_memread_8(mbase_start + cur_match);
/* Walk the remaining candidates with the chain advance kept inline. */
for (;;) {
diff = scan_start ^ cand_start;
- len = zng_first_diff_byte64(diff);
- if (len > best_len)
+ if (UNLIKELY((diff & first_mask) == 0)) {
+ len = zng_first_diff_byte64(diff);
goto short_match_accept;
+ }
if (--chain_length == 0 || (cur_match = prev[cur_match & wmask]) <= limit)
return best_len;
cand_start = zng_memread_8(mbase_start + cur_match);