-
-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy pathReader.php
264 lines (224 loc) · 8.03 KB
/
Reader.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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
<?php
declare(strict_types=1);
namespace Psl\IO;
use Psl\Async;
use Psl\DateTime\Duration;
use Psl\Str;
use function strlen;
use function strpos;
use function substr;
use const PHP_EOL;
final class Reader implements ReadHandleInterface
{
use ReadHandleConvenienceMethodsTrait;
private readonly ReadHandleInterface $handle;
private bool $eof = false;
private string $buffer = '';
public function __construct(ReadHandleInterface $handle)
{
$this->handle = $handle;
}
/**
* {@inheritDoc}
*/
public function reachedEndOfDataSource(): bool
{
if ($this->eof) {
return true;
}
if ($this->buffer !== '') {
return false;
}
// @codeCoverageIgnoreStart
try {
$this->buffer = $this->handle->read();
if ($this->buffer === '') {
return $this->eof = $this->handle->reachedEndOfDataSource();
}
} catch (Exception\ExceptionInterface) {
// ignore; it'll be thrown again when attempting a real read.
}
// @codeCoverageIgnoreEnd
return false;
}
/**
* {@inheritDoc}
*/
public function readFixedSize(int $size, null|Duration $timeout = null): string
{
$timer = new Async\OptionalIncrementalTimeout($timeout, function (): void {
// @codeCoverageIgnoreStart
throw new Exception\TimeoutException(Str\format(
'Reached timeout before reading requested amount of data',
$this->buffer === '' ? 'any' : 'all',
));
// @codeCoverageIgnoreEnd
});
while (($length = strlen($this->buffer)) < $size && !$this->eof) {
/** @var positive-int $to_read */
$to_read = $size - $length;
$this->fillBuffer($to_read, $timer->getRemaining());
}
if ($this->eof) {
throw new Exception\RuntimeException('Reached end of file before requested size.');
}
$buffer_size = strlen($this->buffer);
if ($size === $buffer_size) {
$ret = $this->buffer;
$this->buffer = '';
return $ret;
}
$ret = substr($this->buffer, 0, $size);
$this->buffer = substr($this->buffer, $size);
return $ret;
}
/**
* Read a single byte from the handle.
*
* @throws Exception\AlreadyClosedException If the handle has been already closed.
* @throws Exception\RuntimeException If an error occurred during the operation, or reached end of file.
* @throws Exception\TimeoutException If $timeout is reached before being able to read from the handle.
*/
public function readByte(null|Duration $timeout = null): string
{
if ($this->buffer === '' && !$this->eof) {
$this->fillBuffer(null, $timeout);
}
if ($this->buffer === '') {
throw new Exception\RuntimeException('Reached EOF without any more data.');
}
$ret = $this->buffer[0];
if ($ret === $this->buffer) {
$this->buffer = '';
return $ret;
}
$this->buffer = substr($this->buffer, 1);
return $ret;
}
/**
* @returns string the read data on success,
* or null if the end of file is reached before finding the current line terminator.
*
* @throws Exception\AlreadyClosedException If the handle has been already closed.
* @throws Exception\RuntimeException If an error occurred during the operation.
* @throws Exception\TimeoutException If $timeout is reached before being able to read from the handle.
*/
public function readLine(null|Duration $timeout = null): null|string
{
$timer = new Async\OptionalIncrementalTimeout($timeout, static function (): void {
// @codeCoverageIgnoreStart
throw new Exception\TimeoutException(
'Reached timeout before encountering reaching the current line terminator.',
);
// @codeCoverageIgnoreEnd
});
$line = $this->readUntil(PHP_EOL, $timer->getRemaining());
if (null !== $line) {
return $line;
}
/** @psalm-suppress MissingThrowsDocblock - $size is positive */
$content = $this->read(null, $timer->getRemaining());
return '' === $content ? null : $content;
}
/**
* Read until the specified suffix is seen.
*
* The trailing suffix is read (so won't be returned by other calls), but is not
* included in the return value.
*
* This call returns null if the suffix is not seen, even if there is other
* data.
*
* @throws Exception\AlreadyClosedException If the handle has been already closed.
* @throws Exception\RuntimeException If an error occurred during the operation.
* @throws Exception\TimeoutException If $timeout is reached before being able to read from the handle.
*/
public function readUntil(string $suffix, null|Duration $timeout = null): null|string
{
$buf = $this->buffer;
$idx = strpos($buf, $suffix);
$suffix_len = strlen($suffix);
if ($idx !== false) {
$this->buffer = substr($buf, $idx + $suffix_len);
return substr($buf, 0, $idx);
}
$timer = new Async\OptionalIncrementalTimeout($timeout, static function () use ($suffix): void {
// @codeCoverageIgnoreStart
throw new Exception\TimeoutException(Str\format(
"Reached timeout before encountering the suffix (\"%s\").",
$suffix,
));
// @codeCoverageIgnoreEnd
});
do {
// + 1 as it would have been matched in the previous iteration if it
// fully fit in the chunk
$offset = (strlen($buf) - $suffix_len) + 1;
$offset = $offset > 0 ? $offset : 0;
$chunk = $this->handle->read(null, $timer->getRemaining());
if ($chunk === '') {
$this->buffer = $buf;
return null;
}
$buf .= $chunk;
$idx = strpos($buf, $suffix, $offset);
} while ($idx === false);
$this->buffer = substr($buf, $idx + $suffix_len);
return substr($buf, 0, $idx);
}
/**
* {@inheritDoc}
*/
public function read(null|int $max_bytes = null, null|Duration $timeout = null): string
{
if ($this->eof) {
return '';
}
if ($this->buffer === '') {
$this->fillBuffer(null, $timeout);
}
// We either have a buffer, or reached EOF; either way, behavior matches
// read, so just delegate
return $this->tryRead($max_bytes);
}
/**
* {@inheritDoc}
*/
public function tryRead(null|int $max_bytes = null): string
{
if ($this->eof) {
return '';
}
if ($this->buffer === '') {
$this->buffer = $this->getHandle()->tryRead();
if ($this->buffer === '') {
return '';
}
}
$buffer = $this->buffer;
if ($max_bytes === null || $max_bytes >= strlen($buffer)) {
$this->buffer = '';
return $buffer;
}
$this->buffer = substr($buffer, $max_bytes);
return substr($buffer, 0, $max_bytes);
}
public function getHandle(): ReadHandleInterface
{
return $this->handle;
}
/**
* @param null|positive-int $desired_bytes
*
* @throws Exception\AlreadyClosedException If the handle has been already closed.
* @throws Exception\RuntimeException If an error occurred during the operation.
* @throws Exception\TimeoutException If $timeout is reached before being able to read from the handle.
*/
private function fillBuffer(null|int $desired_bytes, null|Duration $timeout): void
{
$this->buffer .= $chunk = $this->handle->read($desired_bytes, $timeout);
if ($chunk === '') {
$this->eof = $this->handle->reachedEndOfDataSource();
}
}
}