Skip to content

Core\Bytes::repeat

Builds a bytes value by repeating a whole buffer.

You give the buffer and the number of copies you want. The result is a new value holding those copies one after another, in the order they were written. Zero copies return a value with nothing in it. A buffer that is already empty stays empty, however many copies you ask for.

Core\Bytes::fill repeats a single byte. Core\Bytes::repeat repeats a buffer of any length, so one copy can be several bytes long. A result larger than the memory the program may use throws an error, and no value is built.

Good to know: this is how a program draws a line under a title, builds a block of a known pattern, or makes a body of a fixed size to send in a test.

Parameters

  • $bbytesThe buffer to repeat.
  • $timesuintHow many copies to write.

Return value

Returns bytes. The new buffer. It is empty when $times is 0 or $b is empty.

Errors

  • RuntimeError$times or the result is larger than the biggest buffer this process can have.

Examples

Repeating a buffer

<?nvs
// Shows how to build a `bytes` value by repeating a whole buffer. You give the
// buffer and the number of copies.
// Three copies of "ab", one after another. This prints "ababab".
echo Core\Bytes::repeat('ab' as bytes, 3) as string, "\n";
// Zero copies give a value with nothing in it. This prints 0.
echo Core\Bytes::length(Core\Bytes::repeat('ab' as bytes, 0)), "\n";
// A buffer with nothing in it stays empty, for any number of copies. This
// prints 0.
echo Core\Bytes::length(Core\Bytes::repeat('' as bytes, 1000)), "\n";
Output
ababab
0
0

One byte or a whole buffer

<?nvs
// Shows the two ways to build a buffer out of something repeated. One repeats
// a single byte, the other repeats a buffer of any length.
// `Core\Bytes::fill` writes the same byte every time. 45 is the letter "-", so
// this prints "-----".
echo Core\Bytes::fill(5, 45) as string, "\n";
// `Core\Bytes::repeat` writes the whole buffer every time. This prints
// "-+-+-+-+-+".
echo Core\Bytes::repeat('-+' as bytes, 5) as string, "\n";
// The result has one copy for each round. Ten bytes of two, so this prints 10.
echo Core\Bytes::length(Core\Bytes::repeat('-+' as bytes, 5)), "\n";
Output
-----
-+-+-+-+-+
10

A line under a title

<?nvs
// Shows how a program draws a line under a title in a report. The line has the
// same length as the title, so it fits whatever the title says.
final class Report
{
// Returns the title with a line of "=" of the same length under it.
public static function heading(bytes $title): bytes
{
uint $width = Core\Bytes::length($title);
bytes $rule = Core\Bytes::repeat('=' as bytes, $width);
return Core\Bytes::join([$title, "\n" as bytes, $rule]);
}
}
// The title has 12 bytes, so the line under it has 12 as well.
echo Report::heading('Orders today' as bytes) as string, "\n";
// A shorter title gives a shorter line.
echo Report::heading('Total' as bytes) as string, "\n";
Output
Orders today
============
Total
=====