-
-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathReadableBuffer.php
68 lines (55 loc) · 1.48 KB
/
ReadableBuffer.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
<?php declare(strict_types=1);
namespace Amp\ByteStream;
use Amp\Cancellation;
use Amp\DeferredFuture;
use Amp\ForbidCloning;
use Amp\ForbidSerialization;
/**
* ReadableStream with a single already known data chunk.
*
* @implements \IteratorAggregate<int, string>
*/
final class ReadableBuffer implements ReadableStream, \IteratorAggregate
{
use ReadableStreamIteratorAggregate;
use ForbidCloning;
use ForbidSerialization;
private ?string $contents;
private readonly DeferredFuture $onClose;
/**
* @param string|null $contents Data chunk or `null` for no data chunk.
*/
public function __construct(?string $contents = null)
{
$this->contents = $contents === '' ? null : $contents;
$this->onClose = new DeferredFuture;
if ($this->contents === null) {
$this->close();
}
}
public function read(?Cancellation $cancellation = null): ?string
{
$contents = $this->contents;
$this->close();
return $contents;
}
public function isReadable(): bool
{
return $this->contents !== null;
}
public function close(): void
{
$this->contents = null;
if (!$this->onClose->isComplete()) {
$this->onClose->complete();
}
}
public function isClosed(): bool
{
return !$this->isReadable();
}
public function onClose(\Closure $onClose): void
{
$this->onClose->getFuture()->finally($onClose);
}
}