Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix loading an extra element when not necessary #40

Merged
merged 1 commit into from
Feb 26, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

- When a deferred `Set` or `Sequence` is used while iterating over itself it could produce unexpected results such as infinite loops or skipped values.
- Fix iterating over a closed `\Generator` on a deferred `Set`/`Sequence` when the source monad no longer exist and the monad at hand has already been iterated over.
- A deferred `Sequence` would load an extra element that is never used when calling `take`.

## 5.11.2 - 2025-02-23

Expand Down
21 changes: 21 additions & 0 deletions proofs/sequence.php
Original file line number Diff line number Diff line change
Expand Up @@ -435,6 +435,27 @@ static function($assert, $values) {
},
);

yield proof(
'Sequence::defer()->take() should not load an extra element',
given(
Set\Sequence::of(Set\Type::any()),
),
static function($assert, $values) {
$sequence = Sequence::defer((static function() use ($values) {
yield from $values;

throw new Exception;
})())->take(\count($values));

$assert->not()->throws(
static fn() => $assert->same(
$values,
$sequence->toList(),
),
);
},
);

yield test(
'Partial load a deferred Sequence appended to a lazy one',
static function($assert) {
Expand Down
9 changes: 7 additions & 2 deletions src/Sequence/Defer.php
Original file line number Diff line number Diff line change
Expand Up @@ -625,6 +625,10 @@ public function take(int $size): Implementation
/** @psalm-suppress ImpureFunctionCall */
return new self(
(static function(int $size) use (&$captured): \Generator {
if ($size === 0) {
return;
}

$taken = 0;
/**
* @psalm-suppress PossiblyNullArgument
Expand All @@ -634,14 +638,15 @@ public function take(int $size): Implementation
$values->rewind();

while ($values->valid()) {
yield $values->current();
++$taken;

if ($taken >= $size) {
$values->cleanup();

return;
}

yield $values->current();
++$taken;
$values->next();
}
})($size),
Expand Down