You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

57 lines
1.6 KiB

4 years ago
  1. var bytesToUuid = require('./bytesToUuid');
  2. function uuidToBytes(uuid) {
  3. // Note: We assume we're being passed a valid uuid string
  4. var bytes = [];
  5. uuid.replace(/[a-fA-F0-9]{2}/g, function(hex) {
  6. bytes.push(parseInt(hex, 16));
  7. });
  8. return bytes;
  9. }
  10. function stringToBytes(str) {
  11. str = unescape(encodeURIComponent(str)); // UTF8 escape
  12. var bytes = new Array(str.length);
  13. for (var i = 0; i < str.length; i++) {
  14. bytes[i] = str.charCodeAt(i);
  15. }
  16. return bytes;
  17. }
  18. module.exports = function(name, version, hashfunc) {
  19. var generateUUID = function(value, namespace, buf, offset) {
  20. var off = buf && offset || 0;
  21. if (typeof(value) == 'string') value = stringToBytes(value);
  22. if (typeof(namespace) == 'string') namespace = uuidToBytes(namespace);
  23. if (!Array.isArray(value)) throw TypeError('value must be an array of bytes');
  24. if (!Array.isArray(namespace) || namespace.length !== 16) throw TypeError('namespace must be uuid string or an Array of 16 byte values');
  25. // Per 4.3
  26. var bytes = hashfunc(namespace.concat(value));
  27. bytes[6] = (bytes[6] & 0x0f) | version;
  28. bytes[8] = (bytes[8] & 0x3f) | 0x80;
  29. if (buf) {
  30. for (var idx = 0; idx < 16; ++idx) {
  31. buf[off+idx] = bytes[idx];
  32. }
  33. }
  34. return buf || bytesToUuid(bytes);
  35. };
  36. // Function#name is not settable on some platforms (#270)
  37. try {
  38. generateUUID.name = name;
  39. } catch (err) {
  40. }
  41. // Pre-defined namespaces, per Appendix C
  42. generateUUID.DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
  43. generateUUID.URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
  44. return generateUUID;
  45. };