role Buf

Mutable buffer for binary data

role Buf[::T] does Blob[T] { ... }

A Buf is a mutable sequence of (usually unsigned) integers.

my $b = Buf.new(1, 2, 3);
$b[1] = 42;

Type graph

Below you should see a clickable image showing the type relations for Buf that links to the documentation pages for the related types. If not, try the PNG version instead.

perl6-type-graph Buf Buf Blob Blob Buf->Blob Positional Positional Stringy Stringy Blob->Positional Blob->Stringy

Routines supplied by role Blob

Buf does role Blob, which provides the following methods:

method new

method new(*@codes)

Creates a Blob from a list of integers.

method Bool

multi method Bool(Blob:D:)

Returns False if and only if the buffer is empty.

method elems

multi method elems(Blob:D:) returns Int:D

Returns the number of elements of the buffer.

method decode

multi method decode(Blob:D: Str:D $encoding = 'UTF-8') returns Str:D

Applies an encoding to turn the blob into a Str.

method subbuf

method subbuf(Int $from, Int $len = self.elems) returns Blob:D

Extracts a part of the invocant buffer, starting from the index with elements $from, and taking $len elements (or less if the buffer is shorter), and creates a new buffer as the result.

say Blob.new(1..10).subbuf(2, 4);    # Blob:0x<03 04 05 06>

method unpack

method unpack(Blob:D: $template) returns List:D

Extracts features from the blob according to the template string, and returns them as a list.

The template string consists of zero or more units that begin with an ASCII letter, and are optionally followed by a quantifier. The quantifier can be * (which typically stands for "use up the rest of the Blob here"), or a positive integer (without a +).

Whitespace between template units is ignored.

Examples of valid templates include "A4 C n*" and "A*".

The following letters are recognized:

Letter Meaning
A Extract a string, where each element of the Blob maps to a codepoint
a Same as A
C Extract an element from the blob as an integer
H Extracts a hex string
L Extracts four elements and returns them as a single unsigned integer
n Extracts two elements and combines them in "network" (big-endian) byte order into a single integer
N Extracts four elements and combines them in "network" (big-endian) byte order into a single integer
S Extracts two elements and returns them as a single unsigned integer
v Same as S
V Same as L
x Drop an element from the blob (that is, ignore it)
Z Same as A

sub pack

sub pack(Str $template, *@items) returns Buf

Packs the given items according to the template and returns a buffer containing the packed bytes.

The template string consists of zero or more units that begin with an ASCII letter, and are optionally followed by a quantifier. For details, see unpack.

Routines supplied by role Positional

Buf does role Positional, which provides the following methods:

method of

method of()

Returns the type constraint for elements of the positional container. Defaults to Mu.