1+ var crypto = require ( 'crypto' ) ;
2+
3+ function rng ( ) {
4+ return crypto . randomBytes ( 16 ) ;
5+ } ;
6+
7+ var byteToHex = [ ] ;
8+ for ( var i = 0 ; i < 256 ; ++ i ) {
9+ byteToHex [ i ] = ( i + 0x100 ) . toString ( 16 ) . substr ( 1 ) ;
10+ }
11+
12+ function bytesToUuid ( buf , offset ) {
13+ var i = offset || 0 ;
14+ var bth = byteToHex ;
15+ // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4
16+ return ( [
17+ bth [ buf [ i ++ ] ] , bth [ buf [ i ++ ] ] ,
18+ bth [ buf [ i ++ ] ] , bth [ buf [ i ++ ] ] , '-' ,
19+ bth [ buf [ i ++ ] ] , bth [ buf [ i ++ ] ] , '-' ,
20+ bth [ buf [ i ++ ] ] , bth [ buf [ i ++ ] ] , '-' ,
21+ bth [ buf [ i ++ ] ] , bth [ buf [ i ++ ] ] , '-' ,
22+ bth [ buf [ i ++ ] ] , bth [ buf [ i ++ ] ] ,
23+ bth [ buf [ i ++ ] ] , bth [ buf [ i ++ ] ] ,
24+ bth [ buf [ i ++ ] ] , bth [ buf [ i ++ ] ]
25+ ] ) . join ( '' ) ;
26+ }
27+
28+ function v4 ( options , buf , offset ) {
29+ var i = buf && offset || 0 ;
30+
31+ if ( typeof ( options ) == 'string' ) {
32+ buf = options === 'binary' ? new Array ( 16 ) : null ;
33+ options = null ;
34+ }
35+ options = options || { } ;
36+
37+ var rnds = options . random || ( options . rng || rng ) ( ) ;
38+
39+ // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
40+ rnds [ 6 ] = ( rnds [ 6 ] & 0x0f ) | 0x40 ;
41+ rnds [ 8 ] = ( rnds [ 8 ] & 0x3f ) | 0x80 ;
42+
43+ // Copy bytes to buffer, if provided
44+ if ( buf ) {
45+ for ( var ii = 0 ; ii < 16 ; ++ ii ) {
46+ buf [ i + ii ] = rnds [ ii ] ;
47+ }
48+ }
49+
50+ return buf || bytesToUuid ( rnds ) ;
51+ }
52+
53+ module . exports = v4 ;
0 commit comments