Core\Bytes::fill
Core\Bytes::fill(uint $length, uint $byte): bytesCore\Bytes::fill( uint $length, uint $byte, ): bytes
Builds a bytes value out of one byte repeated.
You give the number of bytes and the byte itself, written as a number from 0 to 255. The result is a new value of that size where every byte is the same. A length of 0 returns a value with nothing in it.
A number above 255 does not fit in one byte, so Core\Bytes::fill throws an error. A length larger than the memory the program may use also throws an error, and no value is built.
Good to know: this is how a program makes a block of zero bytes for a header it writes later, or the padding that brings a record up to a fixed size.
Parameters
$lengthuintHow many bytes to write.$byteuintThe byte to repeat, from0to255.
Return value
Returns bytes. The new buffer. It is empty when $length is 0.
Errors
RuntimeError$byteis above255, or$lengthis larger than the biggest buffer this process can have.
Examples
Building a value from one byte
<?nvs// Shows how to build a `bytes` value out of one byte repeated. You give the// number of bytes and the byte itself, as a number from 0 to 255.
// 65 is the letter "A", so this prints "AAAA".echo Core\Bytes::fill(4, 65) as string, "\n";
// A block of 16 zero bytes, as a program writes at the front of a file. This// prints 16.echo Core\Bytes::length(Core\Bytes::fill(16, 0)), "\n";
// A length of 0 gives a value with nothing in it. This prints 0.echo Core\Bytes::length(Core\Bytes::fill(0, 65)), "\n";AAAA160A byte outside the range
<?nvs// Shows what happens when the byte is not a number from 0 to 255. One byte// cannot hold 256, so the call throws an error.
try { bytes $wrong = Core\Bytes::fill(4, 256); echo Core\Bytes::length($wrong), "\n";} catch (Throwable $error) { // This prints the message of the error. echo $error->message, "\n";}
// 255 is the largest byte there is, and it works. This prints 4.echo Core\Bytes::length(Core\Bytes::fill(4, 255)), "\n";Core\Bytes::fill: 256 is not one octet — a byte is 0 to 2554Padding a record to a fixed size
<?nvs// Shows how a program brings every record up to the same size. Records of one// size can be read back one after another without a separator between them.
final class Record{ // Returns the record with zero bytes added at the end, up to $size bytes. public static function padded(bytes $record, uint $size): bytes { uint $have = Core\Bytes::length($record); if ($have >= $size) { return $record; } return Core\Bytes::join([$record, Core\Bytes::fill($size - $have, 0)]); }}
// This record has 11 bytes, so 5 zero bytes are added. This prints 16.echo Core\Bytes::length(Record::padded('Hello there' as bytes, 16)), "\n";
// This one already has 16 bytes, so nothing is added. This prints 16.echo Core\Bytes::length(Record::padded(Core\Bytes::fill(16, 65), 16)), "\n";1616