1 | // Copyright (c) Jupyter Development Team.
|
2 | // Distributed under the terms of the Modified BSD License.
|
3 | /*-----------------------------------------------------------------------------
|
4 | | Copyright (c) 2014-2017, PhosphorJS Contributors
|
5 | |
|
6 | | Distributed under the terms of the BSD 3-Clause License.
|
7 | |
|
8 | | The full license is in the file LICENSE, distributed with this software.
|
9 | |----------------------------------------------------------------------------*/
|
10 | /**
|
11 | * A function which creates a function that generates UUID v4 identifiers.
|
12 | *
|
13 | * @returns A new function that creates a UUID v4 string.
|
14 | *
|
15 | * #### Notes
|
16 | * This implementation complies with RFC 4122.
|
17 | *
|
18 | * This uses `Random.getRandomValues()` for random bytes, which in
|
19 | * turn will use the underlying `crypto` module of the platform if
|
20 | * it is available. The fallback for randomness is `Math.random`.
|
21 | */
|
22 | export function uuid4Factory(
|
23 | getRandomValues: (bytes: Uint8Array) => void
|
24 | ): () => string {
|
25 | // Create a 16 byte array to hold the random values.
|
26 | const bytes = new Uint8Array(16);
|
27 |
|
28 | // Create a look up table from bytes to hex strings.
|
29 | const lut = new Array<string>(256);
|
30 |
|
31 | // Pad the single character hex digits with a leading zero.
|
32 | for (let i = 0; i < 16; ++i) {
|
33 | lut[i] = '0' + i.toString(16);
|
34 | }
|
35 |
|
36 | // Populate the rest of the hex digits.
|
37 | for (let i = 16; i < 256; ++i) {
|
38 | lut[i] = i.toString(16);
|
39 | }
|
40 |
|
41 | // Return a function which generates the UUID.
|
42 | return function uuid4(): string {
|
43 | // Get a new batch of random values.
|
44 | getRandomValues(bytes);
|
45 |
|
46 | // Set the UUID version number to 4.
|
47 | bytes[6] = 0x40 | (bytes[6] & 0x0f);
|
48 |
|
49 | // Set the clock sequence bit to the RFC spec.
|
50 | bytes[8] = 0x80 | (bytes[8] & 0x3f);
|
51 |
|
52 | // Assemble the UUID string.
|
53 | return (
|
54 | lut[bytes[0]] +
|
55 | lut[bytes[1]] +
|
56 | lut[bytes[2]] +
|
57 | lut[bytes[3]] +
|
58 | '-' +
|
59 | lut[bytes[4]] +
|
60 | lut[bytes[5]] +
|
61 | '-' +
|
62 | lut[bytes[6]] +
|
63 | lut[bytes[7]] +
|
64 | '-' +
|
65 | lut[bytes[8]] +
|
66 | lut[bytes[9]] +
|
67 | '-' +
|
68 | lut[bytes[10]] +
|
69 | lut[bytes[11]] +
|
70 | lut[bytes[12]] +
|
71 | lut[bytes[13]] +
|
72 | lut[bytes[14]] +
|
73 | lut[bytes[15]]
|
74 | );
|
75 | };
|
76 | }
|