-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathByteString.php
More file actions
106 lines (92 loc) · 2.39 KB
/
ByteString.php
File metadata and controls
106 lines (92 loc) · 2.39 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
106
<?php
declare(strict_types=1);
namespace BitWasp\Buffertools\Types;
use BitWasp\Buffertools\Buffer;
use BitWasp\Buffertools\BufferInterface;
use BitWasp\Buffertools\ByteOrder;
use BitWasp\Buffertools\Parser;
class ByteString extends AbstractType
{
/**
* @var int|string
*/
private $length;
/**
* @param int $length
* @param int $byteOrder
*/
public function __construct(int $length, int $byteOrder = ByteOrder::BE)
{
$this->length = $length;
parent::__construct($byteOrder);
}
/**
* @param BufferInterface $string
* @return string
*/
public function writeBits(BufferInterface $string): string
{
$bits = str_pad(
gmp_strval(gmp_init($string->getHex(), 16), 2),
$this->length * 8,
'0',
STR_PAD_LEFT
);
return $bits;
}
/**
* @param BufferInterface $string
* @return string
* @throws \Exception
*/
public function write($string): string
{
if (!($string instanceof Buffer)) {
throw new \InvalidArgumentException('FixedLengthString::write() must be passed a Buffer');
}
$bits = $this->isBigEndian()
? $this->writeBits($string)
: $this->flipBits($this->writeBits($string));
$hex = str_pad(
gmp_strval(gmp_init($bits, 2), 16),
$this->length * 2,
'0',
STR_PAD_LEFT
);
return pack("H*", $hex);
}
/**
* @param BufferInterface $buffer
* @return string
*/
public function readBits(BufferInterface $buffer): string
{
return str_pad(
gmp_strval(gmp_init($buffer->getHex(), 16), 2),
$this->length * 8,
'0',
STR_PAD_LEFT
);
}
/**
* @param Parser $parser
* @return BufferInterface
* @throws \Exception
*/
public function read(Parser $parser): BufferInterface
{
$bits = $this->readBits($parser->readBytes($this->length));
if (!$this->isBigEndian()) {
$bits = $this->flipBits($bits);
}
return Buffer::hex(
str_pad(
gmp_strval(gmp_init($bits, 2), 16),
$this->length * 2,
'0',
STR_PAD_LEFT
),
$this->length
);
}
}