Skip to content

Fix Heap comparator interference - #236

Open
HypeMC wants to merge 1 commit into
php-ds:masterfrom
HypeMC:fix-heap-comparator-isolation
Open

HypeMC wants to merge 1 commit into
php-ds:masterfrom
HypeMC:fix-heap-comparator-isolation

Conversation

@HypeMC

@HypeMC HypeMC commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Heap operations shared callback state, so using another heap during iteration or inside a comparator could cause incorrect ordering. Pass the owning heap into comparisons and keep callback invocation state local.

This bug predates #234 and already affected ordinary foreach. Returning InternalIterator added another way to encounter it through interleaved iterators.

For example:

$min = new Ds\Heap([1, 2, 3, 4, 5], fn($a, $b) => $b <=> $a);
$max = new Ds\Heap([1, 2, 3, 4, 5], fn($a, $b) => $a <=> $b);

$values = [];
foreach ($min as $value) {
    $values[] = $value;
    foreach ($max as $_) {}
}
echo json_encode($values);

Before: [1,2,5,4,3]
After: [1,2,3,4,5]

@HypeMC
HypeMC force-pushed the fix-heap-comparator-isolation branch from 2a0bff9 to cff6df2 Compare October 13, 2026 09:00
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.

1 participant