aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/Stream/BlobStream.php
blob: 08eed21869b27ccbafe3e709132e0f0fbac30dea (plain)
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
<?php

declare(strict_types=1);

namespace Nsfisis\Waddiwasi\Stream;

use function assert;
use function ord;
use function sprintf;
use function strlen;
use function substr;

/**
 * Read-only blob stream.
 */
final class BlobStream implements StreamInterface
{
    /**
     * @var int<0, max>
     */
    private int $pos = 0;

    /**
     * @var positive-int
     */
    private readonly int $len;

    /**
     * Creates a new blob stream with the given content.
     *
     * @param non-empty-string $content
     *   The content of the blob.
     */
    public function __construct(
        private readonly string $content,
    ) {
        $this->len = strlen($content);
    }

    public function close(): void
    {
    }

    public function read(int $bytes): string
    {
        $this->ensureNBytesAvailable($bytes);
        $ret = substr($this->content, $this->pos, $bytes);
        $this->pos += $bytes;
        assert($ret !== '');
        return $ret;
    }

    public function readByte(): int
    {
        $this->ensureNBytesAvailable(1);
        return ord($this->content[$this->pos++]);
    }

    public function peekByte(): int
    {
        $this->ensureNBytesAvailable(1);
        return ord($this->content[$this->pos]);
    }

    public function seek(int $bytes): void
    {
        $this->ensureNBytesAvailable($bytes);
        $this->pos += $bytes;
    }

    /**
     * @phpstan-pure
     */
    public function tell(): int
    {
        return $this->pos;
    }

    /**
     * @phpstan-pure
     */
    public function eof(): bool
    {
        return $this->len <= $this->pos;
    }

    /**
     * @param positive-int $bytes
     */
    private function ensureNBytesAvailable(int $bytes): void
    {
        if ($this->len < $this->pos + $bytes) {
            throw new UnexpectedEofException(sprintf('Unexpected EOF while reading from blob (%d bytes expected, %d bytes read)', $bytes, $this->len - $this->pos));
        }
    }
}