stringify.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. exports.unsafeStringify = unsafeStringify;
  7. var _validate = _interopRequireDefault(require("./validate.js"));
  8. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  9. /**
  10. * Convert array of 16 byte values to UUID string format of the form:
  11. * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
  12. */
  13. const byteToHex = [];
  14. for (let i = 0; i < 256; ++i) {
  15. byteToHex.push((i + 0x100).toString(16).slice(1));
  16. }
  17. function unsafeStringify(arr, offset = 0) {
  18. // Note: Be careful editing this code! It's been tuned for performance
  19. // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
  20. return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]];
  21. }
  22. function stringify(arr, offset = 0) {
  23. const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one
  24. // of the following:
  25. // - One or more input array values don't map to a hex octet (leading to
  26. // "undefined" in the uuid)
  27. // - Invalid input values for the RFC `version` or `variant` fields
  28. if (!(0, _validate.default)(uuid)) {
  29. throw TypeError('Stringified UUID is invalid');
  30. }
  31. return uuid;
  32. }
  33. var _default = stringify;
  34. exports.default = _default;