-
Notifications
You must be signed in to change notification settings - Fork 0
/
Stack.php
158 lines (139 loc) · 2.91 KB
/
Stack.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
150
151
152
153
154
155
156
157
158
<?php
namespace Altair\Structure;
use Altair\Structure\Contracts\CapacityInterface;
use Altair\Structure\Contracts\StackInterface;
use ArrayAccess;
use Error;
use IteratorAggregate;
use OutOfBoundsException;
/**
* Stack.
*
* A Stack is a “last in, first out” or “LIFO” structure that only allows access to the value at the top of the
* structure and iterates in that order, destructively. Altair\Structure\Stack uses a Altair\Structure\Vector
* internally.
*
* @link https://medium.com/@rtheunissen/efficient-data-structures-for-php-7-9dda7af674cd#.gl62k1xqr
*/
class Stack implements IteratorAggregate, ArrayAccess, StackInterface, CapacityInterface
{
use Traits\CollectionTrait;
/**
* Creates an instance using the values of an array or Traversable object.
*
* @param array|\Traversable $values
*/
public function __construct($values = null)
{
$this->internal = new Vector($values ?? []);
}
/**
* {@inheritdoc}
*/
public function peek()
{
return $this->internal->last();
}
/**
* {@inheritdoc}
*/
public function pop()
{
return $this->internal->pop();
}
/**
* {@inheritdoc}
*/
public function push(...$values): StackInterface
{
$this->internal->push(...$values);
return $this;
}
/**
* {@inheritdoc}
*/
public function copy()
{
return new static($this->internal);
}
/**
* {@inheritdoc}
*/
public function count(): int
{
return count($this->internal);
}
/**
* {@inheritdoc}
*/
public function allocate(int $capacity)
{
$this->internal->allocate($capacity);
return $this;
}
/**
* Returns the current capacity of the stack.
*
* @return int
*/
public function capacity(): int
{
return $this->internal->capacity();
}
/**
* {@inheritdoc}
*/
public function toArray(): array
{
return array_reverse($this->internal->toArray());
}
/**
* @return \Generator
*/
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();
}
}