Core\Random\Seeded::bytes
Returns the number of bytes you ask for from a seeded generator.
You make the generator with new Core\Random\Seeded(42). The number 42 is the seed. Two generators with the same seed return the same bytes, on every run. This is useful for test data, such as the content of a file that a test uploads. The result is a tainted bytes value of exactly the length you asked for. Convert it with Core\Encoding::toHex to show it as text.
Asking for zero bytes throws an error.
Good to know: anybody who knows the seed knows every byte, so never use these bytes as a key, a salt or a nonce. For those, use Core\Random::bytes. The result is tainted, so a program that passes it as a key does not compile.
Parameters
$countuintHow many bytes to return. It must be at least1.
Return value
Returns tainted bytes. A tainted bytes value with exactly $count raw bytes. It is tainted, so a parameter that needs a key does not accept it.
Errors
RuntimeError$countis0, as withCore\Random::bytes, or it is larger than a buffer this process can allocate.
Examples
The same seed gives the same bytes
<?nvs// Shows that two generators with the same seed return the same bytes.
Core\Random\Seeded $first = new Core\Random\Seeded(42);Core\Random\Seeded $second = new Core\Random\Seeded(42);
// `Core\Encoding::toHex` shows each byte as two characters. Both lines are the same.echo Core\Encoding::toHex($first->bytes(8)), "\n";echo Core\Encoding::toHex($second->bytes(8)), "\n";
// The next call returns the next bytes, so this line is different.echo Core\Encoding::toHex($first->bytes(8)), "\n";956eeb2f2632d7bd956eeb2f2632d7bd03f166b233e3ef28Zero bytes is an error
<?nvs// Shows that the result has the length you asked for, and that zero bytes is an error.
Core\Random\Seeded $generator = new Core\Random\Seeded(42);
// This prints 1 and 100.echo Core\Bytes::length($generator->bytes(1)), "\n";echo Core\Bytes::length($generator->bytes(100)), "\n";
// Asking for zero bytes throws an error.try { $generator->bytes(0);} catch (Throwable $e) { echo 'Error: ', $e->message, "\n";}1100Error: Core\Random\Seeded::bytes(): a draw of zero bytes is the empty buffer, which is no sequence at all — draw at least one byteA file for an upload test
<?nvs// Shows how to make the content of a test file that is the same on every run.
// An upload test needs three files of different sizes. The seed is fixed, so// the files have the same content every time, and a failed test can be repeated.Core\Random\Seeded $generator = new Core\Random\Seeded(2024);array<uint> $sizes = [16, 1024, 65536];foreach ($sizes as uint $size) { tainted bytes $content = $generator->bytes($size); // Six more bytes give the file a name. `Core\Encoding::toBase64` turns them into text. tainted string $name = Core\Encoding::toBase64($generator->bytes(6)) . '.bin'; echo $name, ': ', Core\Bytes::length($content), " bytes\n";}f6XbWL98.bin: 16 bytesgYsPooG8.bin: 1024 bytes+XwpC0XB.bin: 65536 bytes