-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathBinaryReader.php
More file actions
105 lines (89 loc) Β· 2.29 KB
/
BinaryReader.php
File metadata and controls
105 lines (89 loc) Β· 2.29 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
<?php
declare(strict_types=1);
namespace PHPJava\Core\JVM\Stream;
use PHPJava\Exceptions\BinaryReaderException;
class BinaryReader implements StreamReaderInterface
{
/**
* @var resource
*/
private $handle;
/**
* @var int
*/
private $offset = 0;
/**
* @param resource $handle
*/
public function __construct($handle)
{
$this->handle = $handle;
}
/**
* @throws BinaryReaderException
*/
final public function read(int $bytes = 1): string
{
$this->offset += $bytes;
if ($bytes === 0) {
return '';
}
$read = fread($this->handle, $bytes);
if (strlen($read) !== $bytes) {
throw new BinaryReaderException(
'Read binary from stream is incorrect. that expected length is ' .
$bytes .
', but actual length is ' . strlen($read) . '.'
);
}
return $read;
}
public function readByte(): int
{
return current(unpack('c', $this->read(1)));
}
public function readUnsignedByte(): int
{
return current(unpack('C', $this->read(1)));
}
public function readUnsignedInt(): int
{
return current(unpack('N', $this->read(4)));
}
public function readUnsignedShort(): int
{
return current(unpack('n', $this->read(2)));
}
public function readInt(): int
{
$bytes = array_values(unpack('c4', $this->read(4)));
return ($bytes[0] << 24) | ($bytes[1] << 16) | ($bytes[2] << 8) | $bytes[3];
}
public function readShort(): int
{
$short = $this->readUnsignedShort();
return (($short & 0x8000) > 0) ? ($short - 0xFFFF - 1) : $short;
}
public function readUnsignedLong(): int
{
return current(unpack('J', $this->read(8)));
}
public function readLong(): int
{
return hexdec(bin2hex($this->read(8)));
}
public function seek(int $bytes): void
{
$this->offset += $bytes;
fseek($this->handle, $bytes, SEEK_CUR);
}
public function setOffset(int $pointer): void
{
$this->offset = $pointer;
fseek($this->handle, $pointer, SEEK_SET);
}
public function getOffset(): int
{
return $this->offset;
}
}