generateTimeBasedUuid.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. /*
  2. Copyright (c) 2004-2012, The Dojo Foundation All Rights Reserved.
  3. Available via Academic Free License >= 2.1 OR the modified BSD license.
  4. see: http://dojotoolkit.org/license for details
  5. */
  6. if(!dojo._hasResource["dojox.uuid.generateTimeBasedUuid"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
  7. dojo._hasResource["dojox.uuid.generateTimeBasedUuid"] = true;
  8. dojo.provide("dojox.uuid.generateTimeBasedUuid");
  9. dojox.uuid.generateTimeBasedUuid = function(/*String?*/ node){
  10. // summary:
  11. // This function generates time-based UUIDs, meaning "version 1" UUIDs.
  12. // description:
  13. // For more info, see
  14. // http://www.webdav.org/specs/draft-leach-uuids-guids-01.txt
  15. // http://www.infonuovo.com/dma/csdocs/sketch/instidid.htm
  16. // http://kruithof.xs4all.nl/uuid/uuidgen
  17. // http://www.opengroup.org/onlinepubs/009629399/apdxa.htm#tagcjh_20
  18. // http://jakarta.apache.org/commons/sandbox/id/apidocs/org/apache/commons/id/uuid/clock/Clock.html
  19. // node:
  20. // A 12-character hex string representing either a pseudo-node or
  21. // hardware-node (an IEEE 802.3 network node). A hardware-node
  22. // will be something like "017bf397618a", always with the first bit
  23. // being 0. A pseudo-node will be something like "f17bf397618a",
  24. // always with the first bit being 1.
  25. // examples:
  26. // string = dojox.uuid.generateTimeBasedUuid();
  27. // string = dojox.uuid.generateTimeBasedUuid("017bf397618a");
  28. // dojox.uuid.generateTimeBasedUuid.setNode("017bf397618a");
  29. // string = dojox.uuid.generateTimeBasedUuid(); // the generated UUID has node == "017bf397618a"
  30. var uuidString = dojox.uuid.generateTimeBasedUuid._generator.generateUuidString(node);
  31. return uuidString; // String
  32. };
  33. dojox.uuid.generateTimeBasedUuid.isValidNode = function(/*String?*/ node){
  34. var HEX_RADIX = 16;
  35. var integer = parseInt(node, HEX_RADIX);
  36. var valid = dojo.isString(node) && node.length == 12 && isFinite(integer);
  37. return valid; // Boolean
  38. };
  39. dojox.uuid.generateTimeBasedUuid.setNode = function(/*String?*/ node){
  40. // summary:
  41. // Sets the 'node' value that will be included in generated UUIDs.
  42. // node: A 12-character hex string representing a pseudoNode or hardwareNode.
  43. dojox.uuid.assert((node === null) || this.isValidNode(node));
  44. this._uniformNode = node;
  45. };
  46. dojox.uuid.generateTimeBasedUuid.getNode = function(){
  47. // summary:
  48. // Returns the 'node' value that will be included in generated UUIDs.
  49. return this._uniformNode; // String (a 12-character hex string representing a pseudoNode or hardwareNode)
  50. };
  51. dojox.uuid.generateTimeBasedUuid._generator = new function(){
  52. // Number of hours between October 15, 1582 and January 1, 1970:
  53. this.GREGORIAN_CHANGE_OFFSET_IN_HOURS = 3394248;
  54. // Number of seconds between October 15, 1582 and January 1, 1970:
  55. // dojox.uuid.generateTimeBasedUuid.GREGORIAN_CHANGE_OFFSET_IN_SECONDS = 12219292800;
  56. // --------------------------------------------------
  57. // Private variables:
  58. var _uuidPseudoNodeString = null;
  59. var _uuidClockSeqString = null;
  60. var _dateValueOfPreviousUuid = null;
  61. var _nextIntraMillisecondIncrement = 0;
  62. var _cachedMillisecondsBetween1582and1970 = null;
  63. var _cachedHundredNanosecondIntervalsPerMillisecond = null;
  64. // --------------------------------------------------
  65. // Private constants:
  66. var HEX_RADIX = 16;
  67. function _carry(/* array */ arrayA){
  68. // summary:
  69. // Given an array which holds a 64-bit number broken into 4 16-bit
  70. // elements, this method carries any excess bits (greater than 16-bits)
  71. // from each array element into the next.
  72. // arrayA: An array with 4 elements, each of which is a 16-bit number.
  73. arrayA[2] += arrayA[3] >>> 16;
  74. arrayA[3] &= 0xFFFF;
  75. arrayA[1] += arrayA[2] >>> 16;
  76. arrayA[2] &= 0xFFFF;
  77. arrayA[0] += arrayA[1] >>> 16;
  78. arrayA[1] &= 0xFFFF;
  79. dojox.uuid.assert((arrayA[0] >>> 16) === 0);
  80. }
  81. function _get64bitArrayFromFloat(/* float */ x){
  82. // summary:
  83. // Given a floating point number, this method returns an array which
  84. // holds a 64-bit number broken into 4 16-bit elements.
  85. var result = new Array(0, 0, 0, 0);
  86. result[3] = x % 0x10000;
  87. x -= result[3];
  88. x /= 0x10000;
  89. result[2] = x % 0x10000;
  90. x -= result[2];
  91. x /= 0x10000;
  92. result[1] = x % 0x10000;
  93. x -= result[1];
  94. x /= 0x10000;
  95. result[0] = x;
  96. return result; // Array with 4 elements, each of which is a 16-bit number.
  97. }
  98. function _addTwo64bitArrays(/* array */ arrayA, /* array */ arrayB){
  99. // summary:
  100. // Takes two arrays, each of which holds a 64-bit number broken into 4
  101. // 16-bit elements, and returns a new array that holds a 64-bit number
  102. // that is the sum of the two original numbers.
  103. // arrayA: An array with 4 elements, each of which is a 16-bit number.
  104. // arrayB: An array with 4 elements, each of which is a 16-bit number.
  105. dojox.uuid.assert(dojo.isArray(arrayA));
  106. dojox.uuid.assert(dojo.isArray(arrayB));
  107. dojox.uuid.assert(arrayA.length == 4);
  108. dojox.uuid.assert(arrayB.length == 4);
  109. var result = new Array(0, 0, 0, 0);
  110. result[3] = arrayA[3] + arrayB[3];
  111. result[2] = arrayA[2] + arrayB[2];
  112. result[1] = arrayA[1] + arrayB[1];
  113. result[0] = arrayA[0] + arrayB[0];
  114. _carry(result);
  115. return result; // Array with 4 elements, each of which is a 16-bit number.
  116. }
  117. function _multiplyTwo64bitArrays(/* array */ arrayA, /* array */ arrayB){
  118. // summary:
  119. // Takes two arrays, each of which holds a 64-bit number broken into 4
  120. // 16-bit elements, and returns a new array that holds a 64-bit number
  121. // that is the product of the two original numbers.
  122. // arrayA: An array with 4 elements, each of which is a 16-bit number.
  123. // arrayB: An array with 4 elements, each of which is a 16-bit number.
  124. dojox.uuid.assert(dojo.isArray(arrayA));
  125. dojox.uuid.assert(dojo.isArray(arrayB));
  126. dojox.uuid.assert(arrayA.length == 4);
  127. dojox.uuid.assert(arrayB.length == 4);
  128. var overflow = false;
  129. if(arrayA[0] * arrayB[0] !== 0){ overflow = true; }
  130. if(arrayA[0] * arrayB[1] !== 0){ overflow = true; }
  131. if(arrayA[0] * arrayB[2] !== 0){ overflow = true; }
  132. if(arrayA[1] * arrayB[0] !== 0){ overflow = true; }
  133. if(arrayA[1] * arrayB[1] !== 0){ overflow = true; }
  134. if(arrayA[2] * arrayB[0] !== 0){ overflow = true; }
  135. dojox.uuid.assert(!overflow);
  136. var result = new Array(0, 0, 0, 0);
  137. result[0] += arrayA[0] * arrayB[3];
  138. _carry(result);
  139. result[0] += arrayA[1] * arrayB[2];
  140. _carry(result);
  141. result[0] += arrayA[2] * arrayB[1];
  142. _carry(result);
  143. result[0] += arrayA[3] * arrayB[0];
  144. _carry(result);
  145. result[1] += arrayA[1] * arrayB[3];
  146. _carry(result);
  147. result[1] += arrayA[2] * arrayB[2];
  148. _carry(result);
  149. result[1] += arrayA[3] * arrayB[1];
  150. _carry(result);
  151. result[2] += arrayA[2] * arrayB[3];
  152. _carry(result);
  153. result[2] += arrayA[3] * arrayB[2];
  154. _carry(result);
  155. result[3] += arrayA[3] * arrayB[3];
  156. _carry(result);
  157. return result; // Array with 4 elements, each of which is a 16-bit number.
  158. }
  159. function _padWithLeadingZeros(/* string */ string, /* int */ desiredLength){
  160. // summary:
  161. // Pads a string with leading zeros and returns the result.
  162. // string: A string to add padding to.
  163. // desiredLength: The number of characters the return string should have.
  164. // examples:
  165. // result = _padWithLeadingZeros("abc", 6);
  166. // dojox.uuid.assert(result == "000abc");
  167. while(string.length < desiredLength){
  168. string = "0" + string;
  169. }
  170. return string; // string
  171. }
  172. function _generateRandomEightCharacterHexString() {
  173. // summary:
  174. // Returns a randomly generated 8-character string of hex digits.
  175. // FIXME: This probably isn't a very high quality random number.
  176. // Make random32bitNumber be a randomly generated floating point number
  177. // between 0 and (4,294,967,296 - 1), inclusive.
  178. var random32bitNumber = Math.floor( (Math.random() % 1) * Math.pow(2, 32) );
  179. var eightCharacterString = random32bitNumber.toString(HEX_RADIX);
  180. while(eightCharacterString.length < 8){
  181. eightCharacterString = "0" + eightCharacterString;
  182. }
  183. return eightCharacterString; // String (an 8-character hex string)
  184. }
  185. this.generateUuidString = function(/*String?*/ node){
  186. // summary:
  187. // Generates a time-based UUID, meaning a version 1 UUID.
  188. // description:
  189. // JavaScript code running in a browser doesn't have access to the
  190. // IEEE 802.3 address of the computer, so if a node value isn't
  191. // supplied, we generate a random pseudonode value instead.
  192. // node: An optional 12-character string to use as the node in the new UUID.
  193. if(node){
  194. dojox.uuid.assert(dojox.uuid.generateTimeBasedUuid.isValidNode(node));
  195. }else{
  196. if(dojox.uuid.generateTimeBasedUuid._uniformNode){
  197. node = dojox.uuid.generateTimeBasedUuid._uniformNode;
  198. }else{
  199. if(!_uuidPseudoNodeString){
  200. var pseudoNodeIndicatorBit = 0x8000;
  201. var random15bitNumber = Math.floor( (Math.random() % 1) * Math.pow(2, 15) );
  202. var leftmost4HexCharacters = (pseudoNodeIndicatorBit | random15bitNumber).toString(HEX_RADIX);
  203. _uuidPseudoNodeString = leftmost4HexCharacters + _generateRandomEightCharacterHexString();
  204. }
  205. node = _uuidPseudoNodeString;
  206. }
  207. }
  208. if(!_uuidClockSeqString){
  209. var variantCodeForDCEUuids = 0x8000; // 10--------------, i.e. uses only first two of 16 bits.
  210. var random14bitNumber = Math.floor( (Math.random() % 1) * Math.pow(2, 14) );
  211. _uuidClockSeqString = (variantCodeForDCEUuids | random14bitNumber).toString(HEX_RADIX);
  212. }
  213. // Maybe we should think about trying to make the code more readable to
  214. // newcomers by creating a class called "WholeNumber" that encapsulates
  215. // the methods and data structures for working with these arrays that
  216. // hold 4 16-bit numbers? And then these variables below have names
  217. // like "wholeSecondsPerHour" rather than "arraySecondsPerHour"?
  218. var now = new Date();
  219. var millisecondsSince1970 = now.valueOf(); // milliseconds since midnight 01 January, 1970 UTC.
  220. var nowArray = _get64bitArrayFromFloat(millisecondsSince1970);
  221. if(!_cachedMillisecondsBetween1582and1970){
  222. var arraySecondsPerHour = _get64bitArrayFromFloat(60 * 60);
  223. var arrayHoursBetween1582and1970 = _get64bitArrayFromFloat(dojox.uuid.generateTimeBasedUuid._generator.GREGORIAN_CHANGE_OFFSET_IN_HOURS);
  224. var arraySecondsBetween1582and1970 = _multiplyTwo64bitArrays(arrayHoursBetween1582and1970, arraySecondsPerHour);
  225. var arrayMillisecondsPerSecond = _get64bitArrayFromFloat(1000);
  226. _cachedMillisecondsBetween1582and1970 = _multiplyTwo64bitArrays(arraySecondsBetween1582and1970, arrayMillisecondsPerSecond);
  227. _cachedHundredNanosecondIntervalsPerMillisecond = _get64bitArrayFromFloat(10000);
  228. }
  229. var arrayMillisecondsSince1970 = nowArray;
  230. var arrayMillisecondsSince1582 = _addTwo64bitArrays(_cachedMillisecondsBetween1582and1970, arrayMillisecondsSince1970);
  231. var arrayHundredNanosecondIntervalsSince1582 = _multiplyTwo64bitArrays(arrayMillisecondsSince1582, _cachedHundredNanosecondIntervalsPerMillisecond);
  232. if(now.valueOf() == _dateValueOfPreviousUuid){
  233. arrayHundredNanosecondIntervalsSince1582[3] += _nextIntraMillisecondIncrement;
  234. _carry(arrayHundredNanosecondIntervalsSince1582);
  235. _nextIntraMillisecondIncrement += 1;
  236. if (_nextIntraMillisecondIncrement == 10000) {
  237. // If we've gotten to here, it means we've already generated 10,000
  238. // UUIDs in this single millisecond, which is the most that the UUID
  239. // timestamp field allows for. So now we'll just sit here and wait
  240. // for a fraction of a millisecond, so as to ensure that the next
  241. // time this method is called there will be a different millisecond
  242. // value in the timestamp field.
  243. while (now.valueOf() == _dateValueOfPreviousUuid) {
  244. now = new Date();
  245. }
  246. }
  247. }else{
  248. _dateValueOfPreviousUuid = now.valueOf();
  249. _nextIntraMillisecondIncrement = 1;
  250. }
  251. var hexTimeLowLeftHalf = arrayHundredNanosecondIntervalsSince1582[2].toString(HEX_RADIX);
  252. var hexTimeLowRightHalf = arrayHundredNanosecondIntervalsSince1582[3].toString(HEX_RADIX);
  253. var hexTimeLow = _padWithLeadingZeros(hexTimeLowLeftHalf, 4) + _padWithLeadingZeros(hexTimeLowRightHalf, 4);
  254. var hexTimeMid = arrayHundredNanosecondIntervalsSince1582[1].toString(HEX_RADIX);
  255. hexTimeMid = _padWithLeadingZeros(hexTimeMid, 4);
  256. var hexTimeHigh = arrayHundredNanosecondIntervalsSince1582[0].toString(HEX_RADIX);
  257. hexTimeHigh = _padWithLeadingZeros(hexTimeHigh, 3);
  258. var hyphen = "-";
  259. var versionCodeForTimeBasedUuids = "1"; // binary2hex("0001")
  260. var resultUuid = hexTimeLow + hyphen + hexTimeMid + hyphen +
  261. versionCodeForTimeBasedUuids + hexTimeHigh + hyphen +
  262. _uuidClockSeqString + hyphen + node;
  263. resultUuid = resultUuid.toLowerCase();
  264. return resultUuid; // String (a 36 character string, which will look something like "b4308fb0-86cd-11da-a72b-0800200c9a66")
  265. }
  266. }();
  267. }