thesis / byte-cursor
In-memory buffer for read/write capabilities.
Fund package maintenance!
www.tinkoff.ru/cf/5MqZQas2dk7
0.1.0
2025-01-17 12:22 UTC
Requires
- php: ^8.3
- thesis/byte-order: ^0.2.0
- thesis/byte-reader: ^0.3.1
- thesis/byte-writer: ^0.2.1
- thesis/endian: ^0.1.0
Requires (Dev)
- bamarni/composer-bin-plugin: ^1.8.2
- ergebnis/composer-normalize: ^2.45.0
- phpunit/phpunit: ^10.5.40
- symfony/var-dumper: ^6.4.15 || ^7.2.0
README
Installation
composer require thesis/byte-cursor
Basic usage
<?php declare(strict_types=1); use Thesis\ByteCursor\Cursor; use Thesis\ByteCursor\Seek; require_once __DIR__.'/vendor/autoload.php'; /** * @param list<non-empty-string> $items */ function writeArray(Cursor $cursor, array $items): void { // Remember the current position to write array len later. $pos = $cursor->position(); // Reserve bytes for array len. $cursor->writeUint32(0); foreach ($items as $item) { $cursor->writeUint16(\strlen($item)); $cursor->write($item); } // Now we can write to this position the actual length of the array in bytes by subtracting the position ($pos) and the position size (4 bytes) from the cursor length. // At the end, the cursor position will reset to the end on its own. $cursor->writeAt($pos, static function (Cursor $cursor) use ($pos): void { $cursor->writeUint32(\count($cursor) - $pos - 4); }); } /** * @param Cursor $cursor * @return list<non-empty-string> */ function readArray(Cursor $cursor): array { $size = $cursor->readUint32(); $items = []; while ($size > 0) { $items[] = $v = $cursor->read($cursor->readUint16()); $size -= \strlen($v) + 2; } return $items; } $cursor = Cursor::new(); writeArray($cursor, ['x', 'y']); $items = readArray($cursor); var_dump($items); // [x, y] // You must reset the position before you can use the cursor again. $cursor->reset(); // by resetting it. $cursor->seek(Seek::start(0)); // or seeking.