kafkiansky/binary

Tool for writing/reading bytes in any order.

0.4.4 2024-07-17 05:00 UTC

README

This package can be installed as a Composer dependency.

composer require kafkiansky/binary

This package requires PHP 8.1 or later.

Usage

Endianness

<?php

declare(strict_types=1);

require_once __DIR__.'/vendor/autoload.php';

use Kafkiansky\Binary\Endianness;

$endian = Endianness::big(); // Big Endian.
$endian = Endianness::little(); // Little Endian.
$endian = Endianness::network(); // Big Endian.
$endian = Endianness::native(); // Machine (native) byte order.

Buffer

<?php

declare(strict_types=1);

require_once __DIR__.'/vendor/autoload.php';

use Kafkiansky\Binary\{Buffer, Endianness};

$buffer = Buffer::empty(); // Network byte order (big endian) by default.
$buffer = Buffer::empty(Endianness::little()); // Override byte order.

// https://kafka.apache.org/protocol.html#The_Messages_CreateTopics
$bytes = Buffer::empty()
    ->writeInt32(1)
    ->writeInt16(6)
    ->write('events')
    ->writeInt32(1)
    ->writeInt16(1)
    ->writeInt32(0)
    ->writeInt32(0)
    ->reset()
;

$buffer = Buffer::fromString($bytes);

var_dump(
    $buffer->consumeInt32(),
    $buffer->consume($buffer->consumeInt16()),
    $buffer->consumeInt32(),
    $buffer->consumeInt16(),
    $buffer->consumeInt32(),
    $buffer->consumeInt32(),
    \assert(0 === \count($buffer)),
);

Stream

<?php

declare(strict_types=1);

require_once __DIR__.'/../vendor/autoload.php';

use Kafkiansky\Binary\Buffer;

$resource = fopen('php://temp', 'a+');
\assert(\is_resource($resource));

$bytes = Buffer::fromResource($resource)
    ->writeInt32(1)
    ->writeInt16(6)
    ->write('events')
    ->writeInt32(1)
    ->writeInt16(1)
    ->writeInt32(0)
    ->writeInt32(0)
    ->reset()
;

$buffer = Buffer::fromString($bytes);

var_dump(
    $buffer->consumeInt32(),
    $buffer->consume($buffer->consumeInt16()),
    $buffer->consumeInt32(),
    $buffer->consumeInt16(),
    $buffer->consumeInt32(),
    $buffer->consumeInt32(),
    \assert(0 === \count($buffer)),
);

Available types

  • int8
  • uint8
  • int16
  • uint16
  • int32
  • uint32
  • int64
  • uint64
  • f32 (float)
  • f64 (double)
  • string
  • varuint
  • varint

Testing

$ composer test

License

The MIT License (MIT). See License File for more information.