Use a better best_len in the lazy search.

PiperOrigin-RevId: 990732063
diff --git a/c/enc/backward_references_opt_inc.h b/c/enc/backward_references_opt_inc.h
index 1b8fb14..149b43a 100644
--- a/c/enc/backward_references_opt_inc.h
+++ b/c/enc/backward_references_opt_inc.h
@@ -132,8 +132,12 @@
       for (;; --max_length) {
         const score_t cost_diff_lazy = 175;
         HasherSearchResult sr2;
-        sr2.len = params->quality < MIN_QUALITY_FOR_EXTENSIVE_REFERENCE_SEARCH ?
-            BROTLI_MIN(size_t, sr.len - 1, max_length) : 0;
+        sr2.len =
+            params->quality < MIN_QUALITY_FOR_EXTENSIVE_REFERENCE_SEARCH
+                ? BROTLI_MIN(size_t, sr.len - 1, max_length)
+                : BROTLI_MIN(size_t,
+                             MinimumBetterLength(sr.score + cost_diff_lazy - 1),
+                             max_length);
         sr2.len_code_delta = 0;
         sr2.distance = 0;
         sr2.score = kMinScore;
diff --git a/c/enc/hash.h b/c/enc/hash.h
index c875e6f..35addc8 100644
--- a/c/enc/hash.h
+++ b/c/enc/hash.h
@@ -126,6 +126,13 @@
       BROTLI_DISTANCE_BIT_PENALTY * Log2FloorNonZero(backward_reference_offset);
 }
 
+/* Returns the minimum length of a backward reference that will improve on the
+ provided score.  We conservatively assume that the match will be a last
+ distance match, the best case scenario for the next match.*/
+static BROTLI_INLINE size_t MinimumBetterLength(score_t score) {
+  return (score - (BROTLI_SCORE_BASE + 15)) / BROTLI_LITERAL_BYTE_SCORE;
+}
+
 static BROTLI_INLINE score_t BackwardReferenceScoreUsingLastDistance(
     size_t copy_length) {
   return BROTLI_LITERAL_BYTE_SCORE * (score_t)copy_length +
diff --git a/c/enc/hash_longest_match_simd_opt_inc.h b/c/enc/hash_longest_match_simd_opt_inc.h
index 9a51301..6985a5d 100644
--- a/c/enc/hash_longest_match_simd_opt_inc.h
+++ b/c/enc/hash_longest_match_simd_opt_inc.h
@@ -156,7 +156,12 @@
   /* Don't accept a short copy from far away. */
   score_t min_score = out->score;
   score_t best_score = out->score;
-  size_t best_len = out->len;
+  /* If we're still searching the static dictionary, we have to do the full
+     search to determine if we should check the static dictionary. */
+  size_t best_len =
+      self->common_->dict_num_matches < (self->common_->dict_num_lookups >> 7)
+          ? out->len
+          : 0;
   size_t i;
   /* Precalculate the hash key and prefetch the bucket. */
   const uint32_t hash =