Skip to content

sbwdlihao/buffertools-php

 
 

Repository files navigation

Buffertools

============= 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.

Build Status Code Coverage Scrutinizer Code Quality Latest Stable Version Join the chat at https://gitter.im/Bit-Wasp/bitcoin-php

Requirements:

  • PHP 5.4+
  • Composer
  • ext-gmp

Installation

You can install this library via Composer: composer require bitwasp/buffertools

Examples

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.

Using Parser to read binary data

    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;
    }

Using Templates

    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);

About

Toolbox for working with binary and hex data. Similar to NodeJS Buffer.

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages

  • PHP 100.0%