-
-
Notifications
You must be signed in to change notification settings - Fork 66
/
Queue.php
104 lines (93 loc) 路 2.01 KB
/
Queue.php
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
<?php
declare(strict_types=1);
namespace Psl\DataStructure;
use function array_shift;
use function count;
/**
* A basic implementation of a queue data structure ( FIFO ).
*
* @template T
*
* @implements QueueInterface<T>
*/
final class Queue implements QueueInterface
{
/**
* @var list<T>
*/
private array $queue = [];
/**
* Provides a default instance of the {@see Queue}.
*
* @return static A new instance of {@see Queue}, devoid of any nodes.
*
* @pure
*/
public static function default(): static
{
return new self();
}
/**
* Adds a node to the queue.
*
* @param T $node
*
* @psalm-external-mutation-free
*/
public function enqueue(mixed $node): void
{
$this->queue[] = $node;
}
/**
* Retrieves, but does not remove, the node at the head of this queue,
* or returns null if this queue is empty.
*
* @return null|T
*
* @psalm-mutation-free
*/
public function peek(): mixed
{
return $this->queue[0] ?? null;
}
/**
* Retrieves and removes the node at the head of this queue,
* or returns null if this queue is empty.
*
* @return null|T
*
* @psalm-external-mutation-free
*/
public function pull(): mixed
{
return array_shift($this->queue);
}
/**
* Dequeues a node from the queue.
*
* @throws Exception\UnderflowException If the queue is empty.
*
* @return T
*
* @psalm-external-mutation-free
*/
public function dequeue(): mixed
{
if ([] === $this->queue) {
throw new Exception\UnderflowException('Cannot dequeue a node from an empty queue.');
}
/** @var T */
return array_shift($this->queue);
}
/**
* Count the nodes in the queue.
*
* @return int<0, max>
*
* @psalm-mutation-free
*/
public function count(): int
{
return count($this->queue);
}
}