Core\Uuid::fromBytes
Reads sixteen bytes as a Uuid. The bytes are in the same order as the digits of the UUID's text, so the bytes f9 16 8c 5e … give the UUID f9168c5e-…. Many databases store a UUID in a binary column in this form, and binary protocols send it this way.
Any sixteen bytes are a valid UUID, so only the length is checked. When the bytes are not exactly sixteen long, fromBytes throws a RuntimeError. The message gives the length it got.
$uuid->toBytes() does the opposite. It returns the sixteen bytes of a Uuid.
The examples below read one UUID, show the error for bytes of the wrong length, and read a list of UUIDs from one binary message.
Parameters
$bbytesThe sixteen bytes, in the same order as the digits of the UUID's text.$uuid->toBytes()gives them in this order.
Return value
Returns Core\Uuid. The Uuid that the bytes give. Any sixteen bytes are a valid UUID, so only the length is checked.
Errors
RuntimeError$bis not exactly sixteen bytes long. The message gives the length of$b.
Examples
Read a uuid from sixteen bytes
<?nvs// Shows how to read a UUID from its sixteen bytes and print it as text.
// `Core\Encoding::fromHex` gives the sixteen bytes of one UUID.bytes $octets = Core\Encoding::fromHex('f9168c5eceb24faab6bf329bf39fa1e4');
// `Core\Uuid::fromBytes` reads them as a UUID.// This prints f9168c5e-ceb2-4faa-b6bf-329bf39fa1e4.var $id = Core\Uuid::fromBytes($octets);echo $id, "\n";f9168c5e-ceb2-4faa-b6bf-329bf39fa1e4Bytes of the wrong length
<?nvs// Shows what happens when the bytes are not exactly sixteen long.
// These are twelve bytes. A UUID needs sixteen.bytes $short = Core\Encoding::fromHex('f9168c5eceb24faab6bf329b');
// `fromBytes` throws a `RuntimeError`. The message gives the length, 12.try { Core\Uuid::fromBytes($short);} catch (RuntimeError $e) { echo $e->message, "\n";}Core\Uuid::fromBytes(): a UUID is sixteen bytes, and this buffer is 12Read a list of ids from a binary message
<?nvs// Shows how to read the UUIDs that a binary message sends one after another.
class Ids{ public static function read(bytes $message): array<Core\Uuid> { array<Core\Uuid> $ids = []; int $offset = 0; while ($offset < (Core\Bytes::length($message) as int)) { // Each UUID is the next sixteen bytes of the message. $ids[] = Core\Uuid::fromBytes(Core\Bytes::slice($message, $offset, 16)); $offset = $offset + 16; } return $ids; }}
// The message has two UUIDs, so it is 32 bytes long.bytes $message = Core\Bytes::join([ Core\Encoding::fromHex('0190d1e68e3c7c2a9a4b1f2e3d4c5b6a'), Core\Encoding::fromHex('f9168c5eceb24faab6bf329bf39fa1e4'),]);
// This prints the two UUIDs as text.foreach (Ids::read($message) as Core\Uuid $id) { echo $id, "\n";}0190d1e6-8e3c-7c2a-9a4b-1f2e3d4c5b6af9168c5e-ceb2-4faa-b6bf-329bf39fa1e4