| Category | Functions |
|---|---|
| Parsing UUIDs | parseUUID UUID UUIDParsingException uuidRegex |
| Generating UUIDs | sha1UUID randomUUID md5UUID timestampRandomUUID |
| Using UUIDs | UUID.uuidVersion UUID.variant UUID.toString UUID.data UUID.swap UUID.opEquals UUID.opCmp UUID.toHash |
| UUID namespaces | dnsNamespace urlNamespace oidNamespace x500Namespace |
Sourcestd/uuid.d
import std.uuid;UUID[] ids;ids ~= randomUUID();ids ~= md5UUID("test.name.123");ids ~= sha1UUID("test.name.123");foreach (entry; ids){ writeln(entry.variant);// UUID.Variant.rfc4122}writeln(ids[0].uuidVersion);// UUID.Version.randomNumberBasedwriteln(ids[1].toString());// "22390768-cced-325f-8f0f-cfeaa19d0ccd"assert(ids[1].data == [34, 57, 7, 104, 204, 237, 50, 95, 143, 15, 207, 234, 161, 157, 12, 205]);UUID id;assert(id.empty);
UUID;UUID id;assert(id.empty);id = randomUUID;assert(!id.empty);id =UUID(cast(ubyte[16]) [138, 179, 6, 14, 44, 186, 79, 35, 183, 76, 181, 45, 179, 189, 251, 70]);writeln(id.toString());// "8ab3060e-2cba-4f23-b74c-b52db3bdfb46"
Variant: int;NoteDo not confuse this withstd.variant.Variant.
ncsrfc4122microsoftfutureVersion: int;NoteAll of these UUID versions can be read and processed bystd.uuid, but only version 3, 4 and 5 UUIDs can be generated.
unknowntimeBaseddceSecuritynameBasedMD5randomNumberBasednameBasedSHA1timestampRandomdata;NoteUUID uses a 16-ubyte representation for the UUID data. RFC 4122 defines a UUID as a special structure in big-endian format. These 16-ubytes always equal the big-endian structure defined in RFC 4122.
Example
auto rawData = uuid.data;//get datarawData[0] = 1;//modifyuuid.data = rawData;//set datauuid.data[1] = 2;//modify directly
uuidData);uuidData);enumubyte[16] data = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];auto uuid = UUID(data);enum ctfe = UUID(data);writeln(uuid.data);// datawriteln(ctfe.data);// data
uuidData)uuidData.length == 16 && allSatisfy!(isIntegral, T));auto tmp = UUID(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15);assert(tmp.data ==cast(ubyte[16])[0,1,2,3,4,5,6,7,8,9,10,11, 12,13,14,15]);
timestamp, ubyte[10]random = generateV7RandomData());SysTimetimestamp | the timestamp part of the UUID V7 |
ubyte[10]random | UUID V7 has 74 bits of random data, which rounds to 10 ubyte's. If no random data is given, random data is generated. |
import std.datetime : DateTime, SysTime;SysTime st = DateTime(2025, 8, 19, 10, 38, 45);UUID u = UUID(st);SysTime o = u.v7Timestamp();writeln(o);// st
uuid)CTFEThis function is supported in CTFE code. Note that error messages caused by a malformed UUID parsed at compile time can be cryptic, but errors are detected and reported at compile time.
NoteThis is a strict parser. It only accepts the pattern above. It doesn't support any leading or trailing characters. It only accepts characters used for hex numbers and the string must have hyphens exactly like above.
For a less strict parser, seeparseUUIDauto id = UUID("8AB3060E-2cba-4f23-b74c-b52db3bdfb46");assert(id.data == [138, 179, 6, 14, 44, 186, 79, 35, 183, 76, 181, 45, 179, 189, 251, 70]);writeln(id.toString());// "8ab3060e-2cba-4f23-b74c-b52db3bdfb46"//Can also be used in CTFE, for example as UUID literals:enum ctfeID = UUID("8ab3060e-2cba-4f23-b74c-b52db3bdfb46");//here parsing is done at compile time, no runtime overhead!
empty() const;UUID id;assert(id.empty);id = UUID("00000000-0000-0000-0000-000000000001");assert(!id.empty);
v7Timestamp() const;variant() const;NoteDo not confuse this withstd.variant.Variant. The type of this property is`std.uuid.UUID.Variant`.
assert(UUID("8ab3060e-2cba-4f23-b74c-b52db3bdfb46").variant == UUID.Variant.rfc4122);
uuidVersion() const;assert(UUID("8ab3060e-2cba-4f23-b74c-b52db3bdfb46").uuidVersion == UUID.Version.randomNumberBased);
swap(ref UUIDrhs);immutableubyte[16] data = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];UUID u1;UUID u2 = UUID(data);u1.swap(u2);writeln(u1);// UUID(data)writeln(u2);// UUID.init
opEquals(const UUIDs) const;opEquals(ref scope const UUIDs) const;opCmp(const UUIDs) const;opCmp(ref scope const UUIDs) const;opAssign(const UUIDs);opAssign(ref scope const UUIDs);toHash() const;//compare UUIDswriteln(UUID("00000000-0000-0000-0000-000000000000"));// UUID.init//UUIDs in associative arrays:int[UUID] test = [UUID("8a94f585-d180-44f7-8929-6fca0189c7d0") : 1, UUID("7c351fd4-b860-4ee3-bbdc-7f79f3dfb00a") : 2, UUID("9ac0a4e5-10ee-493a-86fc-d29eeb82ecc1") : 3];writeln(test[UUID("9ac0a4e5-10ee-493a-86fc-d29eeb82ecc1")]);// 3//UUIDS can be sorted:import std.algorithm;UUID[] ids = [UUID("8a94f585-d180-44f7-8929-6fca0189c7d0"), UUID("7c351fd4-b860-4ee3-bbdc-7f79f3dfb00a"), UUID("9ac0a4e5-10ee-493a-86fc-d29eeb82ecc1")];sort(ids);
toString(Writer)(scope Writersink) const;sink as an ASCII string in the canonical form, which is 36 characters in the form "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"Writersink | OutputRange or writeable array at least 36 entries long |
toString() const;immutable str ="8ab3060e-2cba-4f23-b74c-b52db3bdfb46";auto id = UUID(str);writeln(id.toString());// str
md5UUID(const(char[])name, const UUIDnamespace = UUID.init);md5UUID(const(ubyte[])data, const UUIDnamespace = UUID.init);NoteThe default namespaces (dnsNamespace, ...) defined by this module should be used when appropriate.
RFC 4122 recommends to use Version 5 UUIDs (SHA-1) instead of Version 3 UUIDs (MD5) for new applications.CTFECTFE is not supported.
NoteRFC 4122 isn't very clear on how UUIDs should be generated from names. It is possible that different implementations return different UUIDs for the same input, so be warned. The implementation for UTF-8 strings and byte arrays used bystd.uuid is compatible with Boost's implementation.std.uuid guarantees that the same input to this function will generate the same output at any time, on any system (this especially means endianness doesn't matter).
NoteThis function does not provide overloads for wstring and dstring, as there's no clear answer on how that should be implemented. It could be argued, that string, wstring and dstring input should have the same output, but that wouldn't be compatible with Boost, which generates different output for strings and wstrings. It's always possible to pass wstrings and dstrings by using the ubyte[] function overload (but be aware of endianness issues!).
//Use default UUID.init namespaceauto simpleID =md5UUID("test.uuid.any.string");//use a name-based id as namespaceautonamespace =md5UUID("my.app");auto id =md5UUID("some-description",namespace);
sha1UUID(scope const(char)[]name, scope const UUIDnamespace = UUID.init);sha1UUID(scope const(ubyte)[]data, scope const UUIDnamespace = UUID.init);NoteThe default namespaces (dnsNamespace, ...) defined by this module should be used when appropriate.
CTFECTFE is not supported.
NoteRFC 4122 isn't very clear on how UUIDs should be generated from names. It is possible that different implementations return different UUIDs for the same input, so be warned. The implementation for UTF-8 strings and byte arrays used bystd.uuid is compatible with Boost's implementation.std.uuid guarantees that the same input to this function will generate the same output at any time, on any system (this especially means endianness doesn't matter).
NoteThis function does not provide overloads for wstring and dstring, as there's no clear answer on how that should be implemented. It could be argued, that string, wstring and dstring input should have the same output, but that wouldn't be compatible with Boost, which generates different output for strings and wstrings. It's always possible to pass wstrings and dstrings by using the ubyte[] function overload (but be aware of endianness issues!).
//Use default UUID.init namespaceauto simpleID =sha1UUID("test.uuid.any.string");//use a name-based id as namespaceautonamespace =sha1UUID("my.app");auto id =sha1UUID("some-description",namespace);
randomUUID();randomUUID(RNG)(ref RNGrandomGen)WarningThis function must not be used for cryptographic purposes. UUIDs generated by this function do not have sufficient randomness for all use cases. This especially applies to the overload that accepts a caller-provided RNG. At the moment, Phobos does not provide acryptographically-secure pseudo-random number generator (CSPRNG) that could be supplied to this function.
While the function overload with no parameters will attempt to use the system CSPRNG where available and implemented, there are no guarantees. Seestd.random.unpredictableSeed for details.RNGrandomGen | uniform RNG |
import std.random : Xorshift192, unpredictableSeed;//simple callauto uuid =randomUUID();//provide a custom RNG. Must be seeded manually.Xorshift192 gen;gen.seed(unpredictableSeed);auto uuid3 =randomUUID(gen);
timestampRandomUUID();UUID u =timestampRandomUUID();writeln(u.uuidVersion);// UUID.Version.timestampRandom
parseUUID(T)(TuuidString)parseUUID(Range)(ref RangeuuidRange)Note Like most parsers, it consumes its argument. This means:
string s ="8AB3060E-2CBA-4F23-b74c-B52Db3BDFB46";parseUUID(s);assert(s =="");
CTFEThis function is supported in CTFE code. Note that error messages caused by a malformed UUID parsed at compile time can be cryptic, but errors are detected and reported at compile time.
auto id =parseUUID("8AB3060E-2CBA-4F23-b74c-B52Db3BDFB46");//no dashesid =parseUUID("8ab3060e2cba4f23b74cb52db3bdfb46");//dashes at different positionsid =parseUUID("8a-b3-06-0e2cba4f23b74c-b52db3bdfb-46");//leading / trailing charactersid =parseUUID("{8ab3060e-2cba-4f23-b74c-b52db3bdfb46}");//unicodeid =parseUUID("ü8ab3060e2cba4f23b74cb52db3bdfb46ü");//multiple trailing/leading charactersid =parseUUID("///8ab3060e2cba4f23b74cb52db3bdfb46||");//Can also be used in CTFE, for example as UUID literals:enum ctfeID =parseUUID("8ab3060e-2cba-4f23-b74c-b52db3bdfb46");//here parsing is done at compile time, no runtime overhead!
dnsNamespace;urlNamespace;oidNamespace;x500Namespace;uuidRegex;import std.algorithm;import std.regex;string test ="Lorem ipsum dolor sit amet, consetetur "~"6ba7b814-9dad-11d1-80b4-00c04fd430c8 sadipscing \n"~"elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore \r\n"~"magna aliquyam erat, sed diam voluptua. "~"8ab3060e-2cba-4f23-b74c-b52db3bdfb46 At vero eos et accusam et "~"justo duo dolores et ea rebum.";auto r = regex(uuidRegex,"g");UUID[] found;foreach (c; match(test, r)){ found ~= UUID(c.hit);}assert(found == [ UUID("6ba7b814-9dad-11d1-80b4-00c04fd430c8"), UUID("8ab3060e-2cba-4f23-b74c-b52db3bdfb46"),]);
UUIDParsingException:object.Exception;import std.exception : collectException;const inputUUID ="this-is-an-invalid-uuid";auto ex = collectException!UUIDParsingException(UUID(inputUUID));assert(ex !isnull);// check that exception was thrownwriteln(ex.input);// inputUUIDwriteln(ex.position);// 0writeln(ex.reason);// UUIDParsingException.Reason.tooLittle
import std.datetime : DateTime, SysTime;SysTime st = DateTime(2025, 8, 19, 10, 38, 45);UUID u = UUID(st);writeln(u.uuidVersion);// UUID.Version.timestampRandomSysTime o = u.v7Timestamp();writeln(o);// ststring s = u.toString();UUID u2 = UUID(s);SysTime o2 = u2.v7Timestamp();writeln(o2);// st
import std.datetime : DateTime, SysTime;UUID u = UUID("0198c2b2-c5a8-7a0f-a1db-86aac7906c7b");auto d = DateTime(2025,8,19);writeln((cast(DateTime)u.v7Timestamp()).year);// d.year
Reason: int;reason;unknowntooLittletooMuchinvalidCharinput;position;