phasync\Util\StringBuffer class

Documentation

A high performance string buffer for buffering streaming data that can be parsed efficiently. Designed for protocol parsing in servers (HTTP, FastCGI, WebSocket) where you need to read fixed-size frames from a byte stream.

For safe coroutine-to-coroutine communication, use Channels instead.

To prevent readers from waiting forever if the writer crashes, use the deadman switch feature:

phasync::go(function() use ($sb, $socket) {
    $deadman = $sb->getDeadmanSwitch();
    while ($data = fread($socket, 8192)) {
        $sb->write($data);
    }
    $sb->end(); // Always end properly - deadman is just a safety net
});

If the writer exits without calling end(), the deadman switch triggers and any blocking read will throw DeadmanException. Buffered data can still be read before the exception is thrown.

Inheritance

Implements: phasync\SelectableInterface

Uses Traits: phasync\DeadmanSwitchTrait

Constants (1)

NameValue
BUFFER_WASTE_LIMIT 4096

Properties (9)

protected SplDoublyLinkedList $queue

Contains the chunks of binary data appended or prepended

protected string $buffer

Contains unread bytes, for situations where data was consumed

protected int $length

The length of the unread bytes buffer

protected int $offset

The read offset in the unread bytes buffer, to reduce the number

private int $totalRead

The total number of bytes that have been read from the string

private int $totalWritten

The total number of bytes that have been written to the buffer.

private bool $ended

Has the end of data been signalled?

private bool $failed

True if the writer terminated unexpectedly (deadman switch triggered).

private ?WeakReference $deadmanSwitch

Weak reference to the deadman switch, allowing it to be GC'd

Methods (15)

Create a new StringBuffer instance.

Wait until the buffer has data available to read or has been ended.

Check if a read operation would not block.

Returns true if there is no data currently available to read.

Write data to the buffer

Read up to $maxLength bytes from the buffer.

Asynchronously read data from the stream resource into the

Signal the equivalent of an end of file. No further writes

Called when the deadman switch is triggered.

True if the end of file has been reached.

Read a fixed number of bytes from the buffer, and return null

Data that enters the buffer will be written asynchronously to the

Prepend data to the buffer.

Function that grows the string buffer until it can be

Get a deadman switch for this object.

Source

src/Util/StringBuffer.php:33-377