-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCursor.php
More file actions
61 lines (53 loc) · 1.11 KB
/
Cursor.php
File metadata and controls
61 lines (53 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<?php
declare(strict_types=1);
namespace PhpTypes\Ast;
use Generator;
/**
* @template T
*/
final class Cursor
{
/** @var T|null */
private mixed $current = null;
/** @var Generator<mixed, T> */
private readonly Generator $items;
/**
* @param iterable<mixed, T> $items
*/
public function __construct(iterable $items)
{
$this->items = self::toGenerator($items);
foreach ($this->items as $item) {
$this->current = $item;
break;
}
}
/**
* @return T | null
*/
public function consume(): mixed
{
$current = $this->current;
$this->items->next();
$this->current = $this->items->current();
return $current;
}
/**
* @return T | null
* @psalm-immutable
*/
public function peek(): mixed
{
return $this->current;
}
/**
* @template K
* @template V
* @param iterable<K, V> $iterable
* @return Generator<K, V>
*/
private static function toGenerator(iterable $iterable): Generator
{
yield from $iterable;
}
}