uuid 0.0.1 → 1.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.npmignore ADDED
@@ -0,0 +1,2 @@
1
+ node_modules
2
+ .DS_Store
package/.travis.yml ADDED
@@ -0,0 +1,5 @@
1
+ language: node_js
2
+ node_js:
3
+ - "0.6"
4
+ - "0.8"
5
+ - "0.10"
package/LICENSE.md ADDED
@@ -0,0 +1,2 @@
1
+ Copyright (c) 2010-2012 Robert Kieffer
2
+ MIT License - http://opensource.org/licenses/mit-license.php
package/README.md ADDED
@@ -0,0 +1,205 @@
1
+ # uuid [![Build Status](https://secure.travis-ci.org/defunctzombie/node-uuid.png?branch=master)](http://travis-ci.org/defunctzombie/node-uuid) #
2
+
3
+ [![browser support](https://ci.testling.com/defunctzombie/node-uuid.png)](https://ci.testling.com/defunctzombie/node-uuid)
4
+
5
+ Simple, fast generation of [RFC4122](http://www.ietf.org/rfc/rfc4122.txt) UUIDS.
6
+
7
+ Features:
8
+
9
+ * Generate RFC4122 version 1 or version 4 UUIDs
10
+ * Runs in node.js and all browsers.
11
+ * Cryptographically strong random # generation on supporting platforms
12
+ * 1185 bytes minified and gzip'ed (Want something smaller? Check this [crazy shit](https://gist.github.com/982883) out! )
13
+ * [Annotated source code](http://broofa.github.com/node-uuid/docs/uuid.html)
14
+
15
+ ## Getting Started
16
+
17
+ Install it in your browser:
18
+
19
+ ```html
20
+ <script src="uuid.js"></script>
21
+ ```
22
+
23
+ Or in node.js:
24
+
25
+ ```
26
+ npm install uuid
27
+ ```
28
+
29
+ ```javascript
30
+ var uuid = require('uuid');
31
+
32
+ // Generate a v1 (time-based) id
33
+ uuid.v1(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a'
34
+
35
+ // Generate a v4 (random) id
36
+ uuid.v4(); // -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1'
37
+ ```
38
+
39
+ ## API
40
+
41
+ ### uuid.v1([`options` [, `buffer` [, `offset`]]])
42
+
43
+ Generate and return a RFC4122 v1 (timestamp-based) UUID.
44
+
45
+ * `options` - (Object) Optional uuid state to apply. Properties may include:
46
+
47
+ * `node` - (Array) Node id as Array of 6 bytes (per 4.1.6). Default: Randomly generated ID. See note 1.
48
+ * `clockseq` - (Number between 0 - 0x3fff) RFC clock sequence. Default: An internally maintained clockseq is used.
49
+ * `msecs` - (Number | Date) Time in milliseconds since unix Epoch. Default: The current time is used.
50
+ * `nsecs` - (Number between 0-9999) additional time, in 100-nanosecond units. Ignored if `msecs` is unspecified. Default: internal uuid counter is used, as per 4.2.1.2.
51
+
52
+ * `buffer` - (Array | Buffer) Array or buffer where UUID bytes are to be written.
53
+ * `offset` - (Number) Starting index in `buffer` at which to begin writing.
54
+
55
+ Returns `buffer`, if specified, otherwise the string form of the UUID
56
+
57
+ Notes:
58
+
59
+ 1. The randomly generated node id is only guaranteed to stay constant for the lifetime of the current JS runtime. (Future versions of this module may use persistent storage mechanisms to extend this guarantee.)
60
+
61
+ Example: Generate string UUID with fully-specified options
62
+
63
+ ```javascript
64
+ uuid.v1({
65
+ node: [0x01, 0x23, 0x45, 0x67, 0x89, 0xab],
66
+ clockseq: 0x1234,
67
+ msecs: new Date('2011-11-01').getTime(),
68
+ nsecs: 5678
69
+ }); // -> "710b962e-041c-11e1-9234-0123456789ab"
70
+ ```
71
+
72
+ Example: In-place generation of two binary IDs
73
+
74
+ ```javascript
75
+ // Generate two ids in an array
76
+ var arr = new Array(32); // -> []
77
+ uuid.v1(null, arr, 0); // -> [02 a2 ce 90 14 32 11 e1 85 58 0b 48 8e 4f c1 15]
78
+ 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]
79
+
80
+ // Optionally use uuid.unparse() to get stringify the ids
81
+ uuid.unparse(buffer); // -> '02a2ce90-1432-11e1-8558-0b488e4fc115'
82
+ uuid.unparse(buffer, 16) // -> '02a31cb0-1432-11e1-8558-0b488e4fc115'
83
+ ```
84
+
85
+ ### uuid.v4([`options` [, `buffer` [, `offset`]]])
86
+
87
+ Generate and return a RFC4122 v4 UUID.
88
+
89
+ * `options` - (Object) Optional uuid state to apply. Properties may include:
90
+
91
+ * `random` - (Number[16]) Array of 16 numbers (0-255) to use in place of randomly generated values
92
+ * `rng` - (Function) Random # generator to use. Set to one of the built-in generators - `uuid.mathRNG` (all platforms), `uuid.nodeRNG` (node.js only), `uuid.whatwgRNG` (WebKit only) - or a custom function that returns an array[16] of byte values.
93
+
94
+ * `buffer` - (Array | Buffer) Array or buffer where UUID bytes are to be written.
95
+ * `offset` - (Number) Starting index in `buffer` at which to begin writing.
96
+
97
+ Returns `buffer`, if specified, otherwise the string form of the UUID
98
+
99
+ Example: Generate string UUID with fully-specified options
100
+
101
+ ```javascript
102
+ uuid.v4({
103
+ random: [
104
+ 0x10, 0x91, 0x56, 0xbe, 0xc4, 0xfb, 0xc1, 0xea,
105
+ 0x71, 0xb4, 0xef, 0xe1, 0x67, 0x1c, 0x58, 0x36
106
+ ]
107
+ });
108
+ // -> "109156be-c4fb-41ea-b1b4-efe1671c5836"
109
+ ```
110
+
111
+ Example: Generate two IDs in a single buffer
112
+
113
+ ```javascript
114
+ var buffer = new Array(32); // (or 'new Buffer' in node.js)
115
+ uuid.v4(null, buffer, 0);
116
+ uuid.v4(null, buffer, 16);
117
+ ```
118
+
119
+ ### uuid.parse(id[, buffer[, offset]])
120
+ ### uuid.unparse(buffer[, offset])
121
+
122
+ Parse and unparse UUIDs
123
+
124
+ * `id` - (String) UUID(-like) string
125
+ * `buffer` - (Array | Buffer) Array or buffer where UUID bytes are to be written. Default: A new Array or Buffer is used
126
+ * `offset` - (Number) Starting index in `buffer` at which to begin writing. Default: 0
127
+
128
+ Example parsing and unparsing a UUID string
129
+
130
+ ```javascript
131
+ var bytes = uuid.parse('797ff043-11eb-11e1-80d6-510998755d10'); // -> <Buffer 79 7f f0 43 11 eb 11 e1 80 d6 51 09 98 75 5d 10>
132
+ var string = uuid.unparse(bytes); // -> '797ff043-11eb-11e1-80d6-510998755d10'
133
+ ```
134
+
135
+ ### uuid.noConflict()
136
+
137
+ (Browsers only) Set `uuid` property back to it's previous value.
138
+
139
+ Returns the uuid object.
140
+
141
+ Example:
142
+
143
+ ```javascript
144
+ var myUuid = uuid.noConflict();
145
+ myUuid.v1(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a'
146
+ ```
147
+
148
+ ## Deprecated APIs
149
+
150
+ Support for the following v1.2 APIs is available in v1.3, but is deprecated and will be removed in the next major version.
151
+
152
+ ### uuid([format [, buffer [, offset]]])
153
+
154
+ 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).
155
+
156
+ ### uuid.BufferClass
157
+
158
+ 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.
159
+
160
+ ## Testing
161
+
162
+ In node.js
163
+
164
+ ```
165
+ > cd test
166
+ > node test.js
167
+ ```
168
+
169
+ In Browser
170
+
171
+ ```
172
+ open test/test.html
173
+ ```
174
+
175
+ ### Benchmarking
176
+
177
+ Requires node.js
178
+
179
+ ```
180
+ cd benchmark/
181
+ npm install
182
+ node benchmark.js
183
+ ```
184
+
185
+ For a more complete discussion of uuid performance, please see the `benchmark/README.md` file, and the [benchmark wiki](https://github.com/broofa/uuid/wiki/Benchmark)
186
+
187
+ For browser performance [checkout the JSPerf tests](http://jsperf.com/node-uuid-performance).
188
+
189
+ ## Release notes
190
+
191
+ ### 1.4.0
192
+
193
+ * Improved module context detection
194
+ * Removed public RNG functions
195
+
196
+ ### 1.3.2
197
+
198
+ * Improve tests and handling of v1() options (Issue #24)
199
+ * Expose RNG option to allow for perf testing with different generators
200
+
201
+ ### 1.3.0
202
+
203
+ * Support for version 1 ids, thanks to [@ctavan](https://github.com/ctavan)!
204
+ * Support for node.js crypto API
205
+ * De-emphasizing performance in favor of a) cryptographic quality PRNGs where available and b) more manageable code
@@ -0,0 +1,53 @@
1
+ # node-uuid Benchmarks
2
+
3
+ ### Results
4
+
5
+ To see the results of our benchmarks visit https://github.com/broofa/node-uuid/wiki/Benchmark
6
+
7
+ ### Run them yourself
8
+
9
+ 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`.
10
+
11
+ To prepare and run the benchmark issue;
12
+
13
+ ```
14
+ npm install uuid uuid-js
15
+ node benchmark/benchmark.js
16
+ ```
17
+
18
+ You'll see an output like this one:
19
+
20
+ ```
21
+ # v4
22
+ nodeuuid.v4(): 854700 uuids/second
23
+ nodeuuid.v4('binary'): 788643 uuids/second
24
+ nodeuuid.v4('binary', buffer): 1336898 uuids/second
25
+ uuid(): 479386 uuids/second
26
+ uuid('binary'): 582072 uuids/second
27
+ uuidjs.create(4): 312304 uuids/second
28
+
29
+ # v1
30
+ nodeuuid.v1(): 938086 uuids/second
31
+ nodeuuid.v1('binary'): 683060 uuids/second
32
+ nodeuuid.v1('binary', buffer): 1644736 uuids/second
33
+ uuidjs.create(1): 190621 uuids/second
34
+ ```
35
+
36
+ * The `uuid()` entries are for Nikhil Marathe's [uuid module](https://bitbucket.org/nikhilm/uuidjs) which is a wrapper around the native libuuid library.
37
+ * 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.
38
+
39
+ If you want to get more reliable results you can run the benchmark multiple times and write the output into a log file:
40
+
41
+ ```
42
+ for i in {0..9}; do node benchmark/benchmark.js >> benchmark/bench_0.4.12.log; done;
43
+ ```
44
+
45
+ If you're interested in how performance varies between different node versions, you can issue the above command multiple times.
46
+
47
+ 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:
48
+
49
+ ```
50
+ (cd benchmark/ && ./bench.sh)
51
+ ```
52
+
53
+ 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.
@@ -0,0 +1,174 @@
1
+ #!/opt/local/bin/gnuplot -persist
2
+ #
3
+ #
4
+ # G N U P L O T
5
+ # Version 4.4 patchlevel 3
6
+ # last modified March 2011
7
+ # System: Darwin 10.8.0
8
+ #
9
+ # Copyright (C) 1986-1993, 1998, 2004, 2007-2010
10
+ # Thomas Williams, Colin Kelley and many others
11
+ #
12
+ # gnuplot home: http://www.gnuplot.info
13
+ # faq, bugs, etc: type "help seeking-assistance"
14
+ # immediate help: type "help"
15
+ # plot window: hit 'h'
16
+ set terminal postscript eps noenhanced defaultplex \
17
+ leveldefault color colortext \
18
+ solid linewidth 1.2 butt noclip \
19
+ palfuncparam 2000,0.003 \
20
+ "Helvetica" 14
21
+ set output 'bench.eps'
22
+ unset clip points
23
+ set clip one
24
+ unset clip two
25
+ set bar 1.000000 front
26
+ set border 31 front linetype -1 linewidth 1.000
27
+ set xdata
28
+ set ydata
29
+ set zdata
30
+ set x2data
31
+ set y2data
32
+ set timefmt x "%d/%m/%y,%H:%M"
33
+ set timefmt y "%d/%m/%y,%H:%M"
34
+ set timefmt z "%d/%m/%y,%H:%M"
35
+ set timefmt x2 "%d/%m/%y,%H:%M"
36
+ set timefmt y2 "%d/%m/%y,%H:%M"
37
+ set timefmt cb "%d/%m/%y,%H:%M"
38
+ set boxwidth
39
+ set style fill empty border
40
+ set style rectangle back fc lt -3 fillstyle solid 1.00 border lt -1
41
+ set style circle radius graph 0.02, first 0, 0
42
+ set dummy x,y
43
+ set format x "% g"
44
+ set format y "% g"
45
+ set format x2 "% g"
46
+ set format y2 "% g"
47
+ set format z "% g"
48
+ set format cb "% g"
49
+ set angles radians
50
+ unset grid
51
+ set key title ""
52
+ set key outside left top horizontal Right noreverse enhanced autotitles columnhead nobox
53
+ set key noinvert samplen 4 spacing 1 width 0 height 0
54
+ set key maxcolumns 2 maxrows 0
55
+ unset label
56
+ unset arrow
57
+ set style increment default
58
+ unset style line
59
+ set style line 1 linetype 1 linewidth 2.000 pointtype 1 pointsize default pointinterval 0
60
+ unset style arrow
61
+ set style histogram clustered gap 2 title offset character 0, 0, 0
62
+ unset logscale
63
+ set offsets graph 0.05, 0.15, 0, 0
64
+ set pointsize 1.5
65
+ set pointintervalbox 1
66
+ set encoding default
67
+ unset polar
68
+ unset parametric
69
+ unset decimalsign
70
+ set view 60, 30, 1, 1
71
+ set samples 100, 100
72
+ set isosamples 10, 10
73
+ set surface
74
+ unset contour
75
+ set clabel '%8.3g'
76
+ set mapping cartesian
77
+ set datafile separator whitespace
78
+ unset hidden3d
79
+ set cntrparam order 4
80
+ set cntrparam linear
81
+ set cntrparam levels auto 5
82
+ set cntrparam points 5
83
+ set size ratio 0 1,1
84
+ set origin 0,0
85
+ set style data points
86
+ set style function lines
87
+ set xzeroaxis linetype -2 linewidth 1.000
88
+ set yzeroaxis linetype -2 linewidth 1.000
89
+ set zzeroaxis linetype -2 linewidth 1.000
90
+ set x2zeroaxis linetype -2 linewidth 1.000
91
+ set y2zeroaxis linetype -2 linewidth 1.000
92
+ set ticslevel 0.5
93
+ set mxtics default
94
+ set mytics default
95
+ set mztics default
96
+ set mx2tics default
97
+ set my2tics default
98
+ set mcbtics default
99
+ set xtics border in scale 1,0.5 mirror norotate offset character 0, 0, 0
100
+ set xtics norangelimit
101
+ set xtics ()
102
+ set ytics border in scale 1,0.5 mirror norotate offset character 0, 0, 0
103
+ set ytics autofreq norangelimit
104
+ set ztics border in scale 1,0.5 nomirror norotate offset character 0, 0, 0
105
+ set ztics autofreq norangelimit
106
+ set nox2tics
107
+ set noy2tics
108
+ set cbtics border in scale 1,0.5 mirror norotate offset character 0, 0, 0
109
+ set cbtics autofreq norangelimit
110
+ set title ""
111
+ set title offset character 0, 0, 0 font "" norotate
112
+ set timestamp bottom
113
+ set timestamp ""
114
+ set timestamp offset character 0, 0, 0 font "" norotate
115
+ set rrange [ * : * ] noreverse nowriteback # (currently [8.98847e+307:-8.98847e+307] )
116
+ set autoscale rfixmin
117
+ set autoscale rfixmax
118
+ set trange [ * : * ] noreverse nowriteback # (currently [-5.00000:5.00000] )
119
+ set autoscale tfixmin
120
+ set autoscale tfixmax
121
+ set urange [ * : * ] noreverse nowriteback # (currently [-10.0000:10.0000] )
122
+ set autoscale ufixmin
123
+ set autoscale ufixmax
124
+ set vrange [ * : * ] noreverse nowriteback # (currently [-10.0000:10.0000] )
125
+ set autoscale vfixmin
126
+ set autoscale vfixmax
127
+ set xlabel ""
128
+ set xlabel offset character 0, 0, 0 font "" textcolor lt -1 norotate
129
+ set x2label ""
130
+ set x2label offset character 0, 0, 0 font "" textcolor lt -1 norotate
131
+ set xrange [ * : * ] noreverse nowriteback # (currently [-0.150000:3.15000] )
132
+ set autoscale xfixmin
133
+ set autoscale xfixmax
134
+ set x2range [ * : * ] noreverse nowriteback # (currently [0.00000:3.00000] )
135
+ set autoscale x2fixmin
136
+ set autoscale x2fixmax
137
+ set ylabel ""
138
+ set ylabel offset character 0, 0, 0 font "" textcolor lt -1 rotate by -270
139
+ set y2label ""
140
+ set y2label offset character 0, 0, 0 font "" textcolor lt -1 rotate by -270
141
+ set yrange [ 0.00000 : 1.90000e+06 ] noreverse nowriteback # (currently [:] )
142
+ set autoscale yfixmin
143
+ set autoscale yfixmax
144
+ set y2range [ * : * ] noreverse nowriteback # (currently [0.00000:1.90000e+06] )
145
+ set autoscale y2fixmin
146
+ set autoscale y2fixmax
147
+ set zlabel ""
148
+ set zlabel offset character 0, 0, 0 font "" textcolor lt -1 norotate
149
+ set zrange [ * : * ] noreverse nowriteback # (currently [-10.0000:10.0000] )
150
+ set autoscale zfixmin
151
+ set autoscale zfixmax
152
+ set cblabel ""
153
+ set cblabel offset character 0, 0, 0 font "" textcolor lt -1 rotate by -270
154
+ set cbrange [ * : * ] noreverse nowriteback # (currently [8.98847e+307:-8.98847e+307] )
155
+ set autoscale cbfixmin
156
+ set autoscale cbfixmax
157
+ set zero 1e-08
158
+ set lmargin -1
159
+ set bmargin -1
160
+ set rmargin -1
161
+ set tmargin -1
162
+ set pm3d explicit at s
163
+ set pm3d scansautomatic
164
+ set pm3d interpolate 1,1 flush begin noftriangles nohidden3d corners2color mean
165
+ set palette positive nops_allcF maxcolors 0 gamma 1.5 color model RGB
166
+ set palette rgbformulae 7, 5, 15
167
+ set colorbox default
168
+ set colorbox vertical origin screen 0.9, 0.2, 0 size screen 0.05, 0.6, 0 front bdefault
169
+ set loadpath
170
+ set fontpath
171
+ set fit noerrorvariables
172
+ GNUTERM = "aqua"
173
+ 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
174
+ # EOF
@@ -0,0 +1,34 @@
1
+ #!/bin/bash
2
+
3
+ # for a given node version run:
4
+ # for i in {0..9}; do node benchmark.js >> bench_0.6.2.log; done;
5
+
6
+ PATTERNS=('nodeuuid.v1()' "nodeuuid.v1('binary'," 'nodeuuid.v4()' "nodeuuid.v4('binary'," "uuid()" "uuid('binary')" 'uuidjs.create(1)' 'uuidjs.create(4)' '140byte')
7
+ 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)
8
+ INDICES=(2 3 2 3 2 2 2 2 2)
9
+ VERSIONS=$( ls bench_*.log | sed -e 's/^bench_\([0-9\.]*\)\.log/\1/' | tr "\\n" " " )
10
+ TMPJOIN="tmp_join"
11
+ OUTPUT="bench_results.txt"
12
+
13
+ for I in ${!FILES[*]}; do
14
+ F=${FILES[$I]}
15
+ P=${PATTERNS[$I]}
16
+ INDEX=${INDICES[$I]}
17
+ echo "version $F" > $F
18
+ for V in $VERSIONS; do
19
+ (VAL=$( grep "$P" bench_$V.log | LC_ALL=en_US awk '{ sum += $'$INDEX' } END { print sum/NR }' ); echo $V $VAL) >> $F
20
+ done
21
+ if [ $I == 0 ]; then
22
+ cat $F > $TMPJOIN
23
+ else
24
+ join $TMPJOIN $F > $OUTPUT
25
+ cp $OUTPUT $TMPJOIN
26
+ fi
27
+ rm $F
28
+ done
29
+
30
+ rm $TMPJOIN
31
+
32
+ gnuplot bench.gnu
33
+ convert -density 200 -resize 800x560 -flatten bench.eps bench.png
34
+ rm bench.eps
@@ -0,0 +1,34 @@
1
+ /*
2
+ Test performance of native C UUID generation
3
+
4
+ To Compile: cc -luuid benchmark-native.c -o benchmark-native
5
+ */
6
+
7
+ #include <stdio.h>
8
+ #include <unistd.h>
9
+ #include <sys/time.h>
10
+ #include <uuid/uuid.h>
11
+
12
+ int main() {
13
+ uuid_t myid;
14
+ char buf[36+1];
15
+ int i;
16
+ struct timeval t;
17
+ double start, finish;
18
+
19
+ gettimeofday(&t, NULL);
20
+ start = t.tv_sec + t.tv_usec/1e6;
21
+
22
+ int n = 2e5;
23
+ for (i = 0; i < n; i++) {
24
+ uuid_generate(myid);
25
+ uuid_unparse(myid, buf);
26
+ }
27
+
28
+ gettimeofday(&t, NULL);
29
+ finish = t.tv_sec + t.tv_usec/1e6;
30
+ double dur = finish - start;
31
+
32
+ printf("%d uuids/sec", (int)(n/dur));
33
+ return 0;
34
+ }
@@ -0,0 +1,84 @@
1
+ try {
2
+ var nodeuuid = require('../uuid');
3
+ } catch (e) {
4
+ console.error('node-uuid require failed - skipping tests');
5
+ }
6
+
7
+ try {
8
+ var uuid = require('uuid');
9
+ } catch (e) {
10
+ console.error('uuid require failed - skipping tests');
11
+ }
12
+
13
+ try {
14
+ var uuidjs = require('uuid-js');
15
+ } catch (e) {
16
+ console.error('uuid-js require failed - skipping tests');
17
+ }
18
+
19
+ var N = 5e5;
20
+
21
+ function rate(msg, t) {
22
+ console.log(msg + ': ' +
23
+ (N / (Date.now() - t) * 1e3 | 0) +
24
+ ' uuids/second');
25
+ }
26
+
27
+ console.log('# v4');
28
+
29
+ // node-uuid - string form
30
+ if (nodeuuid) {
31
+ for (var i = 0, t = Date.now(); i < N; i++) nodeuuid.v4();
32
+ rate('nodeuuid.v4() - using node.js crypto RNG', t);
33
+
34
+ for (var i = 0, t = Date.now(); i < N; i++) nodeuuid.v4({rng: nodeuuid.mathRNG});
35
+ rate('nodeuuid.v4() - using Math.random() RNG', t);
36
+
37
+ for (var i = 0, t = Date.now(); i < N; i++) nodeuuid.v4('binary');
38
+ rate('nodeuuid.v4(\'binary\')', t);
39
+
40
+ var buffer = new nodeuuid.BufferClass(16);
41
+ for (var i = 0, t = Date.now(); i < N; i++) nodeuuid.v4('binary', buffer);
42
+ rate('nodeuuid.v4(\'binary\', buffer)', t);
43
+ }
44
+
45
+ // libuuid - string form
46
+ if (uuid) {
47
+ for (var i = 0, t = Date.now(); i < N; i++) uuid();
48
+ rate('uuid()', t);
49
+
50
+ for (var i = 0, t = Date.now(); i < N; i++) uuid('binary');
51
+ rate('uuid(\'binary\')', t);
52
+ }
53
+
54
+ // uuid-js - string form
55
+ if (uuidjs) {
56
+ for (var i = 0, t = Date.now(); i < N; i++) uuidjs.create(4);
57
+ rate('uuidjs.create(4)', t);
58
+ }
59
+
60
+ // 140byte.es
61
+ 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)});
62
+ rate('140byte.es_v4', t);
63
+
64
+ console.log('');
65
+ console.log('# v1');
66
+
67
+ // node-uuid - v1 string form
68
+ if (nodeuuid) {
69
+ for (var i = 0, t = Date.now(); i < N; i++) nodeuuid.v1();
70
+ rate('nodeuuid.v1()', t);
71
+
72
+ for (var i = 0, t = Date.now(); i < N; i++) nodeuuid.v1('binary');
73
+ rate('nodeuuid.v1(\'binary\')', t);
74
+
75
+ var buffer = new nodeuuid.BufferClass(16);
76
+ for (var i = 0, t = Date.now(); i < N; i++) nodeuuid.v1('binary', buffer);
77
+ rate('nodeuuid.v1(\'binary\', buffer)', t);
78
+ }
79
+
80
+ // uuid-js - v1 string form
81
+ if (uuidjs) {
82
+ for (var i = 0, t = Date.now(); i < N; i++) uuidjs.create(1);
83
+ rate('uuidjs.create(1)', t);
84
+ }
@@ -0,0 +1,9 @@
1
+ {
2
+ "name": "benchmark-uuid",
3
+ "private": true,
4
+ "description": "Benchmarks for node-uuid",
5
+ "dependencies": {
6
+ "uuid": "^1.4.1",
7
+ "uuid-js": "^0.7.4"
8
+ }
9
+ }
@@ -0,0 +1 @@
1
+ module.exports = Array;
package/buffer.js ADDED
@@ -0,0 +1 @@
1
+ module.exports = Buffer;
@@ -0,0 +1,62 @@
1
+ var assert = require('assert'),
2
+ nodeuuid = require('../'),
3
+ uuidjs = require('uuid-js'),
4
+ util = require('util'),
5
+ exec = require('child_process').exec,
6
+ os = require('os');
7
+
8
+ // On Mac Os X / macports there's only the ossp-uuid package that provides uuid
9
+ // On Linux there's uuid-runtime which provides uuidgen
10
+ var uuidCmd = os.type() === 'Darwin' ? 'uuid -1' : 'uuidgen -t';
11
+
12
+ function compare(ids) {
13
+ console.log(ids);
14
+ for (var i = 0; i < ids.length; i++) {
15
+ var id = ids[i].split('-');
16
+ id = [id[2], id[1], id[0]].join('');
17
+ ids[i] = id;
18
+ }
19
+ var sorted = ([].concat(ids)).sort();
20
+
21
+ if (sorted.toString() !== ids.toString()) {
22
+ console.log('Warning: sorted !== ids');
23
+ } else {
24
+ console.log('everything in order!');
25
+ }
26
+ }
27
+
28
+ // Test time order of v1 uuids
29
+ var ids = [];
30
+ while (ids.length < 10e3) ids.push(nodeuuid.v1());
31
+
32
+ var max = 10;
33
+ console.log('node-uuid:');
34
+ ids = [];
35
+ for (var i = 0; i < max; i++) ids.push(nodeuuid.v1());
36
+ compare(ids);
37
+
38
+ console.log('');
39
+ console.log('uuidjs:');
40
+ ids = [];
41
+ for (var i = 0; i < max; i++) ids.push(uuidjs.create(1).toString());
42
+ compare(ids);
43
+
44
+ console.log('');
45
+ console.log('libuuid:');
46
+ ids = [];
47
+ var count = 0;
48
+ var last = function() {
49
+ compare(ids);
50
+ }
51
+ var cb = function(err, stdout, stderr) {
52
+ ids.push(stdout.substring(0, stdout.length-1));
53
+ count++;
54
+ if (count < max) {
55
+ return next();
56
+ }
57
+ last();
58
+ };
59
+ var next = function() {
60
+ exec(uuidCmd, cb);
61
+ };
62
+ next();
package/misc/perf.js ADDED
@@ -0,0 +1,102 @@
1
+ var assert = require('assert');
2
+
3
+ var uuid = require('../');
4
+
5
+ var log = console.log;
6
+
7
+ var generators = {
8
+ v1: uuid.v1,
9
+ v4: uuid.v4
10
+ };
11
+
12
+ var UUID_FORMAT = {
13
+ v1: /[0-9a-f]{8}-[0-9a-f]{4}-1[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/i,
14
+ v4: /[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/i
15
+ };
16
+
17
+ var N = 1e4;
18
+
19
+ // Get %'age an actual value differs from the ideal value
20
+ function divergence(actual, ideal) {
21
+ return Math.round(100*100*(actual - ideal)/ideal)/100;
22
+ }
23
+
24
+ function rate(msg, t) {
25
+ log(msg + ': ' + (N / (Date.now() - t) * 1e3 | 0) + ' uuids\/second');
26
+ }
27
+
28
+ for (var version in generators) {
29
+ var counts = {}, max = 0;
30
+ var generator = generators[version];
31
+ var format = UUID_FORMAT[version];
32
+
33
+ log('\nSanity check ' + N + ' ' + version + ' uuids');
34
+ for (var i = 0, ok = 0; i < N; i++) {
35
+ id = generator();
36
+ if (!format.test(id)) {
37
+ throw Error(id + ' is not a valid UUID string');
38
+ }
39
+
40
+ if (id != uuid.unparse(uuid.parse(id))) {
41
+ assert(fail, id + ' is not a valid id');
42
+ }
43
+
44
+ // Count digits for our randomness check
45
+ if (version == 'v4') {
46
+ var digits = id.replace(/-/g, '').split('');
47
+ for (var j = digits.length-1; j >= 0; j--) {
48
+ var c = digits[j];
49
+ max = Math.max(max, counts[c] = (counts[c] || 0) + 1);
50
+ }
51
+ }
52
+ }
53
+
54
+ // Check randomness for v4 UUIDs
55
+ if (version == 'v4') {
56
+ // Limit that we get worried about randomness. (Purely empirical choice, this!)
57
+ var limit = 2*100*Math.sqrt(1/N);
58
+
59
+ log('\nChecking v4 randomness. Distribution of Hex Digits (% deviation from ideal)');
60
+
61
+ for (var i = 0; i < 16; i++) {
62
+ var c = i.toString(16);
63
+ var bar = '', n = counts[c], p = Math.round(n/max*100|0);
64
+
65
+ // 1-3,5-8, and D-F: 1:16 odds over 30 digits
66
+ var ideal = N*30/16;
67
+ if (i == 4) {
68
+ // 4: 1:1 odds on 1 digit, plus 1:16 odds on 30 digits
69
+ ideal = N*(1 + 30/16);
70
+ } else if (i >= 8 && i <= 11) {
71
+ // 8-B: 1:4 odds on 1 digit, plus 1:16 odds on 30 digits
72
+ ideal = N*(1/4 + 30/16);
73
+ } else {
74
+ // Otherwise: 1:16 odds on 30 digits
75
+ ideal = N*30/16;
76
+ }
77
+ var d = divergence(n, ideal);
78
+
79
+ // Draw bar using UTF squares (just for grins)
80
+ var s = n/max*50 | 0;
81
+ while (s--) bar += '=';
82
+
83
+ assert(Math.abs(d) < limit, c + ' |' + bar + '| ' + counts[c] + ' (' + d + '% < ' + limit + '%)');
84
+ }
85
+ }
86
+ }
87
+
88
+ // Perf tests
89
+ for (var version in generators) {
90
+ log('\nPerformance testing ' + version + ' UUIDs');
91
+ var generator = generators[version];
92
+ var buf = new uuid.BufferClass(16);
93
+
94
+ for (var i = 0, t = Date.now(); i < N; i++) generator();
95
+ rate('uuid.' + version + '()', t);
96
+
97
+ for (var i = 0, t = Date.now(); i < N; i++) generator('binary');
98
+ rate('uuid.' + version + '(\'binary\')', t);
99
+
100
+ for (var i = 0, t = Date.now(); i < N; i++) generator('binary', buf);
101
+ rate('uuid.' + version + '(\'binary\', buffer)', t);
102
+ }
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "uuid",
3
+ "version": "1.4.2",
4
+ "description": "Rigorous implementation of RFC4122 (v1 and v4) UUIDs.",
5
+ "keywords": [
6
+ "uuid",
7
+ "guid",
8
+ "rfc4122"
9
+ ],
10
+ "author": "Robert Kieffer <robert@broofa.com>",
11
+ "contributors": [
12
+ {
13
+ "name": "Christoph Tavan <dev@tavan.de>",
14
+ "github": "https://github.com/ctavan"
15
+ },
16
+ {
17
+ "name": "Vincent Voyer <vincent@zeroload.net>",
18
+ "github": "https://github.com/vvo"
19
+ }
20
+ ],
21
+ "main": "./uuid.js",
22
+ "devDependencies": {
23
+ "mocha": "1.8.0"
24
+ },
25
+ "scripts": {
26
+ "test": "mocha test/test.js"
27
+ },
28
+ "browser": {
29
+ "./rng.js": "./rng-browser.js",
30
+ "./buffer.js": "./buffer-browser.js"
31
+ },
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "https://github.com/shtylman/node-uuid.git"
35
+ },
36
+ "testling": {
37
+ "browsers": [
38
+ "ie6..latest",
39
+ "firefox/3.6..latest",
40
+ "chrome/22..latest",
41
+ "safari/5.1..latest"
42
+ ],
43
+ "harness": "mocha-tdd",
44
+ "files": "test/*.js"
45
+ }
46
+ }
package/rng-browser.js ADDED
@@ -0,0 +1,31 @@
1
+
2
+ var rng;
3
+
4
+ if (global.crypto && crypto.getRandomValues) {
5
+ // WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto
6
+ // Moderately fast, high quality
7
+ var _rnds8 = new Uint8Array(16);
8
+ rng = function whatwgRNG() {
9
+ crypto.getRandomValues(_rnds8);
10
+ return _rnds8;
11
+ };
12
+ }
13
+
14
+ if (!rng) {
15
+ // Math.random()-based (RNG)
16
+ //
17
+ // If all else fails, use Math.random(). It's fast, but is of unspecified
18
+ // quality.
19
+ var _rnds = new Array(16);
20
+ rng = function() {
21
+ for (var i = 0, r; i < 16; i++) {
22
+ if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
23
+ _rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
24
+ }
25
+
26
+ return _rnds;
27
+ };
28
+ }
29
+
30
+ module.exports = rng;
31
+
package/rng.js ADDED
@@ -0,0 +1,4 @@
1
+ var rb = require('crypto').randomBytes;
2
+ module.exports = function() {
3
+ return rb(16);
4
+ };
@@ -0,0 +1 @@
1
+ --ui qunit
package/test/test.js ADDED
@@ -0,0 +1,105 @@
1
+ var assert = require('assert');
2
+
3
+ var uuid = require('../');
4
+
5
+ // Verify ordering of v1 ids created with explicit times
6
+ var TIME = 1321644961388; // 2011-11-18 11:36:01.388-08:00
7
+
8
+ function compare(name, ids) {
9
+ test(name, function() {
10
+ // avoid .map for older browsers
11
+ for (var i=0 ; i<ids.length ; ++i) {
12
+ ids[i] = ids[i].split('-').reverse().join('-');
13
+ }
14
+ ids = ids.sort();
15
+ var sorted = ([].concat(ids)).sort();
16
+
17
+ assert(sorted.toString() == ids.toString(), name + ' have expected order');
18
+ });
19
+ }
20
+
21
+ // Verify ordering of v1 ids created using default behavior
22
+ compare('uuids with current time', [
23
+ uuid.v1(),
24
+ uuid.v1(),
25
+ uuid.v1(),
26
+ uuid.v1(),
27
+ uuid.v1()
28
+ ]);
29
+
30
+ // Verify ordering of v1 ids created with explicit times
31
+ compare('uuids with time option', [
32
+ uuid.v1({msecs: TIME - 10*3600*1000}),
33
+ uuid.v1({msecs: TIME - 1}),
34
+ uuid.v1({msecs: TIME}),
35
+ uuid.v1({msecs: TIME + 1}),
36
+ uuid.v1({msecs: TIME + 28*24*3600*1000})
37
+ ]);
38
+
39
+ test('msec', function() {
40
+ assert(
41
+ uuid.v1({msecs: TIME}) != uuid.v1({msecs: TIME}),
42
+ 'IDs created at same msec are different'
43
+ );
44
+ });
45
+
46
+ test('exception thrown when > 10k ids created in 1ms', function() {
47
+ // Verify throw if too many ids created
48
+ var thrown = false;
49
+ try {
50
+ uuid.v1({msecs: TIME, nsecs: 10000});
51
+ } catch (e) {
52
+ thrown = true;
53
+ }
54
+ assert(thrown, 'Exception thrown when > 10K ids created in 1 ms');
55
+ });
56
+
57
+ test('clock regression by msec', function() {
58
+ // Verify clock regression bumps clockseq
59
+ var uidt = uuid.v1({msecs: TIME});
60
+ var uidtb = uuid.v1({msecs: TIME - 1});
61
+ assert(
62
+ parseInt(uidtb.split('-')[3], 16) - parseInt(uidt.split('-')[3], 16) === 1,
63
+ 'Clock regression by msec increments the clockseq'
64
+ );
65
+ });
66
+
67
+ test('clock regression by nsec', function() {
68
+ // Verify clock regression bumps clockseq
69
+ var uidtn = uuid.v1({msecs: TIME, nsecs: 10});
70
+ var uidtnb = uuid.v1({msecs: TIME, nsecs: 9});
71
+ assert(
72
+ parseInt(uidtnb.split('-')[3], 16) - parseInt(uidtn.split('-')[3], 16) === 1,
73
+ 'Clock regression by nsec increments the clockseq'
74
+ );
75
+ });
76
+
77
+ test('explicit options product expected id', function() {
78
+ // Verify explicit options produce expected id
79
+ var id = uuid.v1({
80
+ msecs: 1321651533573,
81
+ nsecs: 5432,
82
+ clockseq: 0x385c,
83
+ node: [ 0x61, 0xcd, 0x3c, 0xbb, 0x32, 0x10 ]
84
+ });
85
+ assert(id == 'd9428888-122b-11e1-b85c-61cd3cbb3210', 'Explicit options produce expected id');
86
+ });
87
+
88
+ test('ids spanning 1ms boundary are 100ns apart', function() {
89
+ // Verify adjacent ids across a msec boundary are 1 time unit apart
90
+ var u0 = uuid.v1({msecs: TIME, nsecs: 9999});
91
+ var u1 = uuid.v1({msecs: TIME + 1, nsecs: 0});
92
+
93
+ var before = u0.split('-')[0], after = u1.split('-')[0];
94
+ var dt = parseInt(after, 16) - parseInt(before, 16);
95
+ assert(dt === 1, 'Ids spanning 1ms boundary are 100ns apart');
96
+ });
97
+
98
+ test('parse/unparse', function() {
99
+ var id = '00112233445566778899aabbccddeeff';
100
+ assert(uuid.unparse(uuid.parse(id.substr(0,10))) ==
101
+ '00112233-4400-0000-0000-000000000000', 'Short parse');
102
+ assert(uuid.unparse(uuid.parse('(this is the uuid -> ' + id + id)) ==
103
+ '00112233-4455-6677-8899-aabbccddeeff', 'Dirty parse');
104
+ });
105
+
package/uuid.js ADDED
@@ -0,0 +1,189 @@
1
+ // uuid.js
2
+ //
3
+ // Copyright (c) 2010-2012 Robert Kieffer
4
+ // MIT License - http://opensource.org/licenses/mit-license.php
5
+
6
+ // Unique ID creation requires a high quality random # generator. We feature
7
+ // detect to determine the best RNG source, normalizing to a function that
8
+ // returns 128-bits of randomness, since that's what's usually required
9
+ var _rng = require('./rng');
10
+
11
+ // Buffer class to use,
12
+ // we can't use `Buffer || Array` otherwise Buffer would be
13
+ // shimmed by browserify and added to the browser build
14
+ var BufferClass = require('./buffer');
15
+
16
+ // Maps for number <-> hex string conversion
17
+ var _byteToHex = [];
18
+ var _hexToByte = {};
19
+ for (var i = 0; i < 256; i++) {
20
+ _byteToHex[i] = (i + 0x100).toString(16).substr(1);
21
+ _hexToByte[_byteToHex[i]] = i;
22
+ }
23
+
24
+ // **`parse()` - Parse a UUID into it's component bytes**
25
+ function parse(s, buf, offset) {
26
+ var i = (buf && offset) || 0, ii = 0;
27
+
28
+ buf = buf || [];
29
+ s.toLowerCase().replace(/[0-9a-f]{2}/g, function(oct) {
30
+ if (ii < 16) { // Don't overflow!
31
+ buf[i + ii++] = _hexToByte[oct];
32
+ }
33
+ });
34
+
35
+ // Zero out remaining bytes if string was short
36
+ while (ii < 16) {
37
+ buf[i + ii++] = 0;
38
+ }
39
+
40
+ return buf;
41
+ }
42
+
43
+ // **`unparse()` - Convert UUID byte array (ala parse()) into a string**
44
+ function unparse(buf, offset) {
45
+ var i = offset || 0, bth = _byteToHex;
46
+ return bth[buf[i++]] + bth[buf[i++]] +
47
+ bth[buf[i++]] + bth[buf[i++]] + '-' +
48
+ bth[buf[i++]] + bth[buf[i++]] + '-' +
49
+ bth[buf[i++]] + bth[buf[i++]] + '-' +
50
+ bth[buf[i++]] + bth[buf[i++]] + '-' +
51
+ bth[buf[i++]] + bth[buf[i++]] +
52
+ bth[buf[i++]] + bth[buf[i++]] +
53
+ bth[buf[i++]] + bth[buf[i++]];
54
+ }
55
+
56
+ // **`v1()` - Generate time-based UUID**
57
+ //
58
+ // Inspired by https://github.com/LiosK/UUID.js
59
+ // and http://docs.python.org/library/uuid.html
60
+
61
+ // random #'s we need to init node and clockseq
62
+ var _seedBytes = _rng();
63
+
64
+ // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
65
+ var _nodeId = [
66
+ _seedBytes[0] | 0x01,
67
+ _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5]
68
+ ];
69
+
70
+ // Per 4.2.2, randomize (14 bit) clockseq
71
+ var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff;
72
+
73
+ // Previous uuid creation time
74
+ var _lastMSecs = 0, _lastNSecs = 0;
75
+
76
+ // See https://github.com/broofa/node-uuid for API details
77
+ function v1(options, buf, offset) {
78
+ var i = buf && offset || 0;
79
+ var b = buf || [];
80
+
81
+ options = options || {};
82
+
83
+ var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq;
84
+
85
+ // UUID timestamps are 100 nano-second units since the Gregorian epoch,
86
+ // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
87
+ // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
88
+ // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
89
+ var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime();
90
+
91
+ // Per 4.2.1.2, use count of uuid's generated during the current clock
92
+ // cycle to simulate higher resolution clock
93
+ var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;
94
+
95
+ // Time since last uuid creation (in msecs)
96
+ var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;
97
+
98
+ // Per 4.2.1.2, Bump clockseq on clock regression
99
+ if (dt < 0 && options.clockseq === undefined) {
100
+ clockseq = clockseq + 1 & 0x3fff;
101
+ }
102
+
103
+ // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
104
+ // time interval
105
+ if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
106
+ nsecs = 0;
107
+ }
108
+
109
+ // Per 4.2.1.2 Throw error if too many uuids are requested
110
+ if (nsecs >= 10000) {
111
+ throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');
112
+ }
113
+
114
+ _lastMSecs = msecs;
115
+ _lastNSecs = nsecs;
116
+ _clockseq = clockseq;
117
+
118
+ // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
119
+ msecs += 12219292800000;
120
+
121
+ // `time_low`
122
+ var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
123
+ b[i++] = tl >>> 24 & 0xff;
124
+ b[i++] = tl >>> 16 & 0xff;
125
+ b[i++] = tl >>> 8 & 0xff;
126
+ b[i++] = tl & 0xff;
127
+
128
+ // `time_mid`
129
+ var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
130
+ b[i++] = tmh >>> 8 & 0xff;
131
+ b[i++] = tmh & 0xff;
132
+
133
+ // `time_high_and_version`
134
+ b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
135
+ b[i++] = tmh >>> 16 & 0xff;
136
+
137
+ // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
138
+ b[i++] = clockseq >>> 8 | 0x80;
139
+
140
+ // `clock_seq_low`
141
+ b[i++] = clockseq & 0xff;
142
+
143
+ // `node`
144
+ var node = options.node || _nodeId;
145
+ for (var n = 0; n < 6; n++) {
146
+ b[i + n] = node[n];
147
+ }
148
+
149
+ return buf ? buf : unparse(b);
150
+ }
151
+
152
+ // **`v4()` - Generate random UUID**
153
+
154
+ // See https://github.com/broofa/node-uuid for API details
155
+ function v4(options, buf, offset) {
156
+ // Deprecated - 'format' argument, as supported in v1.2
157
+ var i = buf && offset || 0;
158
+
159
+ if (typeof(options) == 'string') {
160
+ buf = options == 'binary' ? new BufferClass(16) : null;
161
+ options = null;
162
+ }
163
+ options = options || {};
164
+
165
+ var rnds = options.random || (options.rng || _rng)();
166
+
167
+ // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
168
+ rnds[6] = (rnds[6] & 0x0f) | 0x40;
169
+ rnds[8] = (rnds[8] & 0x3f) | 0x80;
170
+
171
+ // Copy bytes to buffer, if provided
172
+ if (buf) {
173
+ for (var ii = 0; ii < 16; ii++) {
174
+ buf[i + ii] = rnds[ii];
175
+ }
176
+ }
177
+
178
+ return buf || unparse(rnds);
179
+ }
180
+
181
+ // Export public API
182
+ var uuid = v4;
183
+ uuid.v1 = v1;
184
+ uuid.v4 = v4;
185
+ uuid.parse = parse;
186
+ uuid.unparse = unparse;
187
+ uuid.BufferClass = BufferClass;
188
+
189
+ module.exports = uuid;
@@ -1,22 +0,0 @@
1
- Copyright (c) 2010 Nikhil Marathe <nsm.nikhil@gmail.com>
2
-
3
- Permission is hereby granted, free of charge, to any person
4
- obtaining a copy of this software and associated documentation
5
- files (the "Software"), to deal in the Software without
6
- restriction, including without limitation the rights to use,
7
- copy, modify, merge, publish, distribute, sublicense, and/or sell
8
- copies of the Software, and to permit persons to whom the
9
- Software is furnished to do so, subject to the following
10
- conditions:
11
-
12
- The above copyright notice and this permission notice shall be
13
- included in all copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
17
- OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
19
- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
20
- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21
- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22
- OTHER DEALINGS IN THE SOFTWARE.
@@ -1,15 +0,0 @@
1
- {
2
- "name": "uuid",
3
- "description": "Simple libuuid bindings to allow UUIDs to be generated from JS.",
4
- "version": "0.0.1",
5
- "author": "Nikhil Marathe",
6
- "repository": {
7
- "type": "hg",
8
- "url": "http://bitbucket.org/nikhilm/uuidjs"
9
- },
10
- "engine": [ "node >=0.1.103" ],
11
- "scripts": {
12
- "preinstall": "node-waf configure && node-waf build"
13
- },
14
- "main": "build/default/uuid.node"
15
- }
@@ -1,48 +0,0 @@
1
- // Copyright (C) 2010 Nikhil Marathe <nsm.nikhil@gmail.com>
2
-
3
- #include "uuid.h"
4
-
5
- #include <cstring>
6
-
7
- using namespace v8;
8
- using namespace node;
9
-
10
- extern "C"
11
- void init( Handle<Object> target ) {
12
- HandleScope scope;
13
- uuid_v8::Initialize( target );
14
- }
15
-
16
- namespace uuid_v8 {
17
-
18
- void Initialize( Handle<Object> target ) {
19
- HandleScope scope;
20
-
21
- Local<FunctionTemplate> t = FunctionTemplate::New(Generate);
22
-
23
- target->Set( String::NewSymbol( "generate" ), t->GetFunction() );
24
- }
25
-
26
- Handle<Value> Generate( const Arguments &args ) {
27
- HandleScope scope;
28
-
29
- uuid_t new_uuid;
30
- encoding encode = ASCII;
31
- char unparsed[40];
32
-
33
- if (args.Length() > 0) {
34
- encode = ParseEncoding(args[0], encode);
35
- }
36
-
37
- uuid_generate(new_uuid);
38
-
39
- if (encode == BINARY) {
40
- return Encode(new_uuid, sizeof(uuid_t), encode);
41
- }
42
- else {
43
- uuid_unparse( new_uuid, unparsed );
44
- return Encode(unparsed, strlen(unparsed), encode);
45
- }
46
- }
47
-
48
- }
@@ -1,14 +0,0 @@
1
- // Copyright (C) 2010 Nikhil Marathe <nsm.nikhil@gmail.com>
2
-
3
- #ifndef _LIBUUID_V8_
4
- #define _LIBUUID_V8_
5
-
6
- #include <uuid/uuid.h>
7
- #include <v8.h>
8
- #include <node.h>
9
-
10
- namespace uuid_v8 {
11
- void Initialize( v8::Handle<v8::Object> target );
12
- v8::Handle<v8::Value> Generate( const v8::Arguments &args );
13
- }
14
- #endif
@@ -1,12 +0,0 @@
1
- var uuid = require( "./uuid" )
2
- , sys = require( "sys" )
3
-
4
- for( var i = 0; i < 10; i++ ) {
5
- // these two are the same
6
- sys.debug( uuid.generate() );
7
- sys.debug( uuid.generate('ascii') );
8
- // don't convert to hex, get the binary string
9
- sys.debug( uuid.generate('binary') );
10
- sys.debug( "-------------" );
11
- }
12
-
@@ -1,39 +0,0 @@
1
- import Options
2
- from os import popen, unlink, symlink, getcwd
3
- from os.path import exists
4
- import sys
5
-
6
- srcdir = "."
7
- blddir = "build"
8
- VERSION = "0.0.1"
9
-
10
- def set_options(opt):
11
- opt.tool_options("compiler_cxx")
12
-
13
- def configure(conf):
14
- conf.check_tool("compiler_cxx")
15
- conf.check_tool("node_addon")
16
- libuuid = conf.check(lib = 'uuid', libpath = ['/usr/lib', '/usr/local/lib'], uselib_store = 'UUID')
17
- if not libuuid:
18
- conf.fatal('Install libuuid devel libraries. `apt-get uuid-dev` on debian systems.')
19
-
20
- def build(bld):
21
- obj = bld.new_task_gen("cxx", "shlib", "node_addon")
22
- obj.target = "uuid"
23
- obj.find_sources_in_dirs("src")
24
- # see http://www.mail-archive.com/programming@jsoftware.com/msg05886.html
25
- # Thanks to Elijah Insua
26
- # http://groups.google.com/group/nodejs/msg/442a49ce6f86d70d
27
- if sys.platform == 'darwin':
28
- obj.lib = ["System"]
29
- else:
30
- obj.lib = ["uuid"]
31
-
32
- def shutdown(bld):
33
- # HACK to get binding.node out of build directory.
34
- # better way to do this?
35
- if Options.commands['clean']:
36
- if exists('uuid.node'): unlink('uuid.node')
37
- else:
38
- if exists('build/default/uuid.node') and not exists('uuid.node'):
39
- symlink(getcwd()+'/build/default/uuid.node', 'uuid.node')