generateTimeBasedUuid.js 12 KB

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