You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3000 lines
77 KiB

4 years ago
  1. /**
  2. * Utility functions for web applications.
  3. *
  4. * @author Dave Longley
  5. *
  6. * Copyright (c) 2010-2018 Digital Bazaar, Inc.
  7. */
  8. var forge = require('./forge');
  9. var baseN = require('./baseN');
  10. /* Utilities API */
  11. var util = module.exports = forge.util = forge.util || {};
  12. // define setImmediate and nextTick
  13. (function() {
  14. // use native nextTick (unless we're in webpack)
  15. // webpack (or better node-libs-browser polyfill) sets process.browser.
  16. // this way we can detect webpack properly
  17. if(typeof process !== 'undefined' && process.nextTick && !process.browser) {
  18. util.nextTick = process.nextTick;
  19. if(typeof setImmediate === 'function') {
  20. util.setImmediate = setImmediate;
  21. } else {
  22. // polyfill setImmediate with nextTick, older versions of node
  23. // (those w/o setImmediate) won't totally starve IO
  24. util.setImmediate = util.nextTick;
  25. }
  26. return;
  27. }
  28. // polyfill nextTick with native setImmediate
  29. if(typeof setImmediate === 'function') {
  30. util.setImmediate = function() { return setImmediate.apply(undefined, arguments); };
  31. util.nextTick = function(callback) {
  32. return setImmediate(callback);
  33. };
  34. return;
  35. }
  36. /* Note: A polyfill upgrade pattern is used here to allow combining
  37. polyfills. For example, MutationObserver is fast, but blocks UI updates,
  38. so it needs to allow UI updates periodically, so it falls back on
  39. postMessage or setTimeout. */
  40. // polyfill with setTimeout
  41. util.setImmediate = function(callback) {
  42. setTimeout(callback, 0);
  43. };
  44. // upgrade polyfill to use postMessage
  45. if(typeof window !== 'undefined' &&
  46. typeof window.postMessage === 'function') {
  47. var msg = 'forge.setImmediate';
  48. var callbacks = [];
  49. util.setImmediate = function(callback) {
  50. callbacks.push(callback);
  51. // only send message when one hasn't been sent in
  52. // the current turn of the event loop
  53. if(callbacks.length === 1) {
  54. window.postMessage(msg, '*');
  55. }
  56. };
  57. function handler(event) {
  58. if(event.source === window && event.data === msg) {
  59. event.stopPropagation();
  60. var copy = callbacks.slice();
  61. callbacks.length = 0;
  62. copy.forEach(function(callback) {
  63. callback();
  64. });
  65. }
  66. }
  67. window.addEventListener('message', handler, true);
  68. }
  69. // upgrade polyfill to use MutationObserver
  70. if(typeof MutationObserver !== 'undefined') {
  71. // polyfill with MutationObserver
  72. var now = Date.now();
  73. var attr = true;
  74. var div = document.createElement('div');
  75. var callbacks = [];
  76. new MutationObserver(function() {
  77. var copy = callbacks.slice();
  78. callbacks.length = 0;
  79. copy.forEach(function(callback) {
  80. callback();
  81. });
  82. }).observe(div, {attributes: true});
  83. var oldSetImmediate = util.setImmediate;
  84. util.setImmediate = function(callback) {
  85. if(Date.now() - now > 15) {
  86. now = Date.now();
  87. oldSetImmediate(callback);
  88. } else {
  89. callbacks.push(callback);
  90. // only trigger observer when it hasn't been triggered in
  91. // the current turn of the event loop
  92. if(callbacks.length === 1) {
  93. div.setAttribute('a', attr = !attr);
  94. }
  95. }
  96. };
  97. }
  98. util.nextTick = util.setImmediate;
  99. })();
  100. // check if running under Node.js
  101. util.isNodejs =
  102. typeof process !== 'undefined' && process.versions && process.versions.node;
  103. // 'self' will also work in Web Workers (instance of WorkerGlobalScope) while
  104. // it will point to `window` in the main thread.
  105. // To remain compatible with older browsers, we fall back to 'window' if 'self'
  106. // is not available.
  107. util.globalScope = (function() {
  108. if(util.isNodejs) {
  109. return global;
  110. }
  111. return typeof self === 'undefined' ? window : self;
  112. })();
  113. // define isArray
  114. util.isArray = Array.isArray || function(x) {
  115. return Object.prototype.toString.call(x) === '[object Array]';
  116. };
  117. // define isArrayBuffer
  118. util.isArrayBuffer = function(x) {
  119. return typeof ArrayBuffer !== 'undefined' && x instanceof ArrayBuffer;
  120. };
  121. // define isArrayBufferView
  122. util.isArrayBufferView = function(x) {
  123. return x && util.isArrayBuffer(x.buffer) && x.byteLength !== undefined;
  124. };
  125. /**
  126. * Ensure a bits param is 8, 16, 24, or 32. Used to validate input for
  127. * algorithms where bit manipulation, JavaScript limitations, and/or algorithm
  128. * design only allow for byte operations of a limited size.
  129. *
  130. * @param n number of bits.
  131. *
  132. * Throw Error if n invalid.
  133. */
  134. function _checkBitsParam(n) {
  135. if(!(n === 8 || n === 16 || n === 24 || n === 32)) {
  136. throw new Error('Only 8, 16, 24, or 32 bits supported: ' + n);
  137. }
  138. }
  139. // TODO: set ByteBuffer to best available backing
  140. util.ByteBuffer = ByteStringBuffer;
  141. /** Buffer w/BinaryString backing */
  142. /**
  143. * Constructor for a binary string backed byte buffer.
  144. *
  145. * @param [b] the bytes to wrap (either encoded as string, one byte per
  146. * character, or as an ArrayBuffer or Typed Array).
  147. */
  148. function ByteStringBuffer(b) {
  149. // TODO: update to match DataBuffer API
  150. // the data in this buffer
  151. this.data = '';
  152. // the pointer for reading from this buffer
  153. this.read = 0;
  154. if(typeof b === 'string') {
  155. this.data = b;
  156. } else if(util.isArrayBuffer(b) || util.isArrayBufferView(b)) {
  157. if(typeof Buffer !== 'undefined' && b instanceof Buffer) {
  158. this.data = b.toString('binary');
  159. } else {
  160. // convert native buffer to forge buffer
  161. // FIXME: support native buffers internally instead
  162. var arr = new Uint8Array(b);
  163. try {
  164. this.data = String.fromCharCode.apply(null, arr);
  165. } catch(e) {
  166. for(var i = 0; i < arr.length; ++i) {
  167. this.putByte(arr[i]);
  168. }
  169. }
  170. }
  171. } else if(b instanceof ByteStringBuffer ||
  172. (typeof b === 'object' && typeof b.data === 'string' &&
  173. typeof b.read === 'number')) {
  174. // copy existing buffer
  175. this.data = b.data;
  176. this.read = b.read;
  177. }
  178. // used for v8 optimization
  179. this._constructedStringLength = 0;
  180. }
  181. util.ByteStringBuffer = ByteStringBuffer;
  182. /* Note: This is an optimization for V8-based browsers. When V8 concatenates
  183. a string, the strings are only joined logically using a "cons string" or
  184. "constructed/concatenated string". These containers keep references to one
  185. another and can result in very large memory usage. For example, if a 2MB
  186. string is constructed by concatenating 4 bytes together at a time, the
  187. memory usage will be ~44MB; so ~22x increase. The strings are only joined
  188. together when an operation requiring their joining takes place, such as
  189. substr(). This function is called when adding data to this buffer to ensure
  190. these types of strings are periodically joined to reduce the memory
  191. footprint. */
  192. var _MAX_CONSTRUCTED_STRING_LENGTH = 4096;
  193. util.ByteStringBuffer.prototype._optimizeConstructedString = function(x) {
  194. this._constructedStringLength += x;
  195. if(this._constructedStringLength > _MAX_CONSTRUCTED_STRING_LENGTH) {
  196. // this substr() should cause the constructed string to join
  197. this.data.substr(0, 1);
  198. this._constructedStringLength = 0;
  199. }
  200. };
  201. /**
  202. * Gets the number of bytes in this buffer.
  203. *
  204. * @return the number of bytes in this buffer.
  205. */
  206. util.ByteStringBuffer.prototype.length = function() {
  207. return this.data.length - this.read;
  208. };
  209. /**
  210. * Gets whether or not this buffer is empty.
  211. *
  212. * @return true if this buffer is empty, false if not.
  213. */
  214. util.ByteStringBuffer.prototype.isEmpty = function() {
  215. return this.length() <= 0;
  216. };
  217. /**
  218. * Puts a byte in this buffer.
  219. *
  220. * @param b the byte to put.
  221. *
  222. * @return this buffer.
  223. */
  224. util.ByteStringBuffer.prototype.putByte = function(b) {
  225. return this.putBytes(String.fromCharCode(b));
  226. };
  227. /**
  228. * Puts a byte in this buffer N times.
  229. *
  230. * @param b the byte to put.
  231. * @param n the number of bytes of value b to put.
  232. *
  233. * @return this buffer.
  234. */
  235. util.ByteStringBuffer.prototype.fillWithByte = function(b, n) {
  236. b = String.fromCharCode(b);
  237. var d = this.data;
  238. while(n > 0) {
  239. if(n & 1) {
  240. d += b;
  241. }
  242. n >>>= 1;
  243. if(n > 0) {
  244. b += b;
  245. }
  246. }
  247. this.data = d;
  248. this._optimizeConstructedString(n);
  249. return this;
  250. };
  251. /**
  252. * Puts bytes in this buffer.
  253. *
  254. * @param bytes the bytes (as a binary encoded string) to put.
  255. *
  256. * @return this buffer.
  257. */
  258. util.ByteStringBuffer.prototype.putBytes = function(bytes) {
  259. this.data += bytes;
  260. this._optimizeConstructedString(bytes.length);
  261. return this;
  262. };
  263. /**
  264. * Puts a UTF-16 encoded string into this buffer.
  265. *
  266. * @param str the string to put.
  267. *
  268. * @return this buffer.
  269. */
  270. util.ByteStringBuffer.prototype.putString = function(str) {
  271. return this.putBytes(util.encodeUtf8(str));
  272. };
  273. /**
  274. * Puts a 16-bit integer in this buffer in big-endian order.
  275. *
  276. * @param i the 16-bit integer.
  277. *
  278. * @return this buffer.
  279. */
  280. util.ByteStringBuffer.prototype.putInt16 = function(i) {
  281. return this.putBytes(
  282. String.fromCharCode(i >> 8 & 0xFF) +
  283. String.fromCharCode(i & 0xFF));
  284. };
  285. /**
  286. * Puts a 24-bit integer in this buffer in big-endian order.
  287. *
  288. * @param i the 24-bit integer.
  289. *
  290. * @return this buffer.
  291. */
  292. util.ByteStringBuffer.prototype.putInt24 = function(i) {
  293. return this.putBytes(
  294. String.fromCharCode(i >> 16 & 0xFF) +
  295. String.fromCharCode(i >> 8 & 0xFF) +
  296. String.fromCharCode(i & 0xFF));
  297. };
  298. /**
  299. * Puts a 32-bit integer in this buffer in big-endian order.
  300. *
  301. * @param i the 32-bit integer.
  302. *
  303. * @return this buffer.
  304. */
  305. util.ByteStringBuffer.prototype.putInt32 = function(i) {
  306. return this.putBytes(
  307. String.fromCharCode(i >> 24 & 0xFF) +
  308. String.fromCharCode(i >> 16 & 0xFF) +
  309. String.fromCharCode(i >> 8 & 0xFF) +
  310. String.fromCharCode(i & 0xFF));
  311. };
  312. /**
  313. * Puts a 16-bit integer in this buffer in little-endian order.
  314. *
  315. * @param i the 16-bit integer.
  316. *
  317. * @return this buffer.
  318. */
  319. util.ByteStringBuffer.prototype.putInt16Le = function(i) {
  320. return this.putBytes(
  321. String.fromCharCode(i & 0xFF) +
  322. String.fromCharCode(i >> 8 & 0xFF));
  323. };
  324. /**
  325. * Puts a 24-bit integer in this buffer in little-endian order.
  326. *
  327. * @param i the 24-bit integer.
  328. *
  329. * @return this buffer.
  330. */
  331. util.ByteStringBuffer.prototype.putInt24Le = function(i) {
  332. return this.putBytes(
  333. String.fromCharCode(i & 0xFF) +
  334. String.fromCharCode(i >> 8 & 0xFF) +
  335. String.fromCharCode(i >> 16 & 0xFF));
  336. };
  337. /**
  338. * Puts a 32-bit integer in this buffer in little-endian order.
  339. *
  340. * @param i the 32-bit integer.
  341. *
  342. * @return this buffer.
  343. */
  344. util.ByteStringBuffer.prototype.putInt32Le = function(i) {
  345. return this.putBytes(
  346. String.fromCharCode(i & 0xFF) +
  347. String.fromCharCode(i >> 8 & 0xFF) +
  348. String.fromCharCode(i >> 16 & 0xFF) +
  349. String.fromCharCode(i >> 24 & 0xFF));
  350. };
  351. /**
  352. * Puts an n-bit integer in this buffer in big-endian order.
  353. *
  354. * @param i the n-bit integer.
  355. * @param n the number of bits in the integer (8, 16, 24, or 32).
  356. *
  357. * @return this buffer.
  358. */
  359. util.ByteStringBuffer.prototype.putInt = function(i, n) {
  360. _checkBitsParam(n);
  361. var bytes = '';
  362. do {
  363. n -= 8;
  364. bytes += String.fromCharCode((i >> n) & 0xFF);
  365. } while(n > 0);
  366. return this.putBytes(bytes);
  367. };
  368. /**
  369. * Puts a signed n-bit integer in this buffer in big-endian order. Two's
  370. * complement representation is used.
  371. *
  372. * @param i the n-bit integer.
  373. * @param n the number of bits in the integer (8, 16, 24, or 32).
  374. *
  375. * @return this buffer.
  376. */
  377. util.ByteStringBuffer.prototype.putSignedInt = function(i, n) {
  378. // putInt checks n
  379. if(i < 0) {
  380. i += 2 << (n - 1);
  381. }
  382. return this.putInt(i, n);
  383. };
  384. /**
  385. * Puts the given buffer into this buffer.
  386. *
  387. * @param buffer the buffer to put into this one.
  388. *
  389. * @return this buffer.
  390. */
  391. util.ByteStringBuffer.prototype.putBuffer = function(buffer) {
  392. return this.putBytes(buffer.getBytes());
  393. };
  394. /**
  395. * Gets a byte from this buffer and advances the read pointer by 1.
  396. *
  397. * @return the byte.
  398. */
  399. util.ByteStringBuffer.prototype.getByte = function() {
  400. return this.data.charCodeAt(this.read++);
  401. };
  402. /**
  403. * Gets a uint16 from this buffer in big-endian order and advances the read
  404. * pointer by 2.
  405. *
  406. * @return the uint16.
  407. */
  408. util.ByteStringBuffer.prototype.getInt16 = function() {
  409. var rval = (
  410. this.data.charCodeAt(this.read) << 8 ^
  411. this.data.charCodeAt(this.read + 1));
  412. this.read += 2;
  413. return rval;
  414. };
  415. /**
  416. * Gets a uint24 from this buffer in big-endian order and advances the read
  417. * pointer by 3.
  418. *
  419. * @return the uint24.
  420. */
  421. util.ByteStringBuffer.prototype.getInt24 = function() {
  422. var rval = (
  423. this.data.charCodeAt(this.read) << 16 ^
  424. this.data.charCodeAt(this.read + 1) << 8 ^
  425. this.data.charCodeAt(this.read + 2));
  426. this.read += 3;
  427. return rval;
  428. };
  429. /**
  430. * Gets a uint32 from this buffer in big-endian order and advances the read
  431. * pointer by 4.
  432. *
  433. * @return the word.
  434. */
  435. util.ByteStringBuffer.prototype.getInt32 = function() {
  436. var rval = (
  437. this.data.charCodeAt(this.read) << 24 ^
  438. this.data.charCodeAt(this.read + 1) << 16 ^
  439. this.data.charCodeAt(this.read + 2) << 8 ^
  440. this.data.charCodeAt(this.read + 3));
  441. this.read += 4;
  442. return rval;
  443. };
  444. /**
  445. * Gets a uint16 from this buffer in little-endian order and advances the read
  446. * pointer by 2.
  447. *
  448. * @return the uint16.
  449. */
  450. util.ByteStringBuffer.prototype.getInt16Le = function() {
  451. var rval = (
  452. this.data.charCodeAt(this.read) ^
  453. this.data.charCodeAt(this.read + 1) << 8);
  454. this.read += 2;
  455. return rval;
  456. };
  457. /**
  458. * Gets a uint24 from this buffer in little-endian order and advances the read
  459. * pointer by 3.
  460. *
  461. * @return the uint24.
  462. */
  463. util.ByteStringBuffer.prototype.getInt24Le = function() {
  464. var rval = (
  465. this.data.charCodeAt(this.read) ^
  466. this.data.charCodeAt(this.read + 1) << 8 ^
  467. this.data.charCodeAt(this.read + 2) << 16);
  468. this.read += 3;
  469. return rval;
  470. };
  471. /**
  472. * Gets a uint32 from this buffer in little-endian order and advances the read
  473. * pointer by 4.
  474. *
  475. * @return the word.
  476. */
  477. util.ByteStringBuffer.prototype.getInt32Le = function() {
  478. var rval = (
  479. this.data.charCodeAt(this.read) ^
  480. this.data.charCodeAt(this.read + 1) << 8 ^
  481. this.data.charCodeAt(this.read + 2) << 16 ^
  482. this.data.charCodeAt(this.read + 3) << 24);
  483. this.read += 4;
  484. return rval;
  485. };
  486. /**
  487. * Gets an n-bit integer from this buffer in big-endian order and advances the
  488. * read pointer by ceil(n/8).
  489. *
  490. * @param n the number of bits in the integer (8, 16, 24, or 32).
  491. *
  492. * @return the integer.
  493. */
  494. util.ByteStringBuffer.prototype.getInt = function(n) {
  495. _checkBitsParam(n);
  496. var rval = 0;
  497. do {
  498. // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits.
  499. rval = (rval << 8) + this.data.charCodeAt(this.read++);
  500. n -= 8;
  501. } while(n > 0);
  502. return rval;
  503. };
  504. /**
  505. * Gets a signed n-bit integer from this buffer in big-endian order, using
  506. * two's complement, and advances the read pointer by n/8.
  507. *
  508. * @param n the number of bits in the integer (8, 16, 24, or 32).
  509. *
  510. * @return the integer.
  511. */
  512. util.ByteStringBuffer.prototype.getSignedInt = function(n) {
  513. // getInt checks n
  514. var x = this.getInt(n);
  515. var max = 2 << (n - 2);
  516. if(x >= max) {
  517. x -= max << 1;
  518. }
  519. return x;
  520. };
  521. /**
  522. * Reads bytes out as a binary encoded string and clears them from the
  523. * buffer. Note that the resulting string is binary encoded (in node.js this
  524. * encoding is referred to as `binary`, it is *not* `utf8`).
  525. *
  526. * @param count the number of bytes to read, undefined or null for all.
  527. *
  528. * @return a binary encoded string of bytes.
  529. */
  530. util.ByteStringBuffer.prototype.getBytes = function(count) {
  531. var rval;
  532. if(count) {
  533. // read count bytes
  534. count = Math.min(this.length(), count);
  535. rval = this.data.slice(this.read, this.read + count);
  536. this.read += count;
  537. } else if(count === 0) {
  538. rval = '';
  539. } else {
  540. // read all bytes, optimize to only copy when needed
  541. rval = (this.read === 0) ? this.data : this.data.slice(this.read);
  542. this.clear();
  543. }
  544. return rval;
  545. };
  546. /**
  547. * Gets a binary encoded string of the bytes from this buffer without
  548. * modifying the read pointer.
  549. *
  550. * @param count the number of bytes to get, omit to get all.
  551. *
  552. * @return a string full of binary encoded characters.
  553. */
  554. util.ByteStringBuffer.prototype.bytes = function(count) {
  555. return (typeof(count) === 'undefined' ?
  556. this.data.slice(this.read) :
  557. this.data.slice(this.read, this.read + count));
  558. };
  559. /**
  560. * Gets a byte at the given index without modifying the read pointer.
  561. *
  562. * @param i the byte index.
  563. *
  564. * @return the byte.
  565. */
  566. util.ByteStringBuffer.prototype.at = function(i) {
  567. return this.data.charCodeAt(this.read + i);
  568. };
  569. /**
  570. * Puts a byte at the given index without modifying the read pointer.
  571. *
  572. * @param i the byte index.
  573. * @param b the byte to put.
  574. *
  575. * @return this buffer.
  576. */
  577. util.ByteStringBuffer.prototype.setAt = function(i, b) {
  578. this.data = this.data.substr(0, this.read + i) +
  579. String.fromCharCode(b) +
  580. this.data.substr(this.read + i + 1);
  581. return this;
  582. };
  583. /**
  584. * Gets the last byte without modifying the read pointer.
  585. *
  586. * @return the last byte.
  587. */
  588. util.ByteStringBuffer.prototype.last = function() {
  589. return this.data.charCodeAt(this.data.length - 1);
  590. };
  591. /**
  592. * Creates a copy of this buffer.
  593. *
  594. * @return the copy.
  595. */
  596. util.ByteStringBuffer.prototype.copy = function() {
  597. var c = util.createBuffer(this.data);
  598. c.read = this.read;
  599. return c;
  600. };
  601. /**
  602. * Compacts this buffer.
  603. *
  604. * @return this buffer.
  605. */
  606. util.ByteStringBuffer.prototype.compact = function() {
  607. if(this.read > 0) {
  608. this.data = this.data.slice(this.read);
  609. this.read = 0;
  610. }
  611. return this;
  612. };
  613. /**
  614. * Clears this buffer.
  615. *
  616. * @return this buffer.
  617. */
  618. util.ByteStringBuffer.prototype.clear = function() {
  619. this.data = '';
  620. this.read = 0;
  621. return this;
  622. };
  623. /**
  624. * Shortens this buffer by triming bytes off of the end of this buffer.
  625. *
  626. * @param count the number of bytes to trim off.
  627. *
  628. * @return this buffer.
  629. */
  630. util.ByteStringBuffer.prototype.truncate = function(count) {
  631. var len = Math.max(0, this.length() - count);
  632. this.data = this.data.substr(this.read, len);
  633. this.read = 0;
  634. return this;
  635. };
  636. /**
  637. * Converts this buffer to a hexadecimal string.
  638. *
  639. * @return a hexadecimal string.
  640. */
  641. util.ByteStringBuffer.prototype.toHex = function() {
  642. var rval = '';
  643. for(var i = this.read; i < this.data.length; ++i) {
  644. var b = this.data.charCodeAt(i);
  645. if(b < 16) {
  646. rval += '0';
  647. }
  648. rval += b.toString(16);
  649. }
  650. return rval;
  651. };
  652. /**
  653. * Converts this buffer to a UTF-16 string (standard JavaScript string).
  654. *
  655. * @return a UTF-16 string.
  656. */
  657. util.ByteStringBuffer.prototype.toString = function() {
  658. return util.decodeUtf8(this.bytes());
  659. };
  660. /** End Buffer w/BinaryString backing */
  661. /** Buffer w/UInt8Array backing */
  662. /**
  663. * FIXME: Experimental. Do not use yet.
  664. *
  665. * Constructor for an ArrayBuffer-backed byte buffer.
  666. *
  667. * The buffer may be constructed from a string, an ArrayBuffer, DataView, or a
  668. * TypedArray.
  669. *
  670. * If a string is given, its encoding should be provided as an option,
  671. * otherwise it will default to 'binary'. A 'binary' string is encoded such
  672. * that each character is one byte in length and size.
  673. *
  674. * If an ArrayBuffer, DataView, or TypedArray is given, it will be used
  675. * *directly* without any copying. Note that, if a write to the buffer requires
  676. * more space, the buffer will allocate a new backing ArrayBuffer to
  677. * accommodate. The starting read and write offsets for the buffer may be
  678. * given as options.
  679. *
  680. * @param [b] the initial bytes for this buffer.
  681. * @param options the options to use:
  682. * [readOffset] the starting read offset to use (default: 0).
  683. * [writeOffset] the starting write offset to use (default: the
  684. * length of the first parameter).
  685. * [growSize] the minimum amount, in bytes, to grow the buffer by to
  686. * accommodate writes (default: 1024).
  687. * [encoding] the encoding ('binary', 'utf8', 'utf16', 'hex') for the
  688. * first parameter, if it is a string (default: 'binary').
  689. */
  690. function DataBuffer(b, options) {
  691. // default options
  692. options = options || {};
  693. // pointers for read from/write to buffer
  694. this.read = options.readOffset || 0;
  695. this.growSize = options.growSize || 1024;
  696. var isArrayBuffer = util.isArrayBuffer(b);
  697. var isArrayBufferView = util.isArrayBufferView(b);
  698. if(isArrayBuffer || isArrayBufferView) {
  699. // use ArrayBuffer directly
  700. if(isArrayBuffer) {
  701. this.data = new DataView(b);
  702. } else {
  703. // TODO: adjust read/write offset based on the type of view
  704. // or specify that this must be done in the options ... that the
  705. // offsets are byte-based
  706. this.data = new DataView(b.buffer, b.byteOffset, b.byteLength);
  707. }
  708. this.write = ('writeOffset' in options ?
  709. options.writeOffset : this.data.byteLength);
  710. return;
  711. }
  712. // initialize to empty array buffer and add any given bytes using putBytes
  713. this.data = new DataView(new ArrayBuffer(0));
  714. this.write = 0;
  715. if(b !== null && b !== undefined) {
  716. this.putBytes(b);
  717. }
  718. if('writeOffset' in options) {
  719. this.write = options.writeOffset;
  720. }
  721. }
  722. util.DataBuffer = DataBuffer;
  723. /**
  724. * Gets the number of bytes in this buffer.
  725. *
  726. * @return the number of bytes in this buffer.
  727. */
  728. util.DataBuffer.prototype.length = function() {
  729. return this.write - this.read;
  730. };
  731. /**
  732. * Gets whether or not this buffer is empty.
  733. *
  734. * @return true if this buffer is empty, false if not.
  735. */
  736. util.DataBuffer.prototype.isEmpty = function() {
  737. return this.length() <= 0;
  738. };
  739. /**
  740. * Ensures this buffer has enough empty space to accommodate the given number
  741. * of bytes. An optional parameter may be given that indicates a minimum
  742. * amount to grow the buffer if necessary. If the parameter is not given,
  743. * the buffer will be grown by some previously-specified default amount
  744. * or heuristic.
  745. *
  746. * @param amount the number of bytes to accommodate.
  747. * @param [growSize] the minimum amount, in bytes, to grow the buffer by if
  748. * necessary.
  749. */
  750. util.DataBuffer.prototype.accommodate = function(amount, growSize) {
  751. if(this.length() >= amount) {
  752. return this;
  753. }
  754. growSize = Math.max(growSize || this.growSize, amount);
  755. // grow buffer
  756. var src = new Uint8Array(
  757. this.data.buffer, this.data.byteOffset, this.data.byteLength);
  758. var dst = new Uint8Array(this.length() + growSize);
  759. dst.set(src);
  760. this.data = new DataView(dst.buffer);
  761. return this;
  762. };
  763. /**
  764. * Puts a byte in this buffer.
  765. *
  766. * @param b the byte to put.
  767. *
  768. * @return this buffer.
  769. */
  770. util.DataBuffer.prototype.putByte = function(b) {
  771. this.accommodate(1);
  772. this.data.setUint8(this.write++, b);
  773. return this;
  774. };
  775. /**
  776. * Puts a byte in this buffer N times.
  777. *
  778. * @param b the byte to put.
  779. * @param n the number of bytes of value b to put.
  780. *
  781. * @return this buffer.
  782. */
  783. util.DataBuffer.prototype.fillWithByte = function(b, n) {
  784. this.accommodate(n);
  785. for(var i = 0; i < n; ++i) {
  786. this.data.setUint8(b);
  787. }
  788. return this;
  789. };
  790. /**
  791. * Puts bytes in this buffer. The bytes may be given as a string, an
  792. * ArrayBuffer, a DataView, or a TypedArray.
  793. *
  794. * @param bytes the bytes to put.
  795. * @param [encoding] the encoding for the first parameter ('binary', 'utf8',
  796. * 'utf16', 'hex'), if it is a string (default: 'binary').
  797. *
  798. * @return this buffer.
  799. */
  800. util.DataBuffer.prototype.putBytes = function(bytes, encoding) {
  801. if(util.isArrayBufferView(bytes)) {
  802. var src = new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);
  803. var len = src.byteLength - src.byteOffset;
  804. this.accommodate(len);
  805. var dst = new Uint8Array(this.data.buffer, this.write);
  806. dst.set(src);
  807. this.write += len;
  808. return this;
  809. }
  810. if(util.isArrayBuffer(bytes)) {
  811. var src = new Uint8Array(bytes);
  812. this.accommodate(src.byteLength);
  813. var dst = new Uint8Array(this.data.buffer);
  814. dst.set(src, this.write);
  815. this.write += src.byteLength;
  816. return this;
  817. }
  818. // bytes is a util.DataBuffer or equivalent
  819. if(bytes instanceof util.DataBuffer ||
  820. (typeof bytes === 'object' &&
  821. typeof bytes.read === 'number' && typeof bytes.write === 'number' &&
  822. util.isArrayBufferView(bytes.data))) {
  823. var src = new Uint8Array(bytes.data.byteLength, bytes.read, bytes.length());
  824. this.accommodate(src.byteLength);
  825. var dst = new Uint8Array(bytes.data.byteLength, this.write);
  826. dst.set(src);
  827. this.write += src.byteLength;
  828. return this;
  829. }
  830. if(bytes instanceof util.ByteStringBuffer) {
  831. // copy binary string and process as the same as a string parameter below
  832. bytes = bytes.data;
  833. encoding = 'binary';
  834. }
  835. // string conversion
  836. encoding = encoding || 'binary';
  837. if(typeof bytes === 'string') {
  838. var view;
  839. // decode from string
  840. if(encoding === 'hex') {
  841. this.accommodate(Math.ceil(bytes.length / 2));
  842. view = new Uint8Array(this.data.buffer, this.write);
  843. this.write += util.binary.hex.decode(bytes, view, this.write);
  844. return this;
  845. }
  846. if(encoding === 'base64') {
  847. this.accommodate(Math.ceil(bytes.length / 4) * 3);
  848. view = new Uint8Array(this.data.buffer, this.write);
  849. this.write += util.binary.base64.decode(bytes, view, this.write);
  850. return this;
  851. }
  852. // encode text as UTF-8 bytes
  853. if(encoding === 'utf8') {
  854. // encode as UTF-8 then decode string as raw binary
  855. bytes = util.encodeUtf8(bytes);
  856. encoding = 'binary';
  857. }
  858. // decode string as raw binary
  859. if(encoding === 'binary' || encoding === 'raw') {
  860. // one byte per character
  861. this.accommodate(bytes.length);
  862. view = new Uint8Array(this.data.buffer, this.write);
  863. this.write += util.binary.raw.decode(view);
  864. return this;
  865. }
  866. // encode text as UTF-16 bytes
  867. if(encoding === 'utf16') {
  868. // two bytes per character
  869. this.accommodate(bytes.length * 2);
  870. view = new Uint16Array(this.data.buffer, this.write);
  871. this.write += util.text.utf16.encode(view);
  872. return this;
  873. }
  874. throw new Error('Invalid encoding: ' + encoding);
  875. }
  876. throw Error('Invalid parameter: ' + bytes);
  877. };
  878. /**
  879. * Puts the given buffer into this buffer.
  880. *
  881. * @param buffer the buffer to put into this one.
  882. *
  883. * @return this buffer.
  884. */
  885. util.DataBuffer.prototype.putBuffer = function(buffer) {
  886. this.putBytes(buffer);
  887. buffer.clear();
  888. return this;
  889. };
  890. /**
  891. * Puts a string into this buffer.
  892. *
  893. * @param str the string to put.
  894. * @param [encoding] the encoding for the string (default: 'utf16').
  895. *
  896. * @return this buffer.
  897. */
  898. util.DataBuffer.prototype.putString = function(str) {
  899. return this.putBytes(str, 'utf16');
  900. };
  901. /**
  902. * Puts a 16-bit integer in this buffer in big-endian order.
  903. *
  904. * @param i the 16-bit integer.
  905. *
  906. * @return this buffer.
  907. */
  908. util.DataBuffer.prototype.putInt16 = function(i) {
  909. this.accommodate(2);
  910. this.data.setInt16(this.write, i);
  911. this.write += 2;
  912. return this;
  913. };
  914. /**
  915. * Puts a 24-bit integer in this buffer in big-endian order.
  916. *
  917. * @param i the 24-bit integer.
  918. *
  919. * @return this buffer.
  920. */
  921. util.DataBuffer.prototype.putInt24 = function(i) {
  922. this.accommodate(3);
  923. this.data.setInt16(this.write, i >> 8 & 0xFFFF);
  924. this.data.setInt8(this.write, i >> 16 & 0xFF);
  925. this.write += 3;
  926. return this;
  927. };
  928. /**
  929. * Puts a 32-bit integer in this buffer in big-endian order.
  930. *
  931. * @param i the 32-bit integer.
  932. *
  933. * @return this buffer.
  934. */
  935. util.DataBuffer.prototype.putInt32 = function(i) {
  936. this.accommodate(4);
  937. this.data.setInt32(this.write, i);
  938. this.write += 4;
  939. return this;
  940. };
  941. /**
  942. * Puts a 16-bit integer in this buffer in little-endian order.
  943. *
  944. * @param i the 16-bit integer.
  945. *
  946. * @return this buffer.
  947. */
  948. util.DataBuffer.prototype.putInt16Le = function(i) {
  949. this.accommodate(2);
  950. this.data.setInt16(this.write, i, true);
  951. this.write += 2;
  952. return this;
  953. };
  954. /**
  955. * Puts a 24-bit integer in this buffer in little-endian order.
  956. *
  957. * @param i the 24-bit integer.
  958. *
  959. * @return this buffer.
  960. */
  961. util.DataBuffer.prototype.putInt24Le = function(i) {
  962. this.accommodate(3);
  963. this.data.setInt8(this.write, i >> 16 & 0xFF);
  964. this.data.setInt16(this.write, i >> 8 & 0xFFFF, true);
  965. this.write += 3;
  966. return this;
  967. };
  968. /**
  969. * Puts a 32-bit integer in this buffer in little-endian order.
  970. *
  971. * @param i the 32-bit integer.
  972. *
  973. * @return this buffer.
  974. */
  975. util.DataBuffer.prototype.putInt32Le = function(i) {
  976. this.accommodate(4);
  977. this.data.setInt32(this.write, i, true);
  978. this.write += 4;
  979. return this;
  980. };
  981. /**
  982. * Puts an n-bit integer in this buffer in big-endian order.
  983. *
  984. * @param i the n-bit integer.
  985. * @param n the number of bits in the integer (8, 16, 24, or 32).
  986. *
  987. * @return this buffer.
  988. */
  989. util.DataBuffer.prototype.putInt = function(i, n) {
  990. _checkBitsParam(n);
  991. this.accommodate(n / 8);
  992. do {
  993. n -= 8;
  994. this.data.setInt8(this.write++, (i >> n) & 0xFF);
  995. } while(n > 0);
  996. return this;
  997. };
  998. /**
  999. * Puts a signed n-bit integer in this buffer in big-endian order. Two's
  1000. * complement representation is used.
  1001. *
  1002. * @param i the n-bit integer.
  1003. * @param n the number of bits in the integer.
  1004. *
  1005. * @return this buffer.
  1006. */
  1007. util.DataBuffer.prototype.putSignedInt = function(i, n) {
  1008. _checkBitsParam(n);
  1009. this.accommodate(n / 8);
  1010. if(i < 0) {
  1011. i += 2 << (n - 1);
  1012. }
  1013. return this.putInt(i, n);
  1014. };
  1015. /**
  1016. * Gets a byte from this buffer and advances the read pointer by 1.
  1017. *
  1018. * @return the byte.
  1019. */
  1020. util.DataBuffer.prototype.getByte = function() {
  1021. return this.data.getInt8(this.read++);
  1022. };
  1023. /**
  1024. * Gets a uint16 from this buffer in big-endian order and advances the read
  1025. * pointer by 2.
  1026. *
  1027. * @return the uint16.
  1028. */
  1029. util.DataBuffer.prototype.getInt16 = function() {
  1030. var rval = this.data.getInt16(this.read);
  1031. this.read += 2;
  1032. return rval;
  1033. };
  1034. /**
  1035. * Gets a uint24 from this buffer in big-endian order and advances the read
  1036. * pointer by 3.
  1037. *
  1038. * @return the uint24.
  1039. */
  1040. util.DataBuffer.prototype.getInt24 = function() {
  1041. var rval = (
  1042. this.data.getInt16(this.read) << 8 ^
  1043. this.data.getInt8(this.read + 2));
  1044. this.read += 3;
  1045. return rval;
  1046. };
  1047. /**
  1048. * Gets a uint32 from this buffer in big-endian order and advances the read
  1049. * pointer by 4.
  1050. *
  1051. * @return the word.
  1052. */
  1053. util.DataBuffer.prototype.getInt32 = function() {
  1054. var rval = this.data.getInt32(this.read);
  1055. this.read += 4;
  1056. return rval;
  1057. };
  1058. /**
  1059. * Gets a uint16 from this buffer in little-endian order and advances the read
  1060. * pointer by 2.
  1061. *
  1062. * @return the uint16.
  1063. */
  1064. util.DataBuffer.prototype.getInt16Le = function() {
  1065. var rval = this.data.getInt16(this.read, true);
  1066. this.read += 2;
  1067. return rval;
  1068. };
  1069. /**
  1070. * Gets a uint24 from this buffer in little-endian order and advances the read
  1071. * pointer by 3.
  1072. *
  1073. * @return the uint24.
  1074. */
  1075. util.DataBuffer.prototype.getInt24Le = function() {
  1076. var rval = (
  1077. this.data.getInt8(this.read) ^
  1078. this.data.getInt16(this.read + 1, true) << 8);
  1079. this.read += 3;
  1080. return rval;
  1081. };
  1082. /**
  1083. * Gets a uint32 from this buffer in little-endian order and advances the read
  1084. * pointer by 4.
  1085. *
  1086. * @return the word.
  1087. */
  1088. util.DataBuffer.prototype.getInt32Le = function() {
  1089. var rval = this.data.getInt32(this.read, true);
  1090. this.read += 4;
  1091. return rval;
  1092. };
  1093. /**
  1094. * Gets an n-bit integer from this buffer in big-endian order and advances the
  1095. * read pointer by n/8.
  1096. *
  1097. * @param n the number of bits in the integer (8, 16, 24, or 32).
  1098. *
  1099. * @return the integer.
  1100. */
  1101. util.DataBuffer.prototype.getInt = function(n) {
  1102. _checkBitsParam(n);
  1103. var rval = 0;
  1104. do {
  1105. // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits.
  1106. rval = (rval << 8) + this.data.getInt8(this.read++);
  1107. n -= 8;
  1108. } while(n > 0);
  1109. return rval;
  1110. };
  1111. /**
  1112. * Gets a signed n-bit integer from this buffer in big-endian order, using
  1113. * two's complement, and advances the read pointer by n/8.
  1114. *
  1115. * @param n the number of bits in the integer (8, 16, 24, or 32).
  1116. *
  1117. * @return the integer.
  1118. */
  1119. util.DataBuffer.prototype.getSignedInt = function(n) {
  1120. // getInt checks n
  1121. var x = this.getInt(n);
  1122. var max = 2 << (n - 2);
  1123. if(x >= max) {
  1124. x -= max << 1;
  1125. }
  1126. return x;
  1127. };
  1128. /**
  1129. * Reads bytes out as a binary encoded string and clears them from the
  1130. * buffer.
  1131. *
  1132. * @param count the number of bytes to read, undefined or null for all.
  1133. *
  1134. * @return a binary encoded string of bytes.
  1135. */
  1136. util.DataBuffer.prototype.getBytes = function(count) {
  1137. // TODO: deprecate this method, it is poorly named and
  1138. // this.toString('binary') replaces it
  1139. // add a toTypedArray()/toArrayBuffer() function
  1140. var rval;
  1141. if(count) {
  1142. // read count bytes
  1143. count = Math.min(this.length(), count);
  1144. rval = this.data.slice(this.read, this.read + count);
  1145. this.read += count;
  1146. } else if(count === 0) {
  1147. rval = '';
  1148. } else {
  1149. // read all bytes, optimize to only copy when needed
  1150. rval = (this.read === 0) ? this.data : this.data.slice(this.read);
  1151. this.clear();
  1152. }
  1153. return rval;
  1154. };
  1155. /**
  1156. * Gets a binary encoded string of the bytes from this buffer without
  1157. * modifying the read pointer.
  1158. *
  1159. * @param count the number of bytes to get, omit to get all.
  1160. *
  1161. * @return a string full of binary encoded characters.
  1162. */
  1163. util.DataBuffer.prototype.bytes = function(count) {
  1164. // TODO: deprecate this method, it is poorly named, add "getString()"
  1165. return (typeof(count) === 'undefined' ?
  1166. this.data.slice(this.read) :
  1167. this.data.slice(this.read, this.read + count));
  1168. };
  1169. /**
  1170. * Gets a byte at the given index without modifying the read pointer.
  1171. *
  1172. * @param i the byte index.
  1173. *
  1174. * @return the byte.
  1175. */
  1176. util.DataBuffer.prototype.at = function(i) {
  1177. return this.data.getUint8(this.read + i);
  1178. };
  1179. /**
  1180. * Puts a byte at the given index without modifying the read pointer.
  1181. *
  1182. * @param i the byte index.
  1183. * @param b the byte to put.
  1184. *
  1185. * @return this buffer.
  1186. */
  1187. util.DataBuffer.prototype.setAt = function(i, b) {
  1188. this.data.setUint8(i, b);
  1189. return this;
  1190. };
  1191. /**
  1192. * Gets the last byte without modifying the read pointer.
  1193. *
  1194. * @return the last byte.
  1195. */
  1196. util.DataBuffer.prototype.last = function() {
  1197. return this.data.getUint8(this.write - 1);
  1198. };
  1199. /**
  1200. * Creates a copy of this buffer.
  1201. *
  1202. * @return the copy.
  1203. */
  1204. util.DataBuffer.prototype.copy = function() {
  1205. return new util.DataBuffer(this);
  1206. };
  1207. /**
  1208. * Compacts this buffer.
  1209. *
  1210. * @return this buffer.
  1211. */
  1212. util.DataBuffer.prototype.compact = function() {
  1213. if(this.read > 0) {
  1214. var src = new Uint8Array(this.data.buffer, this.read);
  1215. var dst = new Uint8Array(src.byteLength);
  1216. dst.set(src);
  1217. this.data = new DataView(dst);
  1218. this.write -= this.read;
  1219. this.read = 0;
  1220. }
  1221. return this;
  1222. };
  1223. /**
  1224. * Clears this buffer.
  1225. *
  1226. * @return this buffer.
  1227. */
  1228. util.DataBuffer.prototype.clear = function() {
  1229. this.data = new DataView(new ArrayBuffer(0));
  1230. this.read = this.write = 0;
  1231. return this;
  1232. };
  1233. /**
  1234. * Shortens this buffer by triming bytes off of the end of this buffer.
  1235. *
  1236. * @param count the number of bytes to trim off.
  1237. *
  1238. * @return this buffer.
  1239. */
  1240. util.DataBuffer.prototype.truncate = function(count) {
  1241. this.write = Math.max(0, this.length() - count);
  1242. this.read = Math.min(this.read, this.write);
  1243. return this;
  1244. };
  1245. /**
  1246. * Converts this buffer to a hexadecimal string.
  1247. *
  1248. * @return a hexadecimal string.
  1249. */
  1250. util.DataBuffer.prototype.toHex = function() {
  1251. var rval = '';
  1252. for(var i = this.read; i < this.data.byteLength; ++i) {
  1253. var b = this.data.getUint8(i);
  1254. if(b < 16) {
  1255. rval += '0';
  1256. }
  1257. rval += b.toString(16);
  1258. }
  1259. return rval;
  1260. };
  1261. /**
  1262. * Converts this buffer to a string, using the given encoding. If no
  1263. * encoding is given, 'utf8' (UTF-8) is used.
  1264. *
  1265. * @param [encoding] the encoding to use: 'binary', 'utf8', 'utf16', 'hex',
  1266. * 'base64' (default: 'utf8').
  1267. *
  1268. * @return a string representation of the bytes in this buffer.
  1269. */
  1270. util.DataBuffer.prototype.toString = function(encoding) {
  1271. var view = new Uint8Array(this.data, this.read, this.length());
  1272. encoding = encoding || 'utf8';
  1273. // encode to string
  1274. if(encoding === 'binary' || encoding === 'raw') {
  1275. return util.binary.raw.encode(view);
  1276. }
  1277. if(encoding === 'hex') {
  1278. return util.binary.hex.encode(view);
  1279. }
  1280. if(encoding === 'base64') {
  1281. return util.binary.base64.encode(view);
  1282. }
  1283. // decode to text
  1284. if(encoding === 'utf8') {
  1285. return util.text.utf8.decode(view);
  1286. }
  1287. if(encoding === 'utf16') {
  1288. return util.text.utf16.decode(view);
  1289. }
  1290. throw new Error('Invalid encoding: ' + encoding);
  1291. };
  1292. /** End Buffer w/UInt8Array backing */
  1293. /**
  1294. * Creates a buffer that stores bytes. A value may be given to populate the
  1295. * buffer with data. This value can either be string of encoded bytes or a
  1296. * regular string of characters. When passing a string of binary encoded
  1297. * bytes, the encoding `raw` should be given. This is also the default. When
  1298. * passing a string of characters, the encoding `utf8` should be given.
  1299. *
  1300. * @param [input] a string with encoded bytes to store in the buffer.
  1301. * @param [encoding] (default: 'raw', other: 'utf8').
  1302. */
  1303. util.createBuffer = function(input, encoding) {
  1304. // TODO: deprecate, use new ByteBuffer() instead
  1305. encoding = encoding || 'raw';
  1306. if(input !== undefined && encoding === 'utf8') {
  1307. input = util.encodeUtf8(input);
  1308. }
  1309. return new util.ByteBuffer(input);
  1310. };
  1311. /**
  1312. * Fills a string with a particular value. If you want the string to be a byte
  1313. * string, pass in String.fromCharCode(theByte).
  1314. *
  1315. * @param c the character to fill the string with, use String.fromCharCode
  1316. * to fill the string with a byte value.
  1317. * @param n the number of characters of value c to fill with.
  1318. *
  1319. * @return the filled string.
  1320. */
  1321. util.fillString = function(c, n) {
  1322. var s = '';
  1323. while(n > 0) {
  1324. if(n & 1) {
  1325. s += c;
  1326. }
  1327. n >>>= 1;
  1328. if(n > 0) {
  1329. c += c;
  1330. }
  1331. }
  1332. return s;
  1333. };
  1334. /**
  1335. * Performs a per byte XOR between two byte strings and returns the result as a
  1336. * string of bytes.
  1337. *
  1338. * @param s1 first string of bytes.
  1339. * @param s2 second string of bytes.
  1340. * @param n the number of bytes to XOR.
  1341. *
  1342. * @return the XOR'd result.
  1343. */
  1344. util.xorBytes = function(s1, s2, n) {
  1345. var s3 = '';
  1346. var b = '';
  1347. var t = '';
  1348. var i = 0;
  1349. var c = 0;
  1350. for(; n > 0; --n, ++i) {
  1351. b = s1.charCodeAt(i) ^ s2.charCodeAt(i);
  1352. if(c >= 10) {
  1353. s3 += t;
  1354. t = '';
  1355. c = 0;
  1356. }
  1357. t += String.fromCharCode(b);
  1358. ++c;
  1359. }
  1360. s3 += t;
  1361. return s3;
  1362. };
  1363. /**
  1364. * Converts a hex string into a 'binary' encoded string of bytes.
  1365. *
  1366. * @param hex the hexadecimal string to convert.
  1367. *
  1368. * @return the binary-encoded string of bytes.
  1369. */
  1370. util.hexToBytes = function(hex) {
  1371. // TODO: deprecate: "Deprecated. Use util.binary.hex.decode instead."
  1372. var rval = '';
  1373. var i = 0;
  1374. if(hex.length & 1 == 1) {
  1375. // odd number of characters, convert first character alone
  1376. i = 1;
  1377. rval += String.fromCharCode(parseInt(hex[0], 16));
  1378. }
  1379. // convert 2 characters (1 byte) at a time
  1380. for(; i < hex.length; i += 2) {
  1381. rval += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
  1382. }
  1383. return rval;
  1384. };
  1385. /**
  1386. * Converts a 'binary' encoded string of bytes to hex.
  1387. *
  1388. * @param bytes the byte string to convert.
  1389. *
  1390. * @return the string of hexadecimal characters.
  1391. */
  1392. util.bytesToHex = function(bytes) {
  1393. // TODO: deprecate: "Deprecated. Use util.binary.hex.encode instead."
  1394. return util.createBuffer(bytes).toHex();
  1395. };
  1396. /**
  1397. * Converts an 32-bit integer to 4-big-endian byte string.
  1398. *
  1399. * @param i the integer.
  1400. *
  1401. * @return the byte string.
  1402. */
  1403. util.int32ToBytes = function(i) {
  1404. return (
  1405. String.fromCharCode(i >> 24 & 0xFF) +
  1406. String.fromCharCode(i >> 16 & 0xFF) +
  1407. String.fromCharCode(i >> 8 & 0xFF) +
  1408. String.fromCharCode(i & 0xFF));
  1409. };
  1410. // base64 characters, reverse mapping
  1411. var _base64 =
  1412. 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  1413. var _base64Idx = [
  1414. /*43 -43 = 0*/
  1415. /*'+', 1, 2, 3,'/' */
  1416. 62, -1, -1, -1, 63,
  1417. /*'0','1','2','3','4','5','6','7','8','9' */
  1418. 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,
  1419. /*15, 16, 17,'=', 19, 20, 21 */
  1420. -1, -1, -1, 64, -1, -1, -1,
  1421. /*65 - 43 = 22*/
  1422. /*'A','B','C','D','E','F','G','H','I','J','K','L','M', */
  1423. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
  1424. /*'N','O','P','Q','R','S','T','U','V','W','X','Y','Z' */
  1425. 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
  1426. /*91 - 43 = 48 */
  1427. /*48, 49, 50, 51, 52, 53 */
  1428. -1, -1, -1, -1, -1, -1,
  1429. /*97 - 43 = 54*/
  1430. /*'a','b','c','d','e','f','g','h','i','j','k','l','m' */
  1431. 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
  1432. /*'n','o','p','q','r','s','t','u','v','w','x','y','z' */
  1433. 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51
  1434. ];
  1435. // base58 characters (Bitcoin alphabet)
  1436. var _base58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
  1437. /**
  1438. * Base64 encodes a 'binary' encoded string of bytes.
  1439. *
  1440. * @param input the binary encoded string of bytes to base64-encode.
  1441. * @param maxline the maximum number of encoded characters per line to use,
  1442. * defaults to none.
  1443. *
  1444. * @return the base64-encoded output.
  1445. */
  1446. util.encode64 = function(input, maxline) {
  1447. // TODO: deprecate: "Deprecated. Use util.binary.base64.encode instead."
  1448. var line = '';
  1449. var output = '';
  1450. var chr1, chr2, chr3;
  1451. var i = 0;
  1452. while(i < input.length) {
  1453. chr1 = input.charCodeAt(i++);
  1454. chr2 = input.charCodeAt(i++);
  1455. chr3 = input.charCodeAt(i++);
  1456. // encode 4 character group
  1457. line += _base64.charAt(chr1 >> 2);
  1458. line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4));
  1459. if(isNaN(chr2)) {
  1460. line += '==';
  1461. } else {
  1462. line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6));
  1463. line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63);
  1464. }
  1465. if(maxline && line.length > maxline) {
  1466. output += line.substr(0, maxline) + '\r\n';
  1467. line = line.substr(maxline);
  1468. }
  1469. }
  1470. output += line;
  1471. return output;
  1472. };
  1473. /**
  1474. * Base64 decodes a string into a 'binary' encoded string of bytes.
  1475. *
  1476. * @param input the base64-encoded input.
  1477. *
  1478. * @return the binary encoded string.
  1479. */
  1480. util.decode64 = function(input) {
  1481. // TODO: deprecate: "Deprecated. Use util.binary.base64.decode instead."
  1482. // remove all non-base64 characters
  1483. input = input.replace(/[^A-Za-z0-9\+\/\=]/g, '');
  1484. var output = '';
  1485. var enc1, enc2, enc3, enc4;
  1486. var i = 0;
  1487. while(i < input.length) {
  1488. enc1 = _base64Idx[input.charCodeAt(i++) - 43];
  1489. enc2 = _base64Idx[input.charCodeAt(i++) - 43];
  1490. enc3 = _base64Idx[input.charCodeAt(i++) - 43];
  1491. enc4 = _base64Idx[input.charCodeAt(i++) - 43];
  1492. output += String.fromCharCode((enc1 << 2) | (enc2 >> 4));
  1493. if(enc3 !== 64) {
  1494. // decoded at least 2 bytes
  1495. output += String.fromCharCode(((enc2 & 15) << 4) | (enc3 >> 2));
  1496. if(enc4 !== 64) {
  1497. // decoded 3 bytes
  1498. output += String.fromCharCode(((enc3 & 3) << 6) | enc4);
  1499. }
  1500. }
  1501. }
  1502. return output;
  1503. };
  1504. /**
  1505. * Encodes the given string of characters (a standard JavaScript
  1506. * string) as a binary encoded string where the bytes represent
  1507. * a UTF-8 encoded string of characters. Non-ASCII characters will be
  1508. * encoded as multiple bytes according to UTF-8.
  1509. *
  1510. * @param str a standard string of characters to encode.
  1511. *
  1512. * @return the binary encoded string.
  1513. */
  1514. util.encodeUtf8 = function(str) {
  1515. return unescape(encodeURIComponent(str));
  1516. };
  1517. /**
  1518. * Decodes a binary encoded string that contains bytes that
  1519. * represent a UTF-8 encoded string of characters -- into a
  1520. * string of characters (a standard JavaScript string).
  1521. *
  1522. * @param str the binary encoded string to decode.
  1523. *
  1524. * @return the resulting standard string of characters.
  1525. */
  1526. util.decodeUtf8 = function(str) {
  1527. return decodeURIComponent(escape(str));
  1528. };
  1529. // binary encoding/decoding tools
  1530. // FIXME: Experimental. Do not use yet.
  1531. util.binary = {
  1532. raw: {},
  1533. hex: {},
  1534. base64: {},
  1535. base58: {},
  1536. baseN : {
  1537. encode: baseN.encode,
  1538. decode: baseN.decode
  1539. }
  1540. };
  1541. /**
  1542. * Encodes a Uint8Array as a binary-encoded string. This encoding uses
  1543. * a value between 0 and 255 for each character.
  1544. *
  1545. * @param bytes the Uint8Array to encode.
  1546. *
  1547. * @return the binary-encoded string.
  1548. */
  1549. util.binary.raw.encode = function(bytes) {
  1550. return String.fromCharCode.apply(null, bytes);
  1551. };
  1552. /**
  1553. * Decodes a binary-encoded string to a Uint8Array. This encoding uses
  1554. * a value between 0 and 255 for each character.
  1555. *
  1556. * @param str the binary-encoded string to decode.
  1557. * @param [output] an optional Uint8Array to write the output to; if it
  1558. * is too small, an exception will be thrown.
  1559. * @param [offset] the start offset for writing to the output (default: 0).
  1560. *
  1561. * @return the Uint8Array or the number of bytes written if output was given.
  1562. */
  1563. util.binary.raw.decode = function(str, output, offset) {
  1564. var out = output;
  1565. if(!out) {
  1566. out = new Uint8Array(str.length);
  1567. }
  1568. offset = offset || 0;
  1569. var j = offset;
  1570. for(var i = 0; i < str.length; ++i) {
  1571. out[j++] = str.charCodeAt(i);
  1572. }
  1573. return output ? (j - offset) : out;
  1574. };
  1575. /**
  1576. * Encodes a 'binary' string, ArrayBuffer, DataView, TypedArray, or
  1577. * ByteBuffer as a string of hexadecimal characters.
  1578. *
  1579. * @param bytes the bytes to convert.
  1580. *
  1581. * @return the string of hexadecimal characters.
  1582. */
  1583. util.binary.hex.encode = util.bytesToHex;
  1584. /**
  1585. * Decodes a hex-encoded string to a Uint8Array.
  1586. *
  1587. * @param hex the hexadecimal string to convert.
  1588. * @param [output] an optional Uint8Array to write the output to; if it
  1589. * is too small, an exception will be thrown.
  1590. * @param [offset] the start offset for writing to the output (default: 0).
  1591. *
  1592. * @return the Uint8Array or the number of bytes written if output was given.
  1593. */
  1594. util.binary.hex.decode = function(hex, output, offset) {
  1595. var out = output;
  1596. if(!out) {
  1597. out = new Uint8Array(Math.ceil(hex.length / 2));
  1598. }
  1599. offset = offset || 0;
  1600. var i = 0, j = offset;
  1601. if(hex.length & 1) {
  1602. // odd number of characters, convert first character alone
  1603. i = 1;
  1604. out[j++] = parseInt(hex[0], 16);
  1605. }
  1606. // convert 2 characters (1 byte) at a time
  1607. for(; i < hex.length; i += 2) {
  1608. out[j++] = parseInt(hex.substr(i, 2), 16);
  1609. }
  1610. return output ? (j - offset) : out;
  1611. };
  1612. /**
  1613. * Base64-encodes a Uint8Array.
  1614. *
  1615. * @param input the Uint8Array to encode.
  1616. * @param maxline the maximum number of encoded characters per line to use,
  1617. * defaults to none.
  1618. *
  1619. * @return the base64-encoded output string.
  1620. */
  1621. util.binary.base64.encode = function(input, maxline) {
  1622. var line = '';
  1623. var output = '';
  1624. var chr1, chr2, chr3;
  1625. var i = 0;
  1626. while(i < input.byteLength) {
  1627. chr1 = input[i++];
  1628. chr2 = input[i++];
  1629. chr3 = input[i++];
  1630. // encode 4 character group
  1631. line += _base64.charAt(chr1 >> 2);
  1632. line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4));
  1633. if(isNaN(chr2)) {
  1634. line += '==';
  1635. } else {
  1636. line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6));
  1637. line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63);
  1638. }
  1639. if(maxline && line.length > maxline) {
  1640. output += line.substr(0, maxline) + '\r\n';
  1641. line = line.substr(maxline);
  1642. }
  1643. }
  1644. output += line;
  1645. return output;
  1646. };
  1647. /**
  1648. * Decodes a base64-encoded string to a Uint8Array.
  1649. *
  1650. * @param input the base64-encoded input string.
  1651. * @param [output] an optional Uint8Array to write the output to; if it
  1652. * is too small, an exception will be thrown.
  1653. * @param [offset] the start offset for writing to the output (default: 0).
  1654. *
  1655. * @return the Uint8Array or the number of bytes written if output was given.
  1656. */
  1657. util.binary.base64.decode = function(input, output, offset) {
  1658. var out = output;
  1659. if(!out) {
  1660. out = new Uint8Array(Math.ceil(input.length / 4) * 3);
  1661. }
  1662. // remove all non-base64 characters
  1663. input = input.replace(/[^A-Za-z0-9\+\/\=]/g, '');
  1664. offset = offset || 0;
  1665. var enc1, enc2, enc3, enc4;
  1666. var i = 0, j = offset;
  1667. while(i < input.length) {
  1668. enc1 = _base64Idx[input.charCodeAt(i++) - 43];
  1669. enc2 = _base64Idx[input.charCodeAt(i++) - 43];
  1670. enc3 = _base64Idx[input.charCodeAt(i++) - 43];
  1671. enc4 = _base64Idx[input.charCodeAt(i++) - 43];
  1672. out[j++] = (enc1 << 2) | (enc2 >> 4);
  1673. if(enc3 !== 64) {
  1674. // decoded at least 2 bytes
  1675. out[j++] = ((enc2 & 15) << 4) | (enc3 >> 2);
  1676. if(enc4 !== 64) {
  1677. // decoded 3 bytes
  1678. out[j++] = ((enc3 & 3) << 6) | enc4;
  1679. }
  1680. }
  1681. }
  1682. // make sure result is the exact decoded length
  1683. return output ? (j - offset) : out.subarray(0, j);
  1684. };
  1685. // add support for base58 encoding/decoding with Bitcoin alphabet
  1686. util.binary.base58.encode = function(input, maxline) {
  1687. return util.binary.baseN.encode(input, _base58, maxline);
  1688. };
  1689. util.binary.base58.decode = function(input, maxline) {
  1690. return util.binary.baseN.decode(input, _base58, maxline);
  1691. };
  1692. // text encoding/decoding tools
  1693. // FIXME: Experimental. Do not use yet.
  1694. util.text = {
  1695. utf8: {},
  1696. utf16: {}
  1697. };
  1698. /**
  1699. * Encodes the given string as UTF-8 in a Uint8Array.
  1700. *
  1701. * @param str the string to encode.
  1702. * @param [output] an optional Uint8Array to write the output to; if it
  1703. * is too small, an exception will be thrown.
  1704. * @param [offset] the start offset for writing to the output (default: 0).
  1705. *
  1706. * @return the Uint8Array or the number of bytes written if output was given.
  1707. */
  1708. util.text.utf8.encode = function(str, output, offset) {
  1709. str = util.encodeUtf8(str);
  1710. var out = output;
  1711. if(!out) {
  1712. out = new Uint8Array(str.length);
  1713. }
  1714. offset = offset || 0;
  1715. var j = offset;
  1716. for(var i = 0; i < str.length; ++i) {
  1717. out[j++] = str.charCodeAt(i);
  1718. }
  1719. return output ? (j - offset) : out;
  1720. };
  1721. /**
  1722. * Decodes the UTF-8 contents from a Uint8Array.
  1723. *
  1724. * @param bytes the Uint8Array to decode.
  1725. *
  1726. * @return the resulting string.
  1727. */
  1728. util.text.utf8.decode = function(bytes) {
  1729. return util.decodeUtf8(String.fromCharCode.apply(null, bytes));
  1730. };
  1731. /**
  1732. * Encodes the given string as UTF-16 in a Uint8Array.
  1733. *
  1734. * @param str the string to encode.
  1735. * @param [output] an optional Uint8Array to write the output to; if it
  1736. * is too small, an exception will be thrown.
  1737. * @param [offset] the start offset for writing to the output (default: 0).
  1738. *
  1739. * @return the Uint8Array or the number of bytes written if output was given.
  1740. */
  1741. util.text.utf16.encode = function(str, output, offset) {
  1742. var out = output;
  1743. if(!out) {
  1744. out = new Uint8Array(str.length * 2);
  1745. }
  1746. var view = new Uint16Array(out.buffer);
  1747. offset = offset || 0;
  1748. var j = offset;
  1749. var k = offset;
  1750. for(var i = 0; i < str.length; ++i) {
  1751. view[k++] = str.charCodeAt(i);
  1752. j += 2;
  1753. }
  1754. return output ? (j - offset) : out;
  1755. };
  1756. /**
  1757. * Decodes the UTF-16 contents from a Uint8Array.
  1758. *
  1759. * @param bytes the Uint8Array to decode.
  1760. *
  1761. * @return the resulting string.
  1762. */
  1763. util.text.utf16.decode = function(bytes) {
  1764. return String.fromCharCode.apply(null, new Uint16Array(bytes.buffer));
  1765. };
  1766. /**
  1767. * Deflates the given data using a flash interface.
  1768. *
  1769. * @param api the flash interface.
  1770. * @param bytes the data.
  1771. * @param raw true to return only raw deflate data, false to include zlib
  1772. * header and trailer.
  1773. *
  1774. * @return the deflated data as a string.
  1775. */
  1776. util.deflate = function(api, bytes, raw) {
  1777. bytes = util.decode64(api.deflate(util.encode64(bytes)).rval);
  1778. // strip zlib header and trailer if necessary
  1779. if(raw) {
  1780. // zlib header is 2 bytes (CMF,FLG) where FLG indicates that
  1781. // there is a 4-byte DICT (alder-32) block before the data if
  1782. // its 5th bit is set
  1783. var start = 2;
  1784. var flg = bytes.charCodeAt(1);
  1785. if(flg & 0x20) {
  1786. start = 6;
  1787. }
  1788. // zlib trailer is 4 bytes of adler-32
  1789. bytes = bytes.substring(start, bytes.length - 4);
  1790. }
  1791. return bytes;
  1792. };
  1793. /**
  1794. * Inflates the given data using a flash interface.
  1795. *
  1796. * @param api the flash interface.
  1797. * @param bytes the data.
  1798. * @param raw true if the incoming data has no zlib header or trailer and is
  1799. * raw DEFLATE data.
  1800. *
  1801. * @return the inflated data as a string, null on error.
  1802. */
  1803. util.inflate = function(api, bytes, raw) {
  1804. // TODO: add zlib header and trailer if necessary/possible
  1805. var rval = api.inflate(util.encode64(bytes)).rval;
  1806. return (rval === null) ? null : util.decode64(rval);
  1807. };
  1808. /**
  1809. * Sets a storage object.
  1810. *
  1811. * @param api the storage interface.
  1812. * @param id the storage ID to use.
  1813. * @param obj the storage object, null to remove.
  1814. */
  1815. var _setStorageObject = function(api, id, obj) {
  1816. if(!api) {
  1817. throw new Error('WebStorage not available.');
  1818. }
  1819. var rval;
  1820. if(obj === null) {
  1821. rval = api.removeItem(id);
  1822. } else {
  1823. // json-encode and base64-encode object
  1824. obj = util.encode64(JSON.stringify(obj));
  1825. rval = api.setItem(id, obj);
  1826. }
  1827. // handle potential flash error
  1828. if(typeof(rval) !== 'undefined' && rval.rval !== true) {
  1829. var error = new Error(rval.error.message);
  1830. error.id = rval.error.id;
  1831. error.name = rval.error.name;
  1832. throw error;
  1833. }
  1834. };
  1835. /**
  1836. * Gets a storage object.
  1837. *
  1838. * @param api the storage interface.
  1839. * @param id the storage ID to use.
  1840. *
  1841. * @return the storage object entry or null if none exists.
  1842. */
  1843. var _getStorageObject = function(api, id) {
  1844. if(!api) {
  1845. throw new Error('WebStorage not available.');
  1846. }
  1847. // get the existing entry
  1848. var rval = api.getItem(id);
  1849. /* Note: We check api.init because we can't do (api == localStorage)
  1850. on IE because of "Class doesn't support Automation" exception. Only
  1851. the flash api has an init method so this works too, but we need a
  1852. better solution in the future. */
  1853. // flash returns item wrapped in an object, handle special case
  1854. if(api.init) {
  1855. if(rval.rval === null) {
  1856. if(rval.error) {
  1857. var error = new Error(rval.error.message);
  1858. error.id = rval.error.id;
  1859. error.name = rval.error.name;
  1860. throw error;
  1861. }
  1862. // no error, but also no item
  1863. rval = null;
  1864. } else {
  1865. rval = rval.rval;
  1866. }
  1867. }
  1868. // handle decoding
  1869. if(rval !== null) {
  1870. // base64-decode and json-decode data
  1871. rval = JSON.parse(util.decode64(rval));
  1872. }
  1873. return rval;
  1874. };
  1875. /**
  1876. * Stores an item in local storage.
  1877. *
  1878. * @param api the storage interface.
  1879. * @param id the storage ID to use.
  1880. * @param key the key for the item.
  1881. * @param data the data for the item (any javascript object/primitive).
  1882. */
  1883. var _setItem = function(api, id, key, data) {
  1884. // get storage object
  1885. var obj = _getStorageObject(api, id);
  1886. if(obj === null) {
  1887. // create a new storage object
  1888. obj = {};
  1889. }
  1890. // update key
  1891. obj[key] = data;
  1892. // set storage object
  1893. _setStorageObject(api, id, obj);
  1894. };
  1895. /**
  1896. * Gets an item from local storage.
  1897. *
  1898. * @param api the storage interface.
  1899. * @param id the storage ID to use.
  1900. * @param key the key for the item.
  1901. *
  1902. * @return the item.
  1903. */
  1904. var _getItem = function(api, id, key) {
  1905. // get storage object
  1906. var rval = _getStorageObject(api, id);
  1907. if(rval !== null) {
  1908. // return data at key
  1909. rval = (key in rval) ? rval[key] : null;
  1910. }
  1911. return rval;
  1912. };
  1913. /**
  1914. * Removes an item from local storage.
  1915. *
  1916. * @param api the storage interface.
  1917. * @param id the storage ID to use.
  1918. * @param key the key for the item.
  1919. */
  1920. var _removeItem = function(api, id, key) {
  1921. // get storage object
  1922. var obj = _getStorageObject(api, id);
  1923. if(obj !== null && key in obj) {
  1924. // remove key
  1925. delete obj[key];
  1926. // see if entry has no keys remaining
  1927. var empty = true;
  1928. for(var prop in obj) {
  1929. empty = false;
  1930. break;
  1931. }
  1932. if(empty) {
  1933. // remove entry entirely if no keys are left
  1934. obj = null;
  1935. }
  1936. // set storage object
  1937. _setStorageObject(api, id, obj);
  1938. }
  1939. };
  1940. /**
  1941. * Clears the local disk storage identified by the given ID.
  1942. *
  1943. * @param api the storage interface.
  1944. * @param id the storage ID to use.
  1945. */
  1946. var _clearItems = function(api, id) {
  1947. _setStorageObject(api, id, null);
  1948. };
  1949. /**
  1950. * Calls a storage function.
  1951. *
  1952. * @param func the function to call.
  1953. * @param args the arguments for the function.
  1954. * @param location the location argument.
  1955. *
  1956. * @return the return value from the function.
  1957. */
  1958. var _callStorageFunction = function(func, args, location) {
  1959. var rval = null;
  1960. // default storage types
  1961. if(typeof(location) === 'undefined') {
  1962. location = ['web', 'flash'];
  1963. }
  1964. // apply storage types in order of preference
  1965. var type;
  1966. var done = false;
  1967. var exception = null;
  1968. for(var idx in location) {
  1969. type = location[idx];
  1970. try {
  1971. if(type === 'flash' || type === 'both') {
  1972. if(args[0] === null) {
  1973. throw new Error('Flash local storage not available.');
  1974. }
  1975. rval = func.apply(this, args);
  1976. done = (type === 'flash');
  1977. }
  1978. if(type === 'web' || type === 'both') {
  1979. args[0] = localStorage;
  1980. rval = func.apply(this, args);
  1981. done = true;
  1982. }
  1983. } catch(ex) {
  1984. exception = ex;
  1985. }
  1986. if(done) {
  1987. break;
  1988. }
  1989. }
  1990. if(!done) {
  1991. throw exception;
  1992. }
  1993. return rval;
  1994. };
  1995. /**
  1996. * Stores an item on local disk.
  1997. *
  1998. * The available types of local storage include 'flash', 'web', and 'both'.
  1999. *
  2000. * The type 'flash' refers to flash local storage (SharedObject). In order
  2001. * to use flash local storage, the 'api' parameter must be valid. The type
  2002. * 'web' refers to WebStorage, if supported by the browser. The type 'both'
  2003. * refers to storing using both 'flash' and 'web', not just one or the
  2004. * other.
  2005. *
  2006. * The location array should list the storage types to use in order of
  2007. * preference:
  2008. *
  2009. * ['flash']: flash only storage
  2010. * ['web']: web only storage
  2011. * ['both']: try to store in both
  2012. * ['flash','web']: store in flash first, but if not available, 'web'
  2013. * ['web','flash']: store in web first, but if not available, 'flash'
  2014. *
  2015. * The location array defaults to: ['web', 'flash']
  2016. *
  2017. * @param api the flash interface, null to use only WebStorage.
  2018. * @param id the storage ID to use.
  2019. * @param key the key for the item.
  2020. * @param data the data for the item (any javascript object/primitive).
  2021. * @param location an array with the preferred types of storage to use.
  2022. */
  2023. util.setItem = function(api, id, key, data, location) {
  2024. _callStorageFunction(_setItem, arguments, location);
  2025. };
  2026. /**
  2027. * Gets an item on local disk.
  2028. *
  2029. * Set setItem() for details on storage types.
  2030. *
  2031. * @param api the flash interface, null to use only WebStorage.
  2032. * @param id the storage ID to use.
  2033. * @param key the key for the item.
  2034. * @param location an array with the preferred types of storage to use.
  2035. *
  2036. * @return the item.
  2037. */
  2038. util.getItem = function(api, id, key, location) {
  2039. return _callStorageFunction(_getItem, arguments, location);
  2040. };
  2041. /**
  2042. * Removes an item on local disk.
  2043. *
  2044. * Set setItem() for details on storage types.
  2045. *
  2046. * @param api the flash interface.
  2047. * @param id the storage ID to use.
  2048. * @param key the key for the item.
  2049. * @param location an array with the preferred types of storage to use.
  2050. */
  2051. util.removeItem = function(api, id, key, location) {
  2052. _callStorageFunction(_removeItem, arguments, location);
  2053. };
  2054. /**
  2055. * Clears the local disk storage identified by the given ID.
  2056. *
  2057. * Set setItem() for details on storage types.
  2058. *
  2059. * @param api the flash interface if flash is available.
  2060. * @param id the storage ID to use.
  2061. * @param location an array with the preferred types of storage to use.
  2062. */
  2063. util.clearItems = function(api, id, location) {
  2064. _callStorageFunction(_clearItems, arguments, location);
  2065. };
  2066. /**
  2067. * Parses the scheme, host, and port from an http(s) url.
  2068. *
  2069. * @param str the url string.
  2070. *
  2071. * @return the parsed url object or null if the url is invalid.
  2072. */
  2073. util.parseUrl = function(str) {
  2074. // FIXME: this regex looks a bit broken
  2075. var regex = /^(https?):\/\/([^:&^\/]*):?(\d*)(.*)$/g;
  2076. regex.lastIndex = 0;
  2077. var m = regex.exec(str);
  2078. var url = (m === null) ? null : {
  2079. full: str,
  2080. scheme: m[1],
  2081. host: m[2],
  2082. port: m[3],
  2083. path: m[4]
  2084. };
  2085. if(url) {
  2086. url.fullHost = url.host;
  2087. if(url.port) {
  2088. if(url.port !== 80 && url.scheme === 'http') {
  2089. url.fullHost += ':' + url.port;
  2090. } else if(url.port !== 443 && url.scheme === 'https') {
  2091. url.fullHost += ':' + url.port;
  2092. }
  2093. } else if(url.scheme === 'http') {
  2094. url.port = 80;
  2095. } else if(url.scheme === 'https') {
  2096. url.port = 443;
  2097. }
  2098. url.full = url.scheme + '://' + url.fullHost;
  2099. }
  2100. return url;
  2101. };
  2102. /* Storage for query variables */
  2103. var _queryVariables = null;
  2104. /**
  2105. * Returns the window location query variables. Query is parsed on the first
  2106. * call and the same object is returned on subsequent calls. The mapping
  2107. * is from keys to an array of values. Parameters without values will have
  2108. * an object key set but no value added to the value array. Values are
  2109. * unescaped.
  2110. *
  2111. * ...?k1=v1&k2=v2:
  2112. * {
  2113. * "k1": ["v1"],
  2114. * "k2": ["v2"]
  2115. * }
  2116. *
  2117. * ...?k1=v1&k1=v2:
  2118. * {
  2119. * "k1": ["v1", "v2"]
  2120. * }
  2121. *
  2122. * ...?k1=v1&k2:
  2123. * {
  2124. * "k1": ["v1"],
  2125. * "k2": []
  2126. * }
  2127. *
  2128. * ...?k1=v1&k1:
  2129. * {
  2130. * "k1": ["v1"]
  2131. * }
  2132. *
  2133. * ...?k1&k1:
  2134. * {
  2135. * "k1": []
  2136. * }
  2137. *
  2138. * @param query the query string to parse (optional, default to cached
  2139. * results from parsing window location search query).
  2140. *
  2141. * @return object mapping keys to variables.
  2142. */
  2143. util.getQueryVariables = function(query) {
  2144. var parse = function(q) {
  2145. var rval = {};
  2146. var kvpairs = q.split('&');
  2147. for(var i = 0; i < kvpairs.length; i++) {
  2148. var pos = kvpairs[i].indexOf('=');
  2149. var key;
  2150. var val;
  2151. if(pos > 0) {
  2152. key = kvpairs[i].substring(0, pos);
  2153. val = kvpairs[i].substring(pos + 1);
  2154. } else {
  2155. key = kvpairs[i];
  2156. val = null;
  2157. }
  2158. if(!(key in rval)) {
  2159. rval[key] = [];
  2160. }
  2161. // disallow overriding object prototype keys
  2162. if(!(key in Object.prototype) && val !== null) {
  2163. rval[key].push(unescape(val));
  2164. }
  2165. }
  2166. return rval;
  2167. };
  2168. var rval;
  2169. if(typeof(query) === 'undefined') {
  2170. // set cached variables if needed
  2171. if(_queryVariables === null) {
  2172. if(typeof(window) !== 'undefined' && window.location && window.location.search) {
  2173. // parse window search query
  2174. _queryVariables = parse(window.location.search.substring(1));
  2175. } else {
  2176. // no query variables available
  2177. _queryVariables = {};
  2178. }
  2179. }
  2180. rval = _queryVariables;
  2181. } else {
  2182. // parse given query
  2183. rval = parse(query);
  2184. }
  2185. return rval;
  2186. };
  2187. /**
  2188. * Parses a fragment into a path and query. This method will take a URI
  2189. * fragment and break it up as if it were the main URI. For example:
  2190. * /bar/baz?a=1&b=2
  2191. * results in:
  2192. * {
  2193. * path: ["bar", "baz"],
  2194. * query: {"k1": ["v1"], "k2": ["v2"]}
  2195. * }
  2196. *
  2197. * @return object with a path array and query object.
  2198. */
  2199. util.parseFragment = function(fragment) {
  2200. // default to whole fragment
  2201. var fp = fragment;
  2202. var fq = '';
  2203. // split into path and query if possible at the first '?'
  2204. var pos = fragment.indexOf('?');
  2205. if(pos > 0) {
  2206. fp = fragment.substring(0, pos);
  2207. fq = fragment.substring(pos + 1);
  2208. }
  2209. // split path based on '/' and ignore first element if empty
  2210. var path = fp.split('/');
  2211. if(path.length > 0 && path[0] === '') {
  2212. path.shift();
  2213. }
  2214. // convert query into object
  2215. var query = (fq === '') ? {} : util.getQueryVariables(fq);
  2216. return {
  2217. pathString: fp,
  2218. queryString: fq,
  2219. path: path,
  2220. query: query
  2221. };
  2222. };
  2223. /**
  2224. * Makes a request out of a URI-like request string. This is intended to
  2225. * be used where a fragment id (after a URI '#') is parsed as a URI with
  2226. * path and query parts. The string should have a path beginning and
  2227. * delimited by '/' and optional query parameters following a '?'. The
  2228. * query should be a standard URL set of key value pairs delimited by
  2229. * '&'. For backwards compatibility the initial '/' on the path is not
  2230. * required. The request object has the following API, (fully described
  2231. * in the method code):
  2232. * {
  2233. * path: <the path string part>.
  2234. * query: <the query string part>,
  2235. * getPath(i): get part or all of the split path array,
  2236. * getQuery(k, i): get part or all of a query key array,
  2237. * getQueryLast(k, _default): get last element of a query key array.
  2238. * }
  2239. *
  2240. * @return object with request parameters.
  2241. */
  2242. util.makeRequest = function(reqString) {
  2243. var frag = util.parseFragment(reqString);
  2244. var req = {
  2245. // full path string
  2246. path: frag.pathString,
  2247. // full query string
  2248. query: frag.queryString,
  2249. /**
  2250. * Get path or element in path.
  2251. *
  2252. * @param i optional path index.
  2253. *
  2254. * @return path or part of path if i provided.
  2255. */
  2256. getPath: function(i) {
  2257. return (typeof(i) === 'undefined') ? frag.path : frag.path[i];
  2258. },
  2259. /**
  2260. * Get query, values for a key, or value for a key index.
  2261. *
  2262. * @param k optional query key.
  2263. * @param i optional query key index.
  2264. *
  2265. * @return query, values for a key, or value for a key index.
  2266. */
  2267. getQuery: function(k, i) {
  2268. var rval;
  2269. if(typeof(k) === 'undefined') {
  2270. rval = frag.query;
  2271. } else {
  2272. rval = frag.query[k];
  2273. if(rval && typeof(i) !== 'undefined') {
  2274. rval = rval[i];
  2275. }
  2276. }
  2277. return rval;
  2278. },
  2279. getQueryLast: function(k, _default) {
  2280. var rval;
  2281. var vals = req.getQuery(k);
  2282. if(vals) {
  2283. rval = vals[vals.length - 1];
  2284. } else {
  2285. rval = _default;
  2286. }
  2287. return rval;
  2288. }
  2289. };
  2290. return req;
  2291. };
  2292. /**
  2293. * Makes a URI out of a path, an object with query parameters, and a
  2294. * fragment. Uses jQuery.param() internally for query string creation.
  2295. * If the path is an array, it will be joined with '/'.
  2296. *
  2297. * @param path string path or array of strings.
  2298. * @param query object with query parameters. (optional)
  2299. * @param fragment fragment string. (optional)
  2300. *
  2301. * @return string object with request parameters.
  2302. */
  2303. util.makeLink = function(path, query, fragment) {
  2304. // join path parts if needed
  2305. path = jQuery.isArray(path) ? path.join('/') : path;
  2306. var qstr = jQuery.param(query || {});
  2307. fragment = fragment || '';
  2308. return path +
  2309. ((qstr.length > 0) ? ('?' + qstr) : '') +
  2310. ((fragment.length > 0) ? ('#' + fragment) : '');
  2311. };
  2312. /**
  2313. * Follows a path of keys deep into an object hierarchy and set a value.
  2314. * If a key does not exist or it's value is not an object, create an
  2315. * object in it's place. This can be destructive to a object tree if
  2316. * leaf nodes are given as non-final path keys.
  2317. * Used to avoid exceptions from missing parts of the path.
  2318. *
  2319. * @param object the starting object.
  2320. * @param keys an array of string keys.
  2321. * @param value the value to set.
  2322. */
  2323. util.setPath = function(object, keys, value) {
  2324. // need to start at an object
  2325. if(typeof(object) === 'object' && object !== null) {
  2326. var i = 0;
  2327. var len = keys.length;
  2328. while(i < len) {
  2329. var next = keys[i++];
  2330. if(i == len) {
  2331. // last
  2332. object[next] = value;
  2333. } else {
  2334. // more
  2335. var hasNext = (next in object);
  2336. if(!hasNext ||
  2337. (hasNext && typeof(object[next]) !== 'object') ||
  2338. (hasNext && object[next] === null)) {
  2339. object[next] = {};
  2340. }
  2341. object = object[next];
  2342. }
  2343. }
  2344. }
  2345. };
  2346. /**
  2347. * Follows a path of keys deep into an object hierarchy and return a value.
  2348. * If a key does not exist, create an object in it's place.
  2349. * Used to avoid exceptions from missing parts of the path.
  2350. *
  2351. * @param object the starting object.
  2352. * @param keys an array of string keys.
  2353. * @param _default value to return if path not found.
  2354. *
  2355. * @return the value at the path if found, else default if given, else
  2356. * undefined.
  2357. */
  2358. util.getPath = function(object, keys, _default) {
  2359. var i = 0;
  2360. var len = keys.length;
  2361. var hasNext = true;
  2362. while(hasNext && i < len &&
  2363. typeof(object) === 'object' && object !== null) {
  2364. var next = keys[i++];
  2365. hasNext = next in object;
  2366. if(hasNext) {
  2367. object = object[next];
  2368. }
  2369. }
  2370. return (hasNext ? object : _default);
  2371. };
  2372. /**
  2373. * Follow a path of keys deep into an object hierarchy and delete the
  2374. * last one. If a key does not exist, do nothing.
  2375. * Used to avoid exceptions from missing parts of the path.
  2376. *
  2377. * @param object the starting object.
  2378. * @param keys an array of string keys.
  2379. */
  2380. util.deletePath = function(object, keys) {
  2381. // need to start at an object
  2382. if(typeof(object) === 'object' && object !== null) {
  2383. var i = 0;
  2384. var len = keys.length;
  2385. while(i < len) {
  2386. var next = keys[i++];
  2387. if(i == len) {
  2388. // last
  2389. delete object[next];
  2390. } else {
  2391. // more
  2392. if(!(next in object) ||
  2393. (typeof(object[next]) !== 'object') ||
  2394. (object[next] === null)) {
  2395. break;
  2396. }
  2397. object = object[next];
  2398. }
  2399. }
  2400. }
  2401. };
  2402. /**
  2403. * Check if an object is empty.
  2404. *
  2405. * Taken from:
  2406. * http://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object-from-json/679937#679937
  2407. *
  2408. * @param object the object to check.
  2409. */
  2410. util.isEmpty = function(obj) {
  2411. for(var prop in obj) {
  2412. if(obj.hasOwnProperty(prop)) {
  2413. return false;
  2414. }
  2415. }
  2416. return true;
  2417. };
  2418. /**
  2419. * Format with simple printf-style interpolation.
  2420. *
  2421. * %%: literal '%'
  2422. * %s,%o: convert next argument into a string.
  2423. *
  2424. * @param format the string to format.
  2425. * @param ... arguments to interpolate into the format string.
  2426. */
  2427. util.format = function(format) {
  2428. var re = /%./g;
  2429. // current match
  2430. var match;
  2431. // current part
  2432. var part;
  2433. // current arg index
  2434. var argi = 0;
  2435. // collected parts to recombine later
  2436. var parts = [];
  2437. // last index found
  2438. var last = 0;
  2439. // loop while matches remain
  2440. while((match = re.exec(format))) {
  2441. part = format.substring(last, re.lastIndex - 2);
  2442. // don't add empty strings (ie, parts between %s%s)
  2443. if(part.length > 0) {
  2444. parts.push(part);
  2445. }
  2446. last = re.lastIndex;
  2447. // switch on % code
  2448. var code = match[0][1];
  2449. switch(code) {
  2450. case 's':
  2451. case 'o':
  2452. // check if enough arguments were given
  2453. if(argi < arguments.length) {
  2454. parts.push(arguments[argi++ + 1]);
  2455. } else {
  2456. parts.push('<?>');
  2457. }
  2458. break;
  2459. // FIXME: do proper formating for numbers, etc
  2460. //case 'f':
  2461. //case 'd':
  2462. case '%':
  2463. parts.push('%');
  2464. break;
  2465. default:
  2466. parts.push('<%' + code + '?>');
  2467. }
  2468. }
  2469. // add trailing part of format string
  2470. parts.push(format.substring(last));
  2471. return parts.join('');
  2472. };
  2473. /**
  2474. * Formats a number.
  2475. *
  2476. * http://snipplr.com/view/5945/javascript-numberformat--ported-from-php/
  2477. */
  2478. util.formatNumber = function(number, decimals, dec_point, thousands_sep) {
  2479. // http://kevin.vanzonneveld.net
  2480. // + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
  2481. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  2482. // + bugfix by: Michael White (http://crestidg.com)
  2483. // + bugfix by: Benjamin Lupton
  2484. // + bugfix by: Allan Jensen (http://www.winternet.no)
  2485. // + revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
  2486. // * example 1: number_format(1234.5678, 2, '.', '');
  2487. // * returns 1: 1234.57
  2488. var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
  2489. var d = dec_point === undefined ? ',' : dec_point;
  2490. var t = thousands_sep === undefined ?
  2491. '.' : thousands_sep, s = n < 0 ? '-' : '';
  2492. var i = parseInt((n = Math.abs(+n || 0).toFixed(c)), 10) + '';
  2493. var j = (i.length > 3) ? i.length % 3 : 0;
  2494. return s + (j ? i.substr(0, j) + t : '') +
  2495. i.substr(j).replace(/(\d{3})(?=\d)/g, '$1' + t) +
  2496. (c ? d + Math.abs(n - i).toFixed(c).slice(2) : '');
  2497. };
  2498. /**
  2499. * Formats a byte size.
  2500. *
  2501. * http://snipplr.com/view/5949/format-humanize-file-byte-size-presentation-in-javascript/
  2502. */
  2503. util.formatSize = function(size) {
  2504. if(size >= 1073741824) {
  2505. size = util.formatNumber(size / 1073741824, 2, '.', '') + ' GiB';
  2506. } else if(size >= 1048576) {
  2507. size = util.formatNumber(size / 1048576, 2, '.', '') + ' MiB';
  2508. } else if(size >= 1024) {
  2509. size = util.formatNumber(size / 1024, 0) + ' KiB';
  2510. } else {
  2511. size = util.formatNumber(size, 0) + ' bytes';
  2512. }
  2513. return size;
  2514. };
  2515. /**
  2516. * Converts an IPv4 or IPv6 string representation into bytes (in network order).
  2517. *
  2518. * @param ip the IPv4 or IPv6 address to convert.
  2519. *
  2520. * @return the 4-byte IPv6 or 16-byte IPv6 address or null if the address can't
  2521. * be parsed.
  2522. */
  2523. util.bytesFromIP = function(ip) {
  2524. if(ip.indexOf('.') !== -1) {
  2525. return util.bytesFromIPv4(ip);
  2526. }
  2527. if(ip.indexOf(':') !== -1) {
  2528. return util.bytesFromIPv6(ip);
  2529. }
  2530. return null;
  2531. };
  2532. /**
  2533. * Converts an IPv4 string representation into bytes (in network order).
  2534. *
  2535. * @param ip the IPv4 address to convert.
  2536. *
  2537. * @return the 4-byte address or null if the address can't be parsed.
  2538. */
  2539. util.bytesFromIPv4 = function(ip) {
  2540. ip = ip.split('.');
  2541. if(ip.length !== 4) {
  2542. return null;
  2543. }
  2544. var b = util.createBuffer();
  2545. for(var i = 0; i < ip.length; ++i) {
  2546. var num = parseInt(ip[i], 10);
  2547. if(isNaN(num)) {
  2548. return null;
  2549. }
  2550. b.putByte(num);
  2551. }
  2552. return b.getBytes();
  2553. };
  2554. /**
  2555. * Converts an IPv6 string representation into bytes (in network order).
  2556. *
  2557. * @param ip the IPv6 address to convert.
  2558. *
  2559. * @return the 16-byte address or null if the address can't be parsed.
  2560. */
  2561. util.bytesFromIPv6 = function(ip) {
  2562. var blanks = 0;
  2563. ip = ip.split(':').filter(function(e) {
  2564. if(e.length === 0) ++blanks;
  2565. return true;
  2566. });
  2567. var zeros = (8 - ip.length + blanks) * 2;
  2568. var b = util.createBuffer();
  2569. for(var i = 0; i < 8; ++i) {
  2570. if(!ip[i] || ip[i].length === 0) {
  2571. b.fillWithByte(0, zeros);
  2572. zeros = 0;
  2573. continue;
  2574. }
  2575. var bytes = util.hexToBytes(ip[i]);
  2576. if(bytes.length < 2) {
  2577. b.putByte(0);
  2578. }
  2579. b.putBytes(bytes);
  2580. }
  2581. return b.getBytes();
  2582. };
  2583. /**
  2584. * Converts 4-bytes into an IPv4 string representation or 16-bytes into
  2585. * an IPv6 string representation. The bytes must be in network order.
  2586. *
  2587. * @param bytes the bytes to convert.
  2588. *
  2589. * @return the IPv4 or IPv6 string representation if 4 or 16 bytes,
  2590. * respectively, are given, otherwise null.
  2591. */
  2592. util.bytesToIP = function(bytes) {
  2593. if(bytes.length === 4) {
  2594. return util.bytesToIPv4(bytes);
  2595. }
  2596. if(bytes.length === 16) {
  2597. return util.bytesToIPv6(bytes);
  2598. }
  2599. return null;
  2600. };
  2601. /**
  2602. * Converts 4-bytes into an IPv4 string representation. The bytes must be
  2603. * in network order.
  2604. *
  2605. * @param bytes the bytes to convert.
  2606. *
  2607. * @return the IPv4 string representation or null for an invalid # of bytes.
  2608. */
  2609. util.bytesToIPv4 = function(bytes) {
  2610. if(bytes.length !== 4) {
  2611. return null;
  2612. }
  2613. var ip = [];
  2614. for(var i = 0; i < bytes.length; ++i) {
  2615. ip.push(bytes.charCodeAt(i));
  2616. }
  2617. return ip.join('.');
  2618. };
  2619. /**
  2620. * Converts 16-bytes into an IPv16 string representation. The bytes must be
  2621. * in network order.
  2622. *
  2623. * @param bytes the bytes to convert.
  2624. *
  2625. * @return the IPv16 string representation or null for an invalid # of bytes.
  2626. */
  2627. util.bytesToIPv6 = function(bytes) {
  2628. if(bytes.length !== 16) {
  2629. return null;
  2630. }
  2631. var ip = [];
  2632. var zeroGroups = [];
  2633. var zeroMaxGroup = 0;
  2634. for(var i = 0; i < bytes.length; i += 2) {
  2635. var hex = util.bytesToHex(bytes[i] + bytes[i + 1]);
  2636. // canonicalize zero representation
  2637. while(hex[0] === '0' && hex !== '0') {
  2638. hex = hex.substr(1);
  2639. }
  2640. if(hex === '0') {
  2641. var last = zeroGroups[zeroGroups.length - 1];
  2642. var idx = ip.length;
  2643. if(!last || idx !== last.end + 1) {
  2644. zeroGroups.push({start: idx, end: idx});
  2645. } else {
  2646. last.end = idx;
  2647. if((last.end - last.start) >
  2648. (zeroGroups[zeroMaxGroup].end - zeroGroups[zeroMaxGroup].start)) {
  2649. zeroMaxGroup = zeroGroups.length - 1;
  2650. }
  2651. }
  2652. }
  2653. ip.push(hex);
  2654. }
  2655. if(zeroGroups.length > 0) {
  2656. var group = zeroGroups[zeroMaxGroup];
  2657. // only shorten group of length > 0
  2658. if(group.end - group.start > 0) {
  2659. ip.splice(group.start, group.end - group.start + 1, '');
  2660. if(group.start === 0) {
  2661. ip.unshift('');
  2662. }
  2663. if(group.end === 7) {
  2664. ip.push('');
  2665. }
  2666. }
  2667. }
  2668. return ip.join(':');
  2669. };
  2670. /**
  2671. * Estimates the number of processes that can be run concurrently. If
  2672. * creating Web Workers, keep in mind that the main JavaScript process needs
  2673. * its own core.
  2674. *
  2675. * @param options the options to use:
  2676. * update true to force an update (not use the cached value).
  2677. * @param callback(err, max) called once the operation completes.
  2678. */
  2679. util.estimateCores = function(options, callback) {
  2680. if(typeof options === 'function') {
  2681. callback = options;
  2682. options = {};
  2683. }
  2684. options = options || {};
  2685. if('cores' in util && !options.update) {
  2686. return callback(null, util.cores);
  2687. }
  2688. if(typeof navigator !== 'undefined' &&
  2689. 'hardwareConcurrency' in navigator &&
  2690. navigator.hardwareConcurrency > 0) {
  2691. util.cores = navigator.hardwareConcurrency;
  2692. return callback(null, util.cores);
  2693. }
  2694. if(typeof Worker === 'undefined') {
  2695. // workers not available
  2696. util.cores = 1;
  2697. return callback(null, util.cores);
  2698. }
  2699. if(typeof Blob === 'undefined') {
  2700. // can't estimate, default to 2
  2701. util.cores = 2;
  2702. return callback(null, util.cores);
  2703. }
  2704. // create worker concurrency estimation code as blob
  2705. var blobUrl = URL.createObjectURL(new Blob(['(',
  2706. function() {
  2707. self.addEventListener('message', function(e) {
  2708. // run worker for 4 ms
  2709. var st = Date.now();
  2710. var et = st + 4;
  2711. while(Date.now() < et);
  2712. self.postMessage({st: st, et: et});
  2713. });
  2714. }.toString(),
  2715. ')()'], {type: 'application/javascript'}));
  2716. // take 5 samples using 16 workers
  2717. sample([], 5, 16);
  2718. function sample(max, samples, numWorkers) {
  2719. if(samples === 0) {
  2720. // get overlap average
  2721. var avg = Math.floor(max.reduce(function(avg, x) {
  2722. return avg + x;
  2723. }, 0) / max.length);
  2724. util.cores = Math.max(1, avg);
  2725. URL.revokeObjectURL(blobUrl);
  2726. return callback(null, util.cores);
  2727. }
  2728. map(numWorkers, function(err, results) {
  2729. max.push(reduce(numWorkers, results));
  2730. sample(max, samples - 1, numWorkers);
  2731. });
  2732. }
  2733. function map(numWorkers, callback) {
  2734. var workers = [];
  2735. var results = [];
  2736. for(var i = 0; i < numWorkers; ++i) {
  2737. var worker = new Worker(blobUrl);
  2738. worker.addEventListener('message', function(e) {
  2739. results.push(e.data);
  2740. if(results.length === numWorkers) {
  2741. for(var i = 0; i < numWorkers; ++i) {
  2742. workers[i].terminate();
  2743. }
  2744. callback(null, results);
  2745. }
  2746. });
  2747. workers.push(worker);
  2748. }
  2749. for(var i = 0; i < numWorkers; ++i) {
  2750. workers[i].postMessage(i);
  2751. }
  2752. }
  2753. function reduce(numWorkers, results) {
  2754. // find overlapping time windows
  2755. var overlaps = [];
  2756. for(var n = 0; n < numWorkers; ++n) {
  2757. var r1 = results[n];
  2758. var overlap = overlaps[n] = [];
  2759. for(var i = 0; i < numWorkers; ++i) {
  2760. if(n === i) {
  2761. continue;
  2762. }
  2763. var r2 = results[i];
  2764. if((r1.st > r2.st && r1.st < r2.et) ||
  2765. (r2.st > r1.st && r2.st < r1.et)) {
  2766. overlap.push(i);
  2767. }
  2768. }
  2769. }
  2770. // get maximum overlaps ... don't include overlapping worker itself
  2771. // as the main JS process was also being scheduled during the work and
  2772. // would have to be subtracted from the estimate anyway
  2773. return overlaps.reduce(function(max, overlap) {
  2774. return Math.max(max, overlap.length);
  2775. }, 0);
  2776. }
  2777. };