From 297e07229bb1fb65595f030aa98742951cb31249 Mon Sep 17 00:00:00 2001 From: Behdad Esfahbod Date: Wed, 19 Aug 2026 11:29:37 -0600 Subject: [PATCH] [iter] Fix rewinding a filter at the beginning (#6179) Detect when the underlying iterator cannot move backwards and restore the last matching position. This avoids looping forever when the first array items do not pass the filter. Add a regression test that exercises the decrement which previously hung. Fixes: https://github.com/harfbuzz/harfbuzz/issues/6178 Assisted-by: Codex --- src/hb-iter.hh | 17 ++++++++++++++++- src/test-iter.cc | 16 ++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/src/hb-iter.hh b/src/hb-iter.hh index ecc30f4e1..19866863c 100644 --- a/src/hb-iter.hh +++ b/src/hb-iter.hh @@ -460,7 +460,22 @@ struct hb_filter_iter_t : __item_t__ __item__ () const { return *it; } bool __more__ () const { return bool (it); } void __next__ () { do ++it; while (it && !hb_has (p.get (), hb_get (f.get (), *it))); } - void __prev__ () { do --it; while (it && !hb_has (p.get (), hb_get (f.get (), *it))); } + void __prev__ () + { + unsigned count = 0; + do + { + Iter old = it; + --it; + if (!(it != old)) + { + it += count; + return; + } + count++; + } + while (!hb_has (p.get (), hb_get (f.get (), *it))); + } hb_filter_iter_t __end__ () const { return hb_filter_iter_t (it._end (), p, f); } bool operator != (const hb_filter_iter_t& o) const { return it != o.it; } diff --git a/src/test-iter.cc b/src/test-iter.cc index be50ad9fb..b8303ef53 100644 --- a/src/test-iter.cc +++ b/src/test-iter.cc @@ -185,6 +185,21 @@ static void test_concat () hb_always_assert (it6.len () == 2); } +static void +test_backward_filter () +{ + hb_vector_t V = {2, 4, 5, 7, 8, 9, 10}; + auto it = hb_iter (V) | hb_filter ([] (int x) { return x % 2 != 0; }); + it += 2; + hb_always_assert (*it == 9); + --it; + hb_always_assert (*it == 7); + --it; + hb_always_assert (*it == 5); + --it; + hb_always_assert (*it == 5); +} + int main (int argc, char **argv) { @@ -377,6 +392,7 @@ main (int argc, char **argv) hb_always_assert (hb_range (-2, -7, -3).len () == 2); test_concat (); + test_backward_filter (); return 0; }