Skip to content

Instantly share code, notes, and snippets.

@bwoods
Last active November 7, 2020 06:54
Show Gist options
  • Save bwoods/4487358 to your computer and use it in GitHub Desktop.
Save bwoods/4487358 to your computer and use it in GitHub Desktop.
A standard conforming implementation of UUIDs in three lines.
// Surprisingly, a standard conforming implementation of UUIDs in three lines.
#include <stdlib.h>
static void generate_random_uuid(unsigned char uuid[16])
{
arc4random_buf(uuid, 16);
// Version 4, Variant 1: http://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_.28random.29
uuid[6] = (uuid[6] & 0x0F) | 0x40;
uuid[8] = (uuid[8] & 0x3F) | 0x80;
}
CREATE TABLE id (
id INTEGER PRIMARY KEY,
uuid BLOB NOT NULL DEFAULT ( -- // Version 4, Variant 1
randomblob(6) ||
substr(X'404142434445464748494a4b4c4d4e4f', 1 + (abs(random()) % 16) , 1) ||
randomblob(1) ||
substr(X'a0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebf808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f',
1 + (abs(random()) % 64) , 1) ||
randomblob(7)),
urn GENERATED ALWAYS AS ( 'urn:uuid:' ||
substr(lower(hex(uuid)), 1,8) || '-' ||
substr(lower(hex(uuid)), 9,4) || '-' ||
substr(lower(hex(uuid)),13,4) || '-' ||
substr(lower(hex(uuid)),17,4) || '-' ||
substr(lower(hex(uuid)),21)
) VIRTUAL
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment