-
Notifications
You must be signed in to change notification settings - Fork 0
/
Queue.php
149 lines (131 loc) · 2.73 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
<?php
namespace Altair\Structure;
use Altair\Structure\Contracts\CapacityInterface;
use Altair\Structure\Contracts\QueueInterface;
use ArrayAccess;
use Error;
use IteratorAggregate;
use OutOfBoundsException;
/**
* Queue.
*
* A Queue is a “first in, first out” or “FIFO” structure that only allows access to the value at the front of the queue
* and iterates in that order, destructively.
*
* @link https://medium.com/@rtheunissen/efficient-data-structures-for-php-7-9dda7af674cd#.gl62k1xqr
*/
class Queue implements IteratorAggregate, ArrayAccess, QueueInterface, CapacityInterface
{
use Traits\CollectionTrait;
/**
* Creates an instance using the values of an array or Traversable object.
*
* @param array|\Traversable|Queue $values
*/
public function __construct($values = null)
{
$this->internal = new Deque($values ?? []);
}
/**
* {@inheritdoc}
*/
public function peek()
{
return $this->internal->first();
}
/**
* {@inheritdoc}
*/
public function pop()
{
return $this->internal->shift();
}
/**
* {@inheritdoc}
*/
public function push(...$values): QueueInterface
{
$this->internal->push(...$values);
return $this;
}
/**
* {@inheritdoc}
*/
public function allocate(int $capacity): QueueInterface
{
$this->internal->allocate($capacity);
return $this;
}
/**
* Returns the current capacity of the queue.
*
* @return int
*/
public function capacity(): int
{
return $this->internal->capacity();
}
/**
* {@inheritdoc}
*/
public function copy()
{
return new static($this->internal);
}
/**
* {@inheritdoc}
*/
public function toArray(): array
{
return $this->internal->toArray();
}
/**
* Get iterator.
*/
public function getIterator()
{
while (!$this->isEmpty()) {
yield $this->pop();
}
}
/**
* {@inheritdoc}
*
* @throws OutOfBoundsException
*/
public function offsetSet($offset, $value)
{
if ($offset === null) {
$this->push($value);
} else {
throw new OutOfBoundsException();
}
}
/**
* {@inheritdoc}
*
* @throws Error
*/
public function offsetGet($offset)
{
throw new Error();
}
/**
* {@inheritdoc}
*
* @throws Error
*/
public function offsetUnset($offset)
{
throw new Error();
}
/**
* {@inheritdoc}
*
* @throws Error
*/
public function offsetExists($offset)
{
throw new Error();
}
}