diff --git a/.gitignore b/.gitignore index 88861393..fd4f2b06 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,2 @@ node_modules .DS_Store -.nyc_output -coverage diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 00000000..d1b90db7 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - "4" + - "6" diff --git a/AUTHORS b/AUTHORS new file mode 100644 index 00000000..5a105230 --- /dev/null +++ b/AUTHORS @@ -0,0 +1,5 @@ +Robert Kieffer +Christoph Tavan +AJ ONeal +Vincent Voyer +Roman Shtylman diff --git a/HISTORY.md b/HISTORY.md new file mode 100644 index 00000000..716a0394 --- /dev/null +++ b/HISTORY.md @@ -0,0 +1,24 @@ +# 3.0.0 (2016-11-17) + + * remove .parse and .unparse + +# 2.0.0 + + * Removed uuid.BufferClass + +# 1.4.0 + + * Improved module context detection + * Removed public RNG functions + +# 1.3.2 + + * Improve tests and handling of v1() options (Issue #24) + * Expose RNG option to allow for perf testing with different generators + +# 1.3.0 + + * Support for version 1 ids, thanks to [@ctavan](https://github.com/ctavan)! + * Support for node.js crypto API + * De-emphasizing performance in favor of a) cryptographic quality PRNGs where available and b) more manageable code + diff --git a/LICENSE.md b/LICENSE.md index 652609b3..8c84e398 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2010-2012 Robert Kieffer +Copyright (c) 2010-2016 Robert Kieffer and other contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index 5cd85550..e837ecb5 100644 --- a/README.md +++ b/README.md @@ -1,49 +1,46 @@ -# node-uuid +# uuid [![Build Status](https://secure.travis-ci.org/kelektiv/node-uuid.svg?branch=master)](http://travis-ci.org/kelektiv/node-uuid) # Simple, fast generation of [RFC4122](http://www.ietf.org/rfc/rfc4122.txt) UUIDS. Features: * Generate RFC4122 version 1 or version 4 UUIDs -* Runs in node.js and all browsers. -* Registered as a [ComponentJS](https://github.com/component/component) [component](https://github.com/component/component/wiki/Components) ('broofa/node-uuid'). -* Cryptographically strong random # generation - * `crypto.randomBytes(n)` in node.js - * `window.crypto.getRandomValues(ta)` in [supported browsers](https://developer.mozilla.org/en-US/docs/Web/API/RandomSource/getRandomValues#Browser_Compatibility) -* 1.1K minified and gzip'ed (Want something smaller? Check this [crazy shit](https://gist.github.com/982883) out! ) -* [Annotated source code](http://broofa.github.com/node-uuid/docs/uuid.html) -* Comes with a Command Line Interface for generating uuids on the command line +* Runs in node.js and browsers +* Cryptographically strong random number generation on supporting platforms +* Small footprint (Want something smaller? [Check this out](https://gist.github.com/982883) out!) -## Getting Started - -Install it in your browser: - -```html - -``` - -Or in node.js: +## Quickstart - nodejs -``` -npm install node-uuid +```shell +npm install uuid ``` ```javascript -var uuid = require('node-uuid'); -``` +const uuid = require('uuid'); -Then create some ids ... +// Generate a v4 (random) id +uuid() // -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1' -```javascript // Generate a v1 (time-based) id uuid.v1(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a' +``` -// Generate a v4 (random) id -uuid.v4(); // -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1' +## Quickstart - browser + +** Not recommende for production or even semi-production use. Use a bundling tool instead (i.e. webpack, browserify, rollup, etc)** + +[wzrd.in](https://github.com/jfhbrook/wzrd.in) will serve up any npm module after performing basic bundling and minification. + +```html + ``` ## API +### uuid(...) + +Generate a V4 uuid. See uuid.v4 documentation below. + ### uuid.v1([`options` [, `buffer` [, `offset`]]]) Generate and return a RFC4122 v1 (timestamp-based) UUID. @@ -79,13 +76,9 @@ Example: In-place generation of two binary IDs ```javascript // Generate two ids in an array -var arr = new Array(32); // -> [] +const arr = new Array(32); // -> [] uuid.v1(null, arr, 0); // -> [02 a2 ce 90 14 32 11 e1 85 58 0b 48 8e 4f c1 15] uuid.v1(null, arr, 16); // -> [02 a2 ce 90 14 32 11 e1 85 58 0b 48 8e 4f c1 15 02 a3 1c b0 14 32 11 e1 85 58 0b 48 8e 4f c1 15] - -// Optionally use uuid.unparse() to get stringify the ids -uuid.unparse(buffer); // -> '02a2ce90-1432-11e1-8558-0b488e4fc115' -uuid.unparse(buffer, 16) // -> '02a31cb0-1432-11e1-8558-0b488e4fc115' ``` ### uuid.v4([`options` [, `buffer` [, `offset`]]]) @@ -117,138 +110,17 @@ uuid.v4({ Example: Generate two IDs in a single buffer ```javascript -var buffer = new Array(32); // (or 'new Buffer' in node.js) +const buffer = new Array(32); // (or 'new Buffer' in node.js) uuid.v4(null, buffer, 0); uuid.v4(null, buffer, 16); ``` -### uuid.parse(id[, buffer[, offset]]) -### uuid.unparse(buffer[, offset]) - -Parse and unparse UUIDs - - * `id` - (String) UUID(-like) string - * `buffer` - (Array | Buffer) Array or buffer where UUID bytes are to be written. Default: A new Array or Buffer is used - * `offset` - (Number) Starting index in `buffer` at which to begin writing. Default: 0 - -Example parsing and unparsing a UUID string - -```javascript -var bytes = uuid.parse('797ff043-11eb-11e1-80d6-510998755d10'); // -> -var string = uuid.unparse(bytes); // -> '797ff043-11eb-11e1-80d6-510998755d10' -``` - -### uuid.noConflict() - -(Browsers only) Set `uuid` property back to it's previous value. - -Returns the node-uuid object. - -Example: - -```javascript -var myUuid = uuid.noConflict(); -myUuid.v1(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a' -``` - -## Deprecated APIs - -Support for the following v1.2 APIs is available in v1.3, but is deprecated and will be removed in the next major version. - -### uuid([format [, buffer [, offset]]]) - -uuid() has become uuid.v4(), and the `format` argument is now implicit in the `buffer` argument. (i.e. if you specify a buffer, the format is assumed to be binary). - -### uuid.BufferClass - -The class of container created when generating binary uuid data if no buffer argument is specified. This is expected to go away, with no replacement API. - -## Command Line Interface - -To use the executable, it's probably best to install this library globally. - -`npm install -g node-uuid` - -Usage: - -``` -USAGE: uuid [version] [options] - - -options: - ---help Display this message and exit -``` - -`version` must be an RFC4122 version that is supported by this library, which is currently version 1 and version 4 (denoted by "v1" and "v4", respectively). `version` defaults to version 4 when not supplied. - -### Examples - -``` -> uuid -3a91f950-dec8-4688-ba14-5b7bbfc7a563 -``` - -``` -> uuid v1 -9d0b43e0-7696-11e3-964b-250efa37a98e -``` - -``` -> uuid v4 -6790ac7c-24ac-4f98-8464-42f6d98a53ae -``` - ## Testing -In node.js - ``` npm test ``` -In Browser - -``` -open test/test.html -``` - -### Benchmarking - -Requires node.js - -``` -npm install uuid uuid-js -node benchmark/benchmark.js -``` - -For a more complete discussion of node-uuid performance, please see the `benchmark/README.md` file, and the [benchmark wiki](https://github.com/broofa/node-uuid/wiki/Benchmark) - -For browser performance [checkout the JSPerf tests](http://jsperf.com/node-uuid-performance). - -## Release notes - -### 1.4.6 - -* Properly detect node crypto and whatwg crypto -* Workaround phantomjs/browserify bug -* Explicit check for `window` rather implicit this-global -* Issue warning if Math.random() is being used -* "use strict"; -* A few jshint / stylistic updates (=== and such) - -### 1.4.0 - -* Improved module context detection -* Removed public RNG functions - -### 1.3.2 - -* Improve tests and handling of v1() options (Issue #24) -* Expose RNG option to allow for perf testing with different generators - -### 1.3.0 +## Legacy node-uuid package -* Support for version 1 ids, thanks to [@ctavan](https://github.com/ctavan)! -* Support for node.js crypto API -* De-emphasizing performance in favor of a) cryptographic quality PRNGs where available and b) more manageable code +The code for the legacy node-uuid package is available in the `node-uuid` branch. diff --git a/benchmark/README.md b/benchmark/README.md deleted file mode 100644 index aaeb2ea0..00000000 --- a/benchmark/README.md +++ /dev/null @@ -1,53 +0,0 @@ -# node-uuid Benchmarks - -### Results - -To see the results of our benchmarks visit https://github.com/broofa/node-uuid/wiki/Benchmark - -### Run them yourself - -node-uuid comes with some benchmarks to measure performance of generating UUIDs. These can be run using node.js. node-uuid is being benchmarked against some other uuid modules, that are available through npm namely `uuid` and `uuid-js`. - -To prepare and run the benchmark issue; - -``` -npm install uuid uuid-js -node benchmark/benchmark.js -``` - -You'll see an output like this one: - -``` -# v4 -nodeuuid.v4(): 854700 uuids/second -nodeuuid.v4('binary'): 788643 uuids/second -nodeuuid.v4('binary', buffer): 1336898 uuids/second -uuid(): 479386 uuids/second -uuid('binary'): 582072 uuids/second -uuidjs.create(4): 312304 uuids/second - -# v1 -nodeuuid.v1(): 938086 uuids/second -nodeuuid.v1('binary'): 683060 uuids/second -nodeuuid.v1('binary', buffer): 1644736 uuids/second -uuidjs.create(1): 190621 uuids/second -``` - -* The `uuid()` entries are for Nikhil Marathe's [uuid module](https://bitbucket.org/nikhilm/uuidjs) which is a wrapper around the native libuuid library. -* The `uuidjs()` entries are for Patrick Negri's [uuid-js module](https://github.com/pnegri/uuid-js) which is a pure javascript implementation based on [UUID.js](https://github.com/LiosK/UUID.js) by LiosK. - -If you want to get more reliable results you can run the benchmark multiple times and write the output into a log file: - -``` -for i in {0..9}; do node benchmark/benchmark.js >> benchmark/bench_0.4.12.log; done; -``` - -If you're interested in how performance varies between different node versions, you can issue the above command multiple times. - -You can then use the shell script `bench.sh` provided in this directory to calculate the averages over all benchmark runs and draw a nice plot: - -``` -(cd benchmark/ && ./bench.sh) -``` - -This assumes you have [gnuplot](http://www.gnuplot.info/) and [ImageMagick](http://www.imagemagick.org/) installed. You'll find a nice `bench.png` graph in the `benchmark/` directory then. diff --git a/benchmark/bench.gnu b/benchmark/bench.gnu deleted file mode 100644 index a342fbbe..00000000 --- a/benchmark/bench.gnu +++ /dev/null @@ -1,174 +0,0 @@ -#!/opt/local/bin/gnuplot -persist -# -# -# G N U P L O T -# Version 4.4 patchlevel 3 -# last modified March 2011 -# System: Darwin 10.8.0 -# -# Copyright (C) 1986-1993, 1998, 2004, 2007-2010 -# Thomas Williams, Colin Kelley and many others -# -# gnuplot home: http://www.gnuplot.info -# faq, bugs, etc: type "help seeking-assistance" -# immediate help: type "help" -# plot window: hit 'h' -set terminal postscript eps noenhanced defaultplex \ - leveldefault color colortext \ - solid linewidth 1.2 butt noclip \ - palfuncparam 2000,0.003 \ - "Helvetica" 14 -set output 'bench.eps' -unset clip points -set clip one -unset clip two -set bar 1.000000 front -set border 31 front linetype -1 linewidth 1.000 -set xdata -set ydata -set zdata -set x2data -set y2data -set timefmt x "%d/%m/%y,%H:%M" -set timefmt y "%d/%m/%y,%H:%M" -set timefmt z "%d/%m/%y,%H:%M" -set timefmt x2 "%d/%m/%y,%H:%M" -set timefmt y2 "%d/%m/%y,%H:%M" -set timefmt cb "%d/%m/%y,%H:%M" -set boxwidth -set style fill empty border -set style rectangle back fc lt -3 fillstyle solid 1.00 border lt -1 -set style circle radius graph 0.02, first 0, 0 -set dummy x,y -set format x "% g" -set format y "% g" -set format x2 "% g" -set format y2 "% g" -set format z "% g" -set format cb "% g" -set angles radians -unset grid -set key title "" -set key outside left top horizontal Right noreverse enhanced autotitles columnhead nobox -set key noinvert samplen 4 spacing 1 width 0 height 0 -set key maxcolumns 2 maxrows 0 -unset label -unset arrow -set style increment default -unset style line -set style line 1 linetype 1 linewidth 2.000 pointtype 1 pointsize default pointinterval 0 -unset style arrow -set style histogram clustered gap 2 title offset character 0, 0, 0 -unset logscale -set offsets graph 0.05, 0.15, 0, 0 -set pointsize 1.5 -set pointintervalbox 1 -set encoding default -unset polar -unset parametric -unset decimalsign -set view 60, 30, 1, 1 -set samples 100, 100 -set isosamples 10, 10 -set surface -unset contour -set clabel '%8.3g' -set mapping cartesian -set datafile separator whitespace -unset hidden3d -set cntrparam order 4 -set cntrparam linear -set cntrparam levels auto 5 -set cntrparam points 5 -set size ratio 0 1,1 -set origin 0,0 -set style data points -set style function lines -set xzeroaxis linetype -2 linewidth 1.000 -set yzeroaxis linetype -2 linewidth 1.000 -set zzeroaxis linetype -2 linewidth 1.000 -set x2zeroaxis linetype -2 linewidth 1.000 -set y2zeroaxis linetype -2 linewidth 1.000 -set ticslevel 0.5 -set mxtics default -set mytics default -set mztics default -set mx2tics default -set my2tics default -set mcbtics default -set xtics border in scale 1,0.5 mirror norotate offset character 0, 0, 0 -set xtics norangelimit -set xtics () -set ytics border in scale 1,0.5 mirror norotate offset character 0, 0, 0 -set ytics autofreq norangelimit -set ztics border in scale 1,0.5 nomirror norotate offset character 0, 0, 0 -set ztics autofreq norangelimit -set nox2tics -set noy2tics -set cbtics border in scale 1,0.5 mirror norotate offset character 0, 0, 0 -set cbtics autofreq norangelimit -set title "" -set title offset character 0, 0, 0 font "" norotate -set timestamp bottom -set timestamp "" -set timestamp offset character 0, 0, 0 font "" norotate -set rrange [ * : * ] noreverse nowriteback # (currently [8.98847e+307:-8.98847e+307] ) -set autoscale rfixmin -set autoscale rfixmax -set trange [ * : * ] noreverse nowriteback # (currently [-5.00000:5.00000] ) -set autoscale tfixmin -set autoscale tfixmax -set urange [ * : * ] noreverse nowriteback # (currently [-10.0000:10.0000] ) -set autoscale ufixmin -set autoscale ufixmax -set vrange [ * : * ] noreverse nowriteback # (currently [-10.0000:10.0000] ) -set autoscale vfixmin -set autoscale vfixmax -set xlabel "" -set xlabel offset character 0, 0, 0 font "" textcolor lt -1 norotate -set x2label "" -set x2label offset character 0, 0, 0 font "" textcolor lt -1 norotate -set xrange [ * : * ] noreverse nowriteback # (currently [-0.150000:3.15000] ) -set autoscale xfixmin -set autoscale xfixmax -set x2range [ * : * ] noreverse nowriteback # (currently [0.00000:3.00000] ) -set autoscale x2fixmin -set autoscale x2fixmax -set ylabel "" -set ylabel offset character 0, 0, 0 font "" textcolor lt -1 rotate by -270 -set y2label "" -set y2label offset character 0, 0, 0 font "" textcolor lt -1 rotate by -270 -set yrange [ 0.00000 : 1.90000e+06 ] noreverse nowriteback # (currently [:] ) -set autoscale yfixmin -set autoscale yfixmax -set y2range [ * : * ] noreverse nowriteback # (currently [0.00000:1.90000e+06] ) -set autoscale y2fixmin -set autoscale y2fixmax -set zlabel "" -set zlabel offset character 0, 0, 0 font "" textcolor lt -1 norotate -set zrange [ * : * ] noreverse nowriteback # (currently [-10.0000:10.0000] ) -set autoscale zfixmin -set autoscale zfixmax -set cblabel "" -set cblabel offset character 0, 0, 0 font "" textcolor lt -1 rotate by -270 -set cbrange [ * : * ] noreverse nowriteback # (currently [8.98847e+307:-8.98847e+307] ) -set autoscale cbfixmin -set autoscale cbfixmax -set zero 1e-08 -set lmargin -1 -set bmargin -1 -set rmargin -1 -set tmargin -1 -set pm3d explicit at s -set pm3d scansautomatic -set pm3d interpolate 1,1 flush begin noftriangles nohidden3d corners2color mean -set palette positive nops_allcF maxcolors 0 gamma 1.5 color model RGB -set palette rgbformulae 7, 5, 15 -set colorbox default -set colorbox vertical origin screen 0.9, 0.2, 0 size screen 0.05, 0.6, 0 front bdefault -set loadpath -set fontpath -set fit noerrorvariables -GNUTERM = "aqua" -plot 'bench_results.txt' using 2:xticlabel(1) w lp lw 2, '' using 3:xticlabel(1) w lp lw 2, '' using 4:xticlabel(1) w lp lw 2, '' using 5:xticlabel(1) w lp lw 2, '' using 6:xticlabel(1) w lp lw 2, '' using 7:xticlabel(1) w lp lw 2, '' using 8:xticlabel(1) w lp lw 2, '' using 9:xticlabel(1) w lp lw 2 -# EOF diff --git a/benchmark/bench.sh b/benchmark/bench.sh deleted file mode 100755 index d870a0cb..00000000 --- a/benchmark/bench.sh +++ /dev/null @@ -1,34 +0,0 @@ -#!/bin/bash - -# for a given node version run: -# for i in {0..9}; do node benchmark.js >> bench_0.6.2.log; done; - -PATTERNS=('nodeuuid.v1()' "nodeuuid.v1('binary'," 'nodeuuid.v4()' "nodeuuid.v4('binary'," "uuid()" "uuid('binary')" 'uuidjs.create(1)' 'uuidjs.create(4)' '140byte') -FILES=(node_uuid_v1_string node_uuid_v1_buf node_uuid_v4_string node_uuid_v4_buf libuuid_v4_string libuuid_v4_binary uuidjs_v1_string uuidjs_v4_string 140byte_es) -INDICES=(2 3 2 3 2 2 2 2 2) -VERSIONS=$( ls bench_*.log | sed -e 's/^bench_\([0-9\.]*\)\.log/\1/' | tr "\\n" " " ) -TMPJOIN="tmp_join" -OUTPUT="bench_results.txt" - -for I in ${!FILES[*]}; do - F=${FILES[$I]} - P=${PATTERNS[$I]} - INDEX=${INDICES[$I]} - echo "version $F" > $F - for V in $VERSIONS; do - (VAL=$( grep "$P" bench_$V.log | LC_ALL=en_US awk '{ sum += $'$INDEX' } END { print sum/NR }' ); echo $V $VAL) >> $F - done - if [ $I == 0 ]; then - cat $F > $TMPJOIN - else - join $TMPJOIN $F > $OUTPUT - cp $OUTPUT $TMPJOIN - fi - rm $F -done - -rm $TMPJOIN - -gnuplot bench.gnu -convert -density 200 -resize 800x560 -flatten bench.eps bench.png -rm bench.eps diff --git a/benchmark/benchmark-native.c b/benchmark/benchmark-native.c deleted file mode 100644 index dbfc75f6..00000000 --- a/benchmark/benchmark-native.c +++ /dev/null @@ -1,34 +0,0 @@ -/* -Test performance of native C UUID generation - -To Compile: cc -luuid benchmark-native.c -o benchmark-native -*/ - -#include -#include -#include -#include - -int main() { - uuid_t myid; - char buf[36+1]; - int i; - struct timeval t; - double start, finish; - - gettimeofday(&t, NULL); - start = t.tv_sec + t.tv_usec/1e6; - - int n = 2e5; - for (i = 0; i < n; i++) { - uuid_generate(myid); - uuid_unparse(myid, buf); - } - - gettimeofday(&t, NULL); - finish = t.tv_sec + t.tv_usec/1e6; - double dur = finish - start; - - printf("%d uuids/sec", (int)(n/dur)); - return 0; -} diff --git a/benchmark/benchmark.js b/benchmark/benchmark.js deleted file mode 100644 index 40e6efbe..00000000 --- a/benchmark/benchmark.js +++ /dev/null @@ -1,84 +0,0 @@ -try { - var nodeuuid = require('../uuid'); -} catch (e) { - console.error('node-uuid require failed - skipping tests'); -} - -try { - var uuid = require('uuid'); -} catch (e) { - console.error('uuid require failed - skipping tests'); -} - -try { - var uuidjs = require('uuid-js'); -} catch (e) { - console.error('uuid-js require failed - skipping tests'); -} - -var N = 5e5; - -function rate(msg, t) { - console.log(msg + ': ' + - (N / (Date.now() - t) * 1e3 | 0) + - ' uuids/second'); -} - -console.log('# v4'); - -// node-uuid - string form -if (nodeuuid) { - for (var i = 0, t = Date.now(); i < N; i++) nodeuuid.v4(); - rate('nodeuuid.v4() - using node.js crypto RNG', t); - - for (var i = 0, t = Date.now(); i < N; i++) nodeuuid.v4({rng: nodeuuid.mathRNG}); - rate('nodeuuid.v4() - using Math.random() RNG', t); - - for (var i = 0, t = Date.now(); i < N; i++) nodeuuid.v4('binary'); - rate('nodeuuid.v4(\'binary\')', t); - - var buffer = new nodeuuid.BufferClass(16); - for (var i = 0, t = Date.now(); i < N; i++) nodeuuid.v4('binary', buffer); - rate('nodeuuid.v4(\'binary\', buffer)', t); -} - -// libuuid - string form -if (uuid) { - for (var i = 0, t = Date.now(); i < N; i++) uuid(); - rate('uuid()', t); - - for (var i = 0, t = Date.now(); i < N; i++) uuid('binary'); - rate('uuid(\'binary\')', t); -} - -// uuid-js - string form -if (uuidjs) { - for (var i = 0, t = Date.now(); i < N; i++) uuidjs.create(4); - rate('uuidjs.create(4)', t); -} - -// 140byte.es -for (var i = 0, t = Date.now(); i < N; i++) 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,function(s,r){r=Math.random()*16|0;return (s=='x'?r:r&0x3|0x8).toString(16)}); -rate('140byte.es_v4', t); - -console.log(''); -console.log('# v1'); - -// node-uuid - v1 string form -if (nodeuuid) { - for (var i = 0, t = Date.now(); i < N; i++) nodeuuid.v1(); - rate('nodeuuid.v1()', t); - - for (var i = 0, t = Date.now(); i < N; i++) nodeuuid.v1('binary'); - rate('nodeuuid.v1(\'binary\')', t); - - var buffer = new nodeuuid.BufferClass(16); - for (var i = 0, t = Date.now(); i < N; i++) nodeuuid.v1('binary', buffer); - rate('nodeuuid.v1(\'binary\', buffer)', t); -} - -// uuid-js - v1 string form -if (uuidjs) { - for (var i = 0, t = Date.now(); i < N; i++) uuidjs.create(1); - rate('uuidjs.create(1)', t); -} diff --git a/bower.json b/bower.json deleted file mode 100644 index c0925e19..00000000 --- a/bower.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "node-uuid", - "version": "1.4.7", - "homepage": "https://github.com/broofa/node-uuid", - "authors": [ - "Robert Kieffer " - ], - "description": "Rigorous implementation of RFC4122 (v1 and v4) UUIDs.", - "main": "uuid.js", - "keywords": [ - "uuid", - "gid", - "rfc4122" - ], - "license": "MIT", - "ignore": [ - "**/.*", - "node_modules", - "bower_components", - "test", - "tests" - ] -} diff --git a/lib/rng-browser.js b/lib/rng-browser.js new file mode 100644 index 00000000..82ffaf64 --- /dev/null +++ b/lib/rng-browser.js @@ -0,0 +1,32 @@ + +var rng; + +var crypto = global.crypto || global.msCrypto; // for IE 11 +if (crypto && crypto.getRandomValues) { + // WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto + // Moderately fast, high quality + var _rnds8 = new Uint8Array(16); + rng = function whatwgRNG() { + crypto.getRandomValues(_rnds8); + return _rnds8; + }; +} + +if (!rng) { + // Math.random()-based (RNG) + // + // If all else fails, use Math.random(). It's fast, but is of unspecified + // quality. + var _rnds = new Array(16); + rng = function() { + for (var i = 0, r; i < 16; i++) { + if ((i & 0x03) === 0) r = Math.random() * 0x100000000; + _rnds[i] = r >>> ((i & 0x03) << 3) & 0xff; + } + + return _rnds; + }; +} + +module.exports = rng; + diff --git a/lib/rng.js b/lib/rng.js new file mode 100644 index 00000000..3977f798 --- /dev/null +++ b/lib/rng.js @@ -0,0 +1,4 @@ +var rb = require('crypto').randomBytes; +module.exports = function() { + return rb(16); +}; diff --git a/package.json b/package.json index d684927b..1a9e6b66 100644 --- a/package.json +++ b/package.json @@ -1,56 +1,28 @@ { - "author": { - "email": "robert@broofa.com", - "name": "Robert Kieffer" - }, - "bin": { - "uuid": "./bin/uuid" - }, - "bugs": { - "url": "https://github.com/broofa/node-uuid/issues" - }, - "contributors": [ - { - "name": "AJ ONeal", - "email": "coolaj86@gmail.com" - }, - { - "name": "Christoph Tavan", - "email": "dev@tavan.de" - } - ], - "dependencies": {}, - "description": "Rigorous implementation of RFC4122 (v1 and v4) UUIDs.", - "devDependencies": { - "nyc": "^2.2.0" - }, - "directories": {}, - "homepage": "https://github.com/broofa/node-uuid", - "installable": true, + "name": "uuid", + "version": "3.0.0", + "description": "RFC4122 (v1 and v4) generator", "keywords": [ + "uuid", "guid", - "rfc4122", - "uuid" + "rfc4122" ], - "lib": ".", "license": "MIT", "main": "./uuid.js", - "maintainers": [ - { - "name": "broofa", - "email": "robert@broofa.com" - } - ], - "name": "node-uuid", - "optionalDependencies": {}, - "repository": { - "type": "git", - "url": "https://github.com/broofa/node-uuid.git" + "bin": { + "uuid": "./bin/uuid" + }, + "devDependencies": { + "mocha": "3.1.2" }, "scripts": { - "coverage": "nyc npm test && nyc report", - "test": "node test/test.js" + "test": "mocha test/test.js" + }, + "browser": { + "./lib/rng.js": "./lib/rng-browser.js" }, - "url": "http://github.com/broofa/node-uuid", - "version": "1.4.7" -} + "repository": { + "type": "git", + "url": "https://github.com/kelektiv/node-uuid.git" + } +} \ No newline at end of file diff --git a/test/compare_v1.js b/test/compare_v1.js deleted file mode 100644 index 05af8221..00000000 --- a/test/compare_v1.js +++ /dev/null @@ -1,63 +0,0 @@ -var assert = require('assert'), - nodeuuid = require('../uuid'), - uuidjs = require('uuid-js'), - libuuid = require('uuid').generate, - util = require('util'), - exec = require('child_process').exec, - os = require('os'); - -// On Mac Os X / macports there's only the ossp-uuid package that provides uuid -// On Linux there's uuid-runtime which provides uuidgen -var uuidCmd = os.type() === 'Darwin' ? 'uuid -1' : 'uuidgen -t'; - -function compare(ids) { - console.log(ids); - for (var i = 0; i < ids.length; i++) { - var id = ids[i].split('-'); - id = [id[2], id[1], id[0]].join(''); - ids[i] = id; - } - var sorted = ([].concat(ids)).sort(); - - if (sorted.toString() !== ids.toString()) { - console.log('Warning: sorted !== ids'); - } else { - console.log('everything in order!'); - } -} - -// Test time order of v1 uuids -var ids = []; -while (ids.length < 10e3) ids.push(nodeuuid.v1()); - -var max = 10; -console.log('node-uuid:'); -ids = []; -for (var i = 0; i < max; i++) ids.push(nodeuuid.v1()); -compare(ids); - -console.log(''); -console.log('uuidjs:'); -ids = []; -for (var i = 0; i < max; i++) ids.push(uuidjs.create(1).toString()); -compare(ids); - -console.log(''); -console.log('libuuid:'); -ids = []; -var count = 0; -var last = function() { - compare(ids); -} -var cb = function(err, stdout, stderr) { - ids.push(stdout.substring(0, stdout.length-1)); - count++; - if (count < max) { - return next(); - } - last(); -}; -var next = function() { - exec(uuidCmd, cb); -}; -next(); diff --git a/test/mocha.opts b/test/mocha.opts new file mode 100644 index 00000000..5d6a3113 --- /dev/null +++ b/test/mocha.opts @@ -0,0 +1,3 @@ +--ui qunit +--reporter spec +--check-leaks diff --git a/test/test.html b/test/test.html deleted file mode 100644 index d80326ec..00000000 --- a/test/test.html +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - diff --git a/test/test.js b/test/test.js index 5f1113d8..ec33bec0 100644 --- a/test/test.js +++ b/test/test.js @@ -1,57 +1,21 @@ -if (!this.uuid) { - // node.js - uuid = require('../uuid'); - if (!/_rb/.test(uuid._rng.toString())) { - throw new Error("should use crypto for node.js"); - } -} - -// -// x-platform log/assert shims -// - -function _log(msg, type) { - type = type || 'log'; +var assert = require('assert'); - if (typeof(document) != 'undefined') { - document.write('
' + msg.replace(/\n/g, '
') + '
'); - } - if (typeof(console) != 'undefined') { - var color = { - log: '\033[39m', - warn: '\033[33m', - error: '\033[31m' - }; - console[type](color[type] + msg + color.log); - } -} - -function log(msg) {_log(msg, 'log');} -function warn(msg) {_log(msg, 'warn');} -function error(msg) {_log(msg, 'error');} - -function assert(res, msg) { - if (!res) { - error('FAIL: ' + msg); - } else { - log('Pass: ' + msg); - } -} - -// -// Unit tests -// +var uuid = require('../'); // Verify ordering of v1 ids created with explicit times var TIME = 1321644961388; // 2011-11-18 11:36:01.388-08:00 function compare(name, ids) { - ids = ids.map(function(id) { - return id.split('-').reverse().join('-'); - }).sort(); - var sorted = ([].concat(ids)).sort(); + test(name, function() { + // avoid .map for older browsers + for (var i=0 ; i 10K ids created in 1 ms'); - -// Verify clock regression bumps clockseq -var uidt = uuid.v1({msecs: TIME}); -var uidtb = uuid.v1({msecs: TIME - 1}); -assert( - parseInt(uidtb.split('-')[3], 16) - parseInt(uidt.split('-')[3], 16) === 1, - 'Clock regression by msec increments the clockseq' -); - -// Verify clock regression bumps clockseq -var uidtn = uuid.v1({msecs: TIME, nsecs: 10}); -var uidtnb = uuid.v1({msecs: TIME, nsecs: 9}); -assert( - parseInt(uidtnb.split('-')[3], 16) - parseInt(uidtn.split('-')[3], 16) === 1, - 'Clock regression by nsec increments the clockseq' -); - -// Verify explicit options produce expected id -var id = uuid.v1({ - msecs: 1321651533573, - nsecs: 5432, - clockseq: 0x385c, - node: [ 0x61, 0xcd, 0x3c, 0xbb, 0x32, 0x10 ] +test('msec', function() { + assert( + uuid.v1({msecs: TIME}) != uuid.v1({msecs: TIME}), + 'IDs created at same msec are different' + ); }); -assert(id == 'd9428888-122b-11e1-b85c-61cd3cbb3210', 'Explicit options produce expected id'); - -// Verify adjacent ids across a msec boundary are 1 time unit apart -var u0 = uuid.v1({msecs: TIME, nsecs: 9999}); -var u1 = uuid.v1({msecs: TIME + 1, nsecs: 0}); - -var before = u0.split('-')[0], after = u1.split('-')[0]; -var dt = parseInt(after, 16) - parseInt(before, 16); -assert(dt === 1, 'Ids spanning 1ms boundary are 100ns apart'); - -// -// Test parse/unparse -// - -id = '00112233445566778899aabbccddeeff'; -assert(uuid.unparse(uuid.parse(id.substr(0,10))) == - '00112233-4400-0000-0000-000000000000', 'Short parse'); -assert(uuid.unparse(uuid.parse('(this is the uuid -> ' + id + id)) == - '00112233-4455-6677-8899-aabbccddeeff', 'Dirty parse'); - -// -// Perf tests -// - -var generators = { - v1: uuid.v1, - v4: uuid.v4 -}; - -var UUID_FORMAT = { - v1: /[0-9a-f]{8}-[0-9a-f]{4}-1[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/i, - v4: /[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/i -}; -var N = 1e4; - -// Get %'age an actual value differs from the ideal value -function divergence(actual, ideal) { - return Math.round(100*100*(actual - ideal)/ideal)/100; -} - -function rate(msg, t) { - log(msg + ': ' + (N / (Date.now() - t) * 1e3 | 0) + ' uuids\/second'); -} - -for (var version in generators) { - var counts = {}, max = 0; - var generator = generators[version]; - var format = UUID_FORMAT[version]; - - log('\nSanity check ' + N + ' ' + version + ' uuids'); - for (var i = 0, ok = 0; i < N; i++) { - id = generator(); - if (!format.test(id)) { - throw Error(id + ' is not a valid UUID string'); - } - - if (id != uuid.unparse(uuid.parse(id))) { - assert(fail, id + ' is not a valid id'); - } - - // Count digits for our randomness check - if (version == 'v4') { - var digits = id.replace(/-/g, '').split(''); - for (var j = digits.length-1; j >= 0; j--) { - var c = digits[j]; - max = Math.max(max, counts[c] = (counts[c] || 0) + 1); - } - } +test('exception thrown when > 10k ids created in 1ms', function() { + // Verify throw if too many ids created + var thrown = false; + try { + uuid.v1({msecs: TIME, nsecs: 10000}); + } catch (e) { + thrown = true; } + assert(thrown, 'Exception thrown when > 10K ids created in 1 ms'); +}); - // Check randomness for v4 UUIDs - if (version == 'v4') { - // Limit that we get worried about randomness. (Purely empirical choice, this!) - var limit = 2*100*Math.sqrt(1/N); - - log('\nChecking v4 randomness. Distribution of Hex Digits (% deviation from ideal)'); - - for (var i = 0; i < 16; i++) { - var c = i.toString(16); - var bar = '', n = counts[c], p = Math.round(n/max*100|0); - - // 1-3,5-8, and D-F: 1:16 odds over 30 digits - var ideal = N*30/16; - if (i == 4) { - // 4: 1:1 odds on 1 digit, plus 1:16 odds on 30 digits - ideal = N*(1 + 30/16); - } else if (i >= 8 && i <= 11) { - // 8-B: 1:4 odds on 1 digit, plus 1:16 odds on 30 digits - ideal = N*(1/4 + 30/16); - } else { - // Otherwise: 1:16 odds on 30 digits - ideal = N*30/16; - } - var d = divergence(n, ideal); - - // Draw bar using UTF squares (just for grins) - var s = n/max*50 | 0; - while (s--) bar += '='; - - assert(Math.abs(d) < limit, c + ' |' + bar + '| ' + counts[c] + ' (' + d + '% < ' + limit + '%)'); - } - } -} +test('clock regression by msec', function() { + // Verify clock regression bumps clockseq + var uidt = uuid.v1({msecs: TIME}); + var uidtb = uuid.v1({msecs: TIME - 1}); + assert( + parseInt(uidtb.split('-')[3], 16) - parseInt(uidt.split('-')[3], 16) === 1, + 'Clock regression by msec increments the clockseq' + ); +}); -// Perf tests -for (var version in generators) { - log('\nPerformance testing ' + version + ' UUIDs'); - var generator = generators[version]; - var buf = new uuid.BufferClass(16); +test('clock regression by nsec', function() { + // Verify clock regression bumps clockseq + var uidtn = uuid.v1({msecs: TIME, nsecs: 10}); + var uidtnb = uuid.v1({msecs: TIME, nsecs: 9}); + assert( + parseInt(uidtnb.split('-')[3], 16) - parseInt(uidtn.split('-')[3], 16) === 1, + 'Clock regression by nsec increments the clockseq' + ); +}); - for (var i = 0, t = Date.now(); i < N; i++) generator(); - rate('uuid.' + version + '()', t); +test('explicit options product expected id', function() { + // Verify explicit options produce expected id + var id = uuid.v1({ + msecs: 1321651533573, + nsecs: 5432, + clockseq: 0x385c, + node: [ 0x61, 0xcd, 0x3c, 0xbb, 0x32, 0x10 ] + }); + assert(id == 'd9428888-122b-11e1-b85c-61cd3cbb3210', 'Explicit options produce expected id'); +}); - for (var i = 0, t = Date.now(); i < N; i++) generator('binary'); - rate('uuid.' + version + '(\'binary\')', t); +test('ids spanning 1ms boundary are 100ns apart', function() { + // Verify adjacent ids across a msec boundary are 1 time unit apart + var u0 = uuid.v1({msecs: TIME, nsecs: 9999}); + var u1 = uuid.v1({msecs: TIME + 1, nsecs: 0}); - for (var i = 0, t = Date.now(); i < N; i++) generator('binary', buf); - rate('uuid.' + version + '(\'binary\', buffer)', t); -} + var before = u0.split('-')[0], after = u1.split('-')[0]; + var dt = parseInt(after, 16) - parseInt(before, 16); + assert(dt === 1, 'Ids spanning 1ms boundary are 100ns apart'); +}); diff --git a/uuid.js b/uuid.js index 89c5b8fb..a1f28f75 100644 --- a/uuid.js +++ b/uuid.js @@ -1,272 +1,157 @@ -// uuid.js +// Unique ID creation requires a high quality random # generator. We feature +// detect to determine the best RNG source, normalizing to a function that +// returns 128-bits of randomness, since that's what's usually required +var _rng = require('./lib/rng'); + +// Maps for number <-> hex string conversion +var _byteToHex = []; +var _hexToByte = {}; +for (var i = 0; i < 256; ++i) { + _byteToHex[i] = (i + 0x100).toString(16).substr(1); + _hexToByte[_byteToHex[i]] = i; +} + +function buff_to_string(buf, offset) { + var i = offset || 0; + var bth = _byteToHex; + return bth[buf[i++]] + bth[buf[i++]] + + bth[buf[i++]] + bth[buf[i++]] + '-' + + bth[buf[i++]] + bth[buf[i++]] + '-' + + bth[buf[i++]] + bth[buf[i++]] + '-' + + bth[buf[i++]] + bth[buf[i++]] + '-' + + bth[buf[i++]] + bth[buf[i++]] + + bth[buf[i++]] + bth[buf[i++]] + + bth[buf[i++]] + bth[buf[i++]]; +} + +// **`v1()` - Generate time-based UUID** // -// Copyright (c) 2010-2012 Robert Kieffer -// MIT License - http://opensource.org/licenses/mit-license.php - -/*global window, require, define */ -(function(_window) { - 'use strict'; - - // Unique ID creation requires a high quality random # generator. We feature - // detect to determine the best RNG source, normalizing to a function that - // returns 128-bits of randomness, since that's what's usually required - var _rng, _mathRNG, _nodeRNG, _whatwgRNG, _previousRoot; - - function setupBrowser() { - // Allow for MSIE11 msCrypto - var _crypto = _window.crypto || _window.msCrypto; - - if (!_rng && _crypto && _crypto.getRandomValues) { - // WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto - // - // Moderately fast, high quality - try { - var _rnds8 = new Uint8Array(16); - _whatwgRNG = _rng = function whatwgRNG() { - _crypto.getRandomValues(_rnds8); - return _rnds8; - }; - _rng(); - } catch(e) {} - } - - if (!_rng) { - // Math.random()-based (RNG) - // - // If all else fails, use Math.random(). It's fast, but is of unspecified - // quality. - var _rnds = new Array(16); - _mathRNG = _rng = function() { - for (var i = 0, r; i < 16; i++) { - if ((i & 0x03) === 0) { r = Math.random() * 0x100000000; } - _rnds[i] = r >>> ((i & 0x03) << 3) & 0xff; - } - - return _rnds; - }; - if ('undefined' !== typeof console && console.warn) { - console.warn("[SECURITY] node-uuid: crypto not usable, falling back to insecure Math.random()"); - } - } - } - - function setupNode() { - // Node.js crypto-based RNG - http://nodejs.org/docs/v0.6.2/api/crypto.html - // - // Moderately fast, high quality - if ('function' === typeof require) { - try { - var _rb = require('crypto').randomBytes; - _nodeRNG = _rng = _rb && function() {return _rb(16);}; - _rng(); - } catch(e) {} - } - } - - if (_window) { - setupBrowser(); - } else { - setupNode(); - } - - // Buffer class to use - var BufferClass = ('function' === typeof Buffer) ? Buffer : Array; - - // Maps for number <-> hex string conversion - var _byteToHex = []; - var _hexToByte = {}; - for (var i = 0; i < 256; i++) { - _byteToHex[i] = (i + 0x100).toString(16).substr(1); - _hexToByte[_byteToHex[i]] = i; - } - - // **`parse()` - Parse a UUID into it's component bytes** - function parse(s, buf, offset) { - var i = (buf && offset) || 0, ii = 0; - - buf = buf || []; - s.toLowerCase().replace(/[0-9a-f]{2}/g, function(oct) { - if (ii < 16) { // Don't overflow! - buf[i + ii++] = _hexToByte[oct]; - } - }); - - // Zero out remaining bytes if string was short - while (ii < 16) { - buf[i + ii++] = 0; - } +// Inspired by https://github.com/LiosK/UUID.js +// and http://docs.python.org/library/uuid.html - return buf; - } +// random #'s we need to init node and clockseq +var _seedBytes = _rng(); - // **`unparse()` - Convert UUID byte array (ala parse()) into a string** - function unparse(buf, offset) { - var i = offset || 0, bth = _byteToHex; - return bth[buf[i++]] + bth[buf[i++]] + - bth[buf[i++]] + bth[buf[i++]] + '-' + - bth[buf[i++]] + bth[buf[i++]] + '-' + - bth[buf[i++]] + bth[buf[i++]] + '-' + - bth[buf[i++]] + bth[buf[i++]] + '-' + - bth[buf[i++]] + bth[buf[i++]] + - bth[buf[i++]] + bth[buf[i++]] + - bth[buf[i++]] + bth[buf[i++]]; - } +// Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) +var _nodeId = [ + _seedBytes[0] | 0x01, + _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5] +]; - // **`v1()` - Generate time-based UUID** - // - // Inspired by https://github.com/LiosK/UUID.js - // and http://docs.python.org/library/uuid.html +// Per 4.2.2, randomize (14 bit) clockseq +var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff; - // random #'s we need to init node and clockseq - var _seedBytes = _rng(); +// Previous uuid creation time +var _lastMSecs = 0, _lastNSecs = 0; - // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) - var _nodeId = [ - _seedBytes[0] | 0x01, - _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5] - ]; +// See https://github.com/broofa/node-uuid for API details +function v1(options, buf, offset) { + var i = buf && offset || 0; + var b = buf || []; - // Per 4.2.2, randomize (14 bit) clockseq - var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff; + options = options || {}; - // Previous uuid creation time - var _lastMSecs = 0, _lastNSecs = 0; + var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; - // See https://github.com/broofa/node-uuid for API details - function v1(options, buf, offset) { - var i = buf && offset || 0; - var b = buf || []; + // UUID timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so + // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime(); - options = options || {}; + // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock + var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; - var clockseq = (options.clockseq != null) ? options.clockseq : _clockseq; + // Time since last uuid creation (in msecs) + var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000; - // UUID timestamps are 100 nano-second units since the Gregorian epoch, - // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so - // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' - // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. - var msecs = (options.msecs != null) ? options.msecs : new Date().getTime(); + // Per 4.2.1.2, Bump clockseq on clock regression + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 0x3fff; + } - // Per 4.2.1.2, use count of uuid's generated during the current clock - // cycle to simulate higher resolution clock - var nsecs = (options.nsecs != null) ? options.nsecs : _lastNSecs + 1; + // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; + } - // Time since last uuid creation (in msecs) - var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000; + // Per 4.2.1.2 Throw error if too many uuids are requested + if (nsecs >= 10000) { + throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec'); + } - // Per 4.2.1.2, Bump clockseq on clock regression - if (dt < 0 && options.clockseq == null) { - clockseq = clockseq + 1 & 0x3fff; - } + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; - // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new - // time interval - if ((dt < 0 || msecs > _lastMSecs) && options.nsecs == null) { - nsecs = 0; - } + // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + msecs += 12219292800000; - // Per 4.2.1.2 Throw error if too many uuids are requested - if (nsecs >= 10000) { - throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec'); - } + // `time_low` + var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + b[i++] = tl >>> 24 & 0xff; + b[i++] = tl >>> 16 & 0xff; + b[i++] = tl >>> 8 & 0xff; + b[i++] = tl & 0xff; - _lastMSecs = msecs; - _lastNSecs = nsecs; - _clockseq = clockseq; + // `time_mid` + var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; - // Per 4.1.4 - Convert from unix epoch to Gregorian epoch - msecs += 12219292800000; + // `time_high_and_version` + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + b[i++] = tmh >>> 16 & 0xff; - // `time_low` - var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; - b[i++] = tl >>> 24 & 0xff; - b[i++] = tl >>> 16 & 0xff; - b[i++] = tl >>> 8 & 0xff; - b[i++] = tl & 0xff; + // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + b[i++] = clockseq >>> 8 | 0x80; - // `time_mid` - var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff; - b[i++] = tmh >>> 8 & 0xff; - b[i++] = tmh & 0xff; + // `clock_seq_low` + b[i++] = clockseq & 0xff; - // `time_high_and_version` - b[i++] = tmh >>> 24 & 0xf | 0x10; // include version - b[i++] = tmh >>> 16 & 0xff; + // `node` + var node = options.node || _nodeId; + for (var n = 0; n < 6; ++n) { + b[i + n] = node[n]; + } - // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) - b[i++] = clockseq >>> 8 | 0x80; + return buf ? buf : buff_to_string(b); +} - // `clock_seq_low` - b[i++] = clockseq & 0xff; +// **`v4()` - Generate random UUID** - // `node` - var node = options.node || _nodeId; - for (var n = 0; n < 6; n++) { - b[i + n] = node[n]; - } +// See https://github.com/broofa/node-uuid for API details +function v4(options, buf, offset) { + // Deprecated - 'format' argument, as supported in v1.2 + var i = buf && offset || 0; - return buf ? buf : unparse(b); + if (typeof(options) == 'string') { + buf = options == 'binary' ? new Array(16) : null; + options = null; } + options = options || {}; - // **`v4()` - Generate random UUID** + var rnds = options.random || (options.rng || _rng)(); - // See https://github.com/broofa/node-uuid for API details - function v4(options, buf, offset) { - // Deprecated - 'format' argument, as supported in v1.2 - var i = buf && offset || 0; + // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + rnds[6] = (rnds[6] & 0x0f) | 0x40; + rnds[8] = (rnds[8] & 0x3f) | 0x80; - if (typeof(options) === 'string') { - buf = (options === 'binary') ? new BufferClass(16) : null; - options = null; + // Copy bytes to buffer, if provided + if (buf) { + for (var ii = 0; ii < 16; ++ii) { + buf[i + ii] = rnds[ii]; } - options = options || {}; - - var rnds = options.random || (options.rng || _rng)(); - - // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` - rnds[6] = (rnds[6] & 0x0f) | 0x40; - rnds[8] = (rnds[8] & 0x3f) | 0x80; + } - // Copy bytes to buffer, if provided - if (buf) { - for (var ii = 0; ii < 16; ii++) { - buf[i + ii] = rnds[ii]; - } - } + return buf || buff_to_string(rnds); +} - return buf || unparse(rnds); - } +// Export public API +var uuid = v4; +uuid.v1 = v1; +uuid.v4 = v4; - // Export public API - var uuid = v4; - uuid.v1 = v1; - uuid.v4 = v4; - uuid.parse = parse; - uuid.unparse = unparse; - uuid.BufferClass = BufferClass; - uuid._rng = _rng; - uuid._mathRNG = _mathRNG; - uuid._nodeRNG = _nodeRNG; - uuid._whatwgRNG = _whatwgRNG; - - if (('undefined' !== typeof module) && module.exports) { - // Publish as node.js module - module.exports = uuid; - } else if (typeof define === 'function' && define.amd) { - // Publish as AMD module - define(function() {return uuid;}); - - - } else { - // Publish as global (in browsers) - _previousRoot = _window.uuid; - - // **`noConflict()` - (browser only) to reset global 'uuid' var** - uuid.noConflict = function() { - _window.uuid = _previousRoot; - return uuid; - }; - - _window.uuid = uuid; - } -})('undefined' !== typeof window ? window : null); +module.exports = uuid;