Skip to content

Core\Response\Stream::offset

$stream->offset(): int

Returns the position of the first byte your program writes. The position is counted from the start of the whole body. It works on a stream that Core\Response::startStream started with a $length.

A browser can ask for one part of a body with the request header Range. It does this to seek in a video or to resume a download. The server reads that header, and offset() is where the part starts. Without a Range header, offset() is 0.

Your program starts writing at this byte, and writes length() bytes. A file is read with seek to this position first. Text in memory is cut with Core\Bytes::slice.

A stream without a $length is always sent whole, so offset() throws a LogicError there.

The examples show a part of some text, a file read from its offset, and a stream without a length.

Return value

Returns int. An int. Start writing the body at this byte.

Errors

  • LogicErrorThe stream was started without a $length.

Examples

The part the browser asked for

<?nvs
// Shows how to write only the part of a body that the browser asked for.
bytes $text = "Hello, world\n" as bytes;
// The stream has the length of the whole body, so a browser can ask for one part of it.
Core\Response\Stream $body = Core\Response::startStream('text/plain; charset=utf-8', Core\Bytes::length($text) as int);
// `offset()` is where the part starts, and `length()` is its size.
// This request has no `Range` header, so the part is the whole body. This prints "Hello, world".
$body->write(Core\Bytes::slice($text, $body->offset(), $body->length()));
Output
Hello, world

A file read from its offset

<?nvs
// Shows how to send a file from storage, starting at the byte the browser asked for.
// A real server already has this file. The example writes it first, so that it has a file to send.
string $path = Core\Path::join(Core\IO::createTemporaryDirectory(), 'notes.txt');
Core\IO::write($path, "Line one\nLine two\nLine three\n");
Core\Response\Stream $body = Core\Response::startStream('text/plain; charset=utf-8', Core\IO::size($path) as int);
// `seek` moves to the first byte of the part. This request has no `Range` header, so `offset()` is `0`.
Core\IO\File $file = Core\IO::open($path, Core\IO::FileMode::Read);
$file->seek($body->offset() as uint);
$body->write($file->read($body->length() as uint));
$file->close();
Output
Line one
Line two
Line three

A stream without a length

<?nvs
// Shows that `offset()` throws a `LogicError` when the stream has no length.
Core\Response\Stream $body = Core\Response::startStream('text/plain; charset=utf-8');
try {
int $start = $body->offset();
$body->write('The part starts at byte ' . ($start as string) . ".\n");
} catch (LogicError $error) {
// A stream without a length is always sent whole, so this line is printed.
$body->write("This stream has no length, so it has no offset.\n");
}
Output
This stream has no length, so it has no offset.