From 85be877925ddbf34f74a1229f3ca1716bb6170dc Mon Sep 17 00:00:00 2001
From: Behdad Esfahbod <behdad@behdad.org>
Date: Wed, 1 Feb 2023 20:00:43 -0700
Subject: [PATCH] [layout] Limit how far we skip when looking back

See comments.
---
 src/hb-ot-layout-gsubgpos.hh | 12 +++++++++++-
 1 file changed, 11 insertions(+), 1 deletion(-)

diff --git a/src/hb-ot-layout-gsubgpos.hh b/src/hb-ot-layout-gsubgpos.hh
index c17bf92..712e307 100644
--- a/src/hb-ot-layout-gsubgpos.hh
+++ b/src/hb-ot-layout-gsubgpos.hh
@@ -535,7 +535,19 @@ struct hb_ot_apply_context_t :
     bool prev ()
     {
       assert (num_items > 0);
-      while (idx > num_items - 1)
+      /* The alternate condition below is faster at string boundaries,
+       * but produces subpar "unsafe-to-concat" values. */
+      unsigned stop = num_items - 1;
+      if (c->buffer->flags & HB_BUFFER_FLAG_PRODUCE_UNSAFE_TO_CONCAT)
+	      stop = 1 - 1;
+
+      /* When looking back, limit how far we search; this function is mostly
+       * used for looking back for base glyphs when attaching marks. If we
+       * don't limit, we can get O(n^2) behavior where n is the number of
+       * consecutive marks. */
+      stop = (unsigned) hb_max ((int) stop, (int) idx - HB_MAX_CONTEXT_LENGTH);
+
+      while (idx > stop)
       {
 	idx--;
 	const hb_glyph_info_t &info = c->buffer->out_info[idx];
-- 
2.33.0

