From 9a3182fe25affaccfa809ffdaa7f833f6241f67e Mon Sep 17 00:00:00 2001 From: Alexey Kopytko Date: Sat, 15 Apr 2023 13:37:46 +0900 Subject: [PATCH] Discard the state in reservoir() for invalid arguments Fixes #120 --- src/Standard.php | 3 +++ tests/ReservoirTest.php | 10 ++++++++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/src/Standard.php b/src/Standard.php index 8e1486a..7f9b800 100644 --- a/src/Standard.php +++ b/src/Standard.php @@ -778,6 +778,9 @@ public function reservoir(int $size, ?callable $weightFunc = null): array } if ($size <= 0) { + // Discard the state to emulate full consumption + $this->pipeline = null; + return []; } diff --git a/tests/ReservoirTest.php b/tests/ReservoirTest.php index 64e2abb..1eef213 100644 --- a/tests/ReservoirTest.php +++ b/tests/ReservoirTest.php @@ -158,9 +158,15 @@ public static function provideWeightedInputs(): iterable */ public function testWeightedSampleFromGenerator(array $input, int $size, callable $weightFn, array $expected): void { - $this->assertSame($expected, map(static function () use ($input) { + $pipeline = map(static function () use ($input) { yield from $input; - })->reservoir($size, $weightFn)); + }); + + $this->assertSame($expected, $pipeline->reservoir($size, $weightFn)); + + if ($size <= 0) { + $this->assertSame([], $pipeline->toArray()); + } } /**