Skip to content

Fix Heap iterator value ownership and rewinding - #235

Merged
rtheunissen merged 1 commit into
php-ds:masterfrom
HypeMC:fix-heap-iterator-ownership-and-rewind
Oct 13, 2026
Merged

rtheunissen merged 1 commit into
php-ds:masterfrom
HypeMC:fix-heap-iterator-ownership-and-rewind

Conversation

@HypeMC

@HypeMC HypeMC commented Oct 13, 2026

Copy link
Copy Markdown
Contributor

Follow-up to #234.

The underlying Heap iterator bugs predated #234, but returning InternalIterator exposed them through direct current(), key(), and rewind() calls. Ordinary foreach checks valid() before reading values or keys and creates a fresh iterator for each loop, which hid these cases.

This fixes value ownership and rewinding, and returns null for empty or exhausted iterators.

Repeated current() calls no longer access freed objects:

$heap = new Ds\Heap([(object) ['value' => 1]]);
$it = $heap->getIterator();
$heap->clear();
echo json_encode($it->current()); // {"value":1}
echo json_encode($it->current()); // {"value":1}; previously could crash

Rewinding restarts the same iterator:

$it = (new Ds\Heap([1, 3, 2]))->getIterator();
iterator_to_array($it); // [3, 2, 1]
iterator_to_array($it); // [3, 2, 1]; previously []

Empty or exhausted iterators now return null from current() and key(). Calling next() or rewind() on the same iterator from its comparator throws RuntimeException to prevent use-after-free.

@rtheunissen
rtheunissen merged commit 6e9d668 into php-ds:master Oct 13, 2026
54 checks passed
@HypeMC
HypeMC deleted the fix-heap-iterator-ownership-and-rewind branch October 13, 2026 08:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants