", "github": "https://github.com/ctavan"}
],
"lib" : ".",
"main" : "./uuid.js",
"repository" : { "type" : "git", "url" : "https://github.com/broofa/node-uuid.git" },
"version" : "1.4.0"
}
node-uuid-1.4.0/test/ 0000775 0000000 0000000 00000000000 12040004472 0014355 5 ustar 00root root 0000000 0000000 node-uuid-1.4.0/test/compare_v1.js 0000664 0000000 0000000 00000002713 12040004472 0016752 0 ustar 00root root 0000000 0000000 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();
node-uuid-1.4.0/test/test.html 0000664 0000000 0000000 00000000524 12040004472 0016223 0 ustar 00root root 0000000 0000000
node-uuid-1.4.0/test/test.js 0000664 0000000 0000000 00000014030 12040004472 0015670 0 ustar 00root root 0000000 0000000 if (!this.uuid) {
// node.js
uuid = require('../uuid');
}
//
// x-platform log/assert shims
//
function _log(msg, type) {
type = type || 'log';
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
//
// 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();
assert(sorted.toString() == ids.toString(), name + ' have expected order');
}
// Verify ordering of v1 ids created using default behavior
compare('uuids with current time', [
uuid.v1(),
uuid.v1(),
uuid.v1(),
uuid.v1(),
uuid.v1()
]);
// Verify ordering of v1 ids created with explicit times
compare('uuids with time option', [
uuid.v1({msecs: TIME - 10*3600*1000}),
uuid.v1({msecs: TIME - 1}),
uuid.v1({msecs: TIME}),
uuid.v1({msecs: TIME + 1}),
uuid.v1({msecs: TIME + 28*24*3600*1000})
]);
assert(
uuid.v1({msecs: TIME}) != uuid.v1({msecs: TIME}),
'IDs created at same msec are different'
);
// 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');
// 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 ]
});
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);
}
}
}
// 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 + '%)');
}
}
}
// Perf tests
for (var version in generators) {
log('\nPerformance testing ' + version + ' UUIDs');
var generator = generators[version];
var buf = new uuid.BufferClass(16);
for (var i = 0, t = Date.now(); i < N; i++) generator();
rate('uuid.' + version + '()', t);
for (var i = 0, t = Date.now(); i < N; i++) generator('binary');
rate('uuid.' + version + '(\'binary\')', t);
for (var i = 0, t = Date.now(); i < N; i++) generator('binary', buf);
rate('uuid.' + version + '(\'binary\', buffer)', t);
}
node-uuid-1.4.0/uuid.js 0000664 0000000 0000000 00000015777 12040004472 0014723 0 ustar 00root root 0000000 0000000 // uuid.js
//
// (c) 2010-2012 Robert Kieffer
// MIT License
// https://github.com/broofa/node-uuid
(function() {
var _global = this;
// 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;
// Node.js crypto-based RNG - http://nodejs.org/docs/v0.6.2/api/crypto.html
//
// Moderately fast, high quality
if (typeof(require) == 'function') {
try {
var _rb = require('crypto').randomBytes;
_rng = _rb && function() {return _rb(16);};
} catch(e) {}
}
if (!_rng && _global.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;
};
}
// Buffer class to use
var BufferClass = typeof(Buffer) == 'function' ? 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;
}
return buf;
}
// **`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++]];
}
// **`v1()` - Generate time-based UUID**
//
// Inspired by https://github.com/LiosK/UUID.js
// and http://docs.python.org/library/uuid.html
// random #'s we need to init node and clockseq
var _seedBytes = _rng();
// 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]
];
// Per 4.2.2, randomize (14 bit) clockseq
var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff;
// Previous uuid creation time
var _lastMSecs = 0, _lastNSecs = 0;
// See https://github.com/broofa/node-uuid for API details
function v1(options, buf, offset) {
var i = buf && offset || 0;
var b = buf || [];
options = options || {};
var clockseq = options.clockseq != null ? options.clockseq : _clockseq;
// 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, 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;
// Time since last uuid creation (in msecs)
var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;
// Per 4.2.1.2, Bump clockseq on clock regression
if (dt < 0 && options.clockseq == null) {
clockseq = clockseq + 1 & 0x3fff;
}
// 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.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');
}
_lastMSecs = msecs;
_lastNSecs = nsecs;
_clockseq = clockseq;
// Per 4.1.4 - Convert from unix epoch to Gregorian epoch
msecs += 12219292800000;
// `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;
// `time_mid`
var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
b[i++] = tmh >>> 8 & 0xff;
b[i++] = tmh & 0xff;
// `time_high_and_version`
b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
b[i++] = tmh >>> 16 & 0xff;
// `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
b[i++] = clockseq >>> 8 | 0x80;
// `clock_seq_low`
b[i++] = clockseq & 0xff;
// `node`
var node = options.node || _nodeId;
for (var n = 0; n < 6; n++) {
b[i + n] = node[n];
}
return buf ? buf : unparse(b);
}
// **`v4()` - Generate random UUID**
// 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;
if (typeof(options) == 'string') {
buf = options == 'binary' ? new BufferClass(16) : null;
options = null;
}
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 || unparse(rnds);
}
// Export public API
var uuid = v4;
uuid.v1 = v1;
uuid.v4 = v4;
uuid.parse = parse;
uuid.unparse = unparse;
uuid.BufferClass = BufferClass;
if (_global.define && define.amd) {
// Publish as AMD module
define(function() {return uuid;});
} else if (typeof(module) != 'undefined' && module.exports) {
// Publish as node.js module
module.exports = uuid;
} else {
// Publish as global (in browsers)
var _previousRoot = _global.uuid;
// **`noConflict()` - (browser only) to reset global 'uuid' var**
uuid.noConflict = function() {
_global.uuid = _previousRoot;
return uuid;
};
_global.uuid = uuid;
}
}());