v4.js 680 B

1234567891011121314151617181920212223242526272829
  1. import native from './native.js';
  2. import rng from './rng.js';
  3. import { unsafeStringify } from './stringify.js';
  4. function v4(options, buf, offset) {
  5. if (native.randomUUID && !buf && !options) {
  6. return native.randomUUID();
  7. }
  8. options = options || {};
  9. const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
  10. rnds[6] = rnds[6] & 0x0f | 0x40;
  11. rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
  12. if (buf) {
  13. offset = offset || 0;
  14. for (let i = 0; i < 16; ++i) {
  15. buf[offset + i] = rnds[i];
  16. }
  17. return buf;
  18. }
  19. return unsafeStringify(rnds);
  20. }
  21. export default v4;