=============
This library provides a Buffer
and Parser
class to make dealing with binary data in PHP easier.
Templates
extend this by offering a read/write interface for larger serialized structures.
- PHP 5.4+
- Composer
- ext-gmp
You can install this library via Composer: composer require bitwasp/buffertools
Buffer's are immutable classes to store binary data. BufferHex will convert the provided data to binary, as will BufferInt. Buffer's main methods are:
- getBinary()
- getHex()
- getInt()
Parser will read Buffers. Parser's main methods are:
- readBytes()
- getArray()
- getVarInt()
- getString()
- writeBytes()
In most cases, the interface offered by Parser should not be used directly. Instead, Templates expose read/write access to larger serialized structures.
use BitWasp\Buffertools\Buffer;
use BitWasp\Buffertools\Parser;
// Parsers read Buffers
$buffer = new Buffer('abc');
$parser = new Parser($buffer);
// Call readBytes to unpack the data
/** @var Buffer[] $set */
$set = [
$parser->readBytes(1),
$parser->readBytes(1),
$parser->readBytes(1)
];
foreach ($set as $item) {
echo $item->getBinary() . PHP_EOL;
}
use BitWasp\Buffertools\Buffer;
use BitWasp\Buffertools\BufferHex;
use BitWasp\Buffertools\Parser;
use BitWasp\Buffertools\TemplateFactory;
$structure = (object) [
'hash' => hash('sha256', 'abc'),
'message_id' => 9123,
'message' => "Hi there! What's up?"
];
// Templates are read/write
$template = (new TemplateFactory)
->bytestring(32)
->uint32()
->varstring()
->getTemplate();
// Write the structure
$binary = $template->write([
new BufferHex($structure->hash),
$structure->message_id,
new Buffer($structure->message)
]);
echo $binary->getHex() . "\n";
// Use the template to read resulting Buffer
$parsed = $template->parse(new Parser($binary));
print_r($parsed);