-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReadBuffer.php
More file actions
89 lines (68 loc) · 1.98 KB
/
Copy pathReadBuffer.php
File metadata and controls
89 lines (68 loc) · 1.98 KB
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
<?php
/**
* Copyright © EcomDev B.V. All rights reserved.
* See LICENSE for license details.
*/
declare(strict_types=1);
namespace EcomDev\MySQLBinaryProtocol;
use function strlen;
use function substr;
use function strpos;
class ReadBuffer
{
const ONE_MEGABYTE = 1024*1024;
/**
* @var string
*/
private $buffer = '';
/** @var int */
private $currentBufferOffset = 0;
/** @var int */
private $readBufferOffset = 0;
/**
* @var int
*/
private $bufferSize;
public function __construct(int $bufferSize = self::ONE_MEGABYTE)
{
$this->bufferSize = $bufferSize;
}
public function append(string $data): void
{
$this->buffer .= $data;
}
public function read(int $length): string
{
if (!$this->isReadable($length)) {
$this->currentBufferOffset = $this->readBufferOffset;
throw new IncompleteBufferException();
}
$data = substr($this->buffer, $this->currentBufferOffset, $length);
$this->currentBufferOffset += $length;
return $data;
}
public function isReadable(int $length): bool
{
return strlen($this->buffer) - $this->currentBufferOffset >= $length;
}
public function flush(): int
{
$bytesRead = $this->currentPosition();
$this->readBufferOffset = $this->currentBufferOffset;
if ($this->readBufferOffset >= $this->bufferSize) {
$this->buffer = substr($this->buffer, $this->readBufferOffset);
$this->readBufferOffset = 0;
$this->currentBufferOffset = 0;
}
return $bytesRead;
}
public function scan(string $pattern): int
{
$position = strpos($this->buffer, $pattern, $this->currentBufferOffset);
return $position === false ? -1 : ($position - $this->currentBufferOffset) + 1;
}
public function currentPosition(): int
{
return $this->currentBufferOffset - $this->readBufferOffset;
}
}