uuid: add example code to generate & pretty-print a version 4 UUID
1 files changed, 51 insertions(+), 0 deletions(-)

M proposed/uuid.md
M proposed/uuid.md +51 -0
@@ 60,3 60,54 @@ References
 ----------
 
 RFC 4122: A Universally Unique IDentifier (UUID) URN Namespace
+
+
+Appendix: Example Code
+----------------------
+
+All popular languages have at least one library that allows UUID generation.
+In the unlikely event that one isn't available, generating version 4 UUIDs
+is quite simple.  Below is sample pseudo-code for reference.  It is intended
+as supplemental information only and not intended as part of the specification.
+
+The following code assumes that `random_byte` is a function which returns a
+random byte, and that the `hexdump` functions returns a string representing
+the hexdumped range of bytes passed in.
+
+```
+def generate_binary_uuid():
+    uuid = []
+    for i = 0 to 15:
+        uuid.append(random_byte())
+
+	/* version 4 */
+	uuid[6] &= 0x0f
+	uuid[6] |= 0x40
+
+	/* variant 1 */
+	uuid[8] &= 0x3f
+	uuid[8] |= 0x80
+
+    return uuid
+```
+
+This raw uuid can be pretty-printed with the following code. 
+
+```
+def pretty_print_uuid(raw):
+	out = ""
+	out += hexdump(raw, 0, 4);
+	out += "-"
+	out += hexdump(raw, 4, 2);
+	out += "-"
+	out += hexdump(raw, 6, 2);
+	out += "-"
+	out += hexdump(raw, 8, 2);
+	out += "-"
+	out += hexdump(raw, 10, 6);
+
+	return out
+```
+
+Note that the random bytes must be cryptographically pseudo-random to avoid
+accidental generation of duplicate UUIDs.