Skip to content

Instantly share code, notes, and snippets.

@kevmoo
Created March 16, 2017 01:38
Show Gist options
  • Save kevmoo/8784c4fca25b4a2cd17101586deecaa0 to your computer and use it in GitHub Desktop.
Save kevmoo/8784c4fca25b4a2cd17101586deecaa0 to your computer and use it in GitHub Desktop.
easy uuid-v4 for dart
// Ran with http://www.cryptosys.net/pki/uuid-rfc4122.html
import 'dart:math' as m;
void main() {
for (var i = 0; i < 1000000; i++) {
var thing = getThing();
print(thing);
print(thing.length);
assert(thing.length == 36);
assert(thing[14] == '4');
print(thing[19]);
assert(const ['8', '9', 'A', 'B'].contains(thing[19]));
}
}
String getThing() {
var rnd = new m.Random.secure();
var bytes = new List<int>.generate(16, (_) => rnd.nextInt(256));
bytes[6] = (bytes[6] & 0x0F) | 0x40;
bytes[8] = (bytes[8] & 0x3f) | 0x80;
var chars = bytes
.map((b) => b.toRadixString(16).padLeft(2, '0'))
.join()
.toUpperCase();
return '${chars.substring(0, 8)}-${chars.substring(8, 12)}-'
'${chars.substring(12, 16)}-${chars.substring(16, 20)}-${chars.substring(20, 32)}';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment