util.js 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652
  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. * Check if an object is empty.
  2068. *
  2069. * Taken from:
  2070. * http://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object-from-json/679937#679937
  2071. *
  2072. * @param object the object to check.
  2073. */
  2074. util.isEmpty = function(obj) {
  2075. for(var prop in obj) {
  2076. if(obj.hasOwnProperty(prop)) {
  2077. return false;
  2078. }
  2079. }
  2080. return true;
  2081. };
  2082. /**
  2083. * Format with simple printf-style interpolation.
  2084. *
  2085. * %%: literal '%'
  2086. * %s,%o: convert next argument into a string.
  2087. *
  2088. * @param format the string to format.
  2089. * @param ... arguments to interpolate into the format string.
  2090. */
  2091. util.format = function(format) {
  2092. var re = /%./g;
  2093. // current match
  2094. var match;
  2095. // current part
  2096. var part;
  2097. // current arg index
  2098. var argi = 0;
  2099. // collected parts to recombine later
  2100. var parts = [];
  2101. // last index found
  2102. var last = 0;
  2103. // loop while matches remain
  2104. while((match = re.exec(format))) {
  2105. part = format.substring(last, re.lastIndex - 2);
  2106. // don't add empty strings (ie, parts between %s%s)
  2107. if(part.length > 0) {
  2108. parts.push(part);
  2109. }
  2110. last = re.lastIndex;
  2111. // switch on % code
  2112. var code = match[0][1];
  2113. switch(code) {
  2114. case 's':
  2115. case 'o':
  2116. // check if enough arguments were given
  2117. if(argi < arguments.length) {
  2118. parts.push(arguments[argi++ + 1]);
  2119. } else {
  2120. parts.push('<?>');
  2121. }
  2122. break;
  2123. // FIXME: do proper formating for numbers, etc
  2124. //case 'f':
  2125. //case 'd':
  2126. case '%':
  2127. parts.push('%');
  2128. break;
  2129. default:
  2130. parts.push('<%' + code + '?>');
  2131. }
  2132. }
  2133. // add trailing part of format string
  2134. parts.push(format.substring(last));
  2135. return parts.join('');
  2136. };
  2137. /**
  2138. * Formats a number.
  2139. *
  2140. * http://snipplr.com/view/5945/javascript-numberformat--ported-from-php/
  2141. */
  2142. util.formatNumber = function(number, decimals, dec_point, thousands_sep) {
  2143. // http://kevin.vanzonneveld.net
  2144. // + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
  2145. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  2146. // + bugfix by: Michael White (http://crestidg.com)
  2147. // + bugfix by: Benjamin Lupton
  2148. // + bugfix by: Allan Jensen (http://www.winternet.no)
  2149. // + revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
  2150. // * example 1: number_format(1234.5678, 2, '.', '');
  2151. // * returns 1: 1234.57
  2152. var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
  2153. var d = dec_point === undefined ? ',' : dec_point;
  2154. var t = thousands_sep === undefined ?
  2155. '.' : thousands_sep, s = n < 0 ? '-' : '';
  2156. var i = parseInt((n = Math.abs(+n || 0).toFixed(c)), 10) + '';
  2157. var j = (i.length > 3) ? i.length % 3 : 0;
  2158. return s + (j ? i.substr(0, j) + t : '') +
  2159. i.substr(j).replace(/(\d{3})(?=\d)/g, '$1' + t) +
  2160. (c ? d + Math.abs(n - i).toFixed(c).slice(2) : '');
  2161. };
  2162. /**
  2163. * Formats a byte size.
  2164. *
  2165. * http://snipplr.com/view/5949/format-humanize-file-byte-size-presentation-in-javascript/
  2166. */
  2167. util.formatSize = function(size) {
  2168. if(size >= 1073741824) {
  2169. size = util.formatNumber(size / 1073741824, 2, '.', '') + ' GiB';
  2170. } else if(size >= 1048576) {
  2171. size = util.formatNumber(size / 1048576, 2, '.', '') + ' MiB';
  2172. } else if(size >= 1024) {
  2173. size = util.formatNumber(size / 1024, 0) + ' KiB';
  2174. } else {
  2175. size = util.formatNumber(size, 0) + ' bytes';
  2176. }
  2177. return size;
  2178. };
  2179. /**
  2180. * Converts an IPv4 or IPv6 string representation into bytes (in network order).
  2181. *
  2182. * @param ip the IPv4 or IPv6 address to convert.
  2183. *
  2184. * @return the 4-byte IPv6 or 16-byte IPv6 address or null if the address can't
  2185. * be parsed.
  2186. */
  2187. util.bytesFromIP = function(ip) {
  2188. if(ip.indexOf('.') !== -1) {
  2189. return util.bytesFromIPv4(ip);
  2190. }
  2191. if(ip.indexOf(':') !== -1) {
  2192. return util.bytesFromIPv6(ip);
  2193. }
  2194. return null;
  2195. };
  2196. /**
  2197. * Converts an IPv4 string representation into bytes (in network order).
  2198. *
  2199. * @param ip the IPv4 address to convert.
  2200. *
  2201. * @return the 4-byte address or null if the address can't be parsed.
  2202. */
  2203. util.bytesFromIPv4 = function(ip) {
  2204. ip = ip.split('.');
  2205. if(ip.length !== 4) {
  2206. return null;
  2207. }
  2208. var b = util.createBuffer();
  2209. for(var i = 0; i < ip.length; ++i) {
  2210. var num = parseInt(ip[i], 10);
  2211. if(isNaN(num)) {
  2212. return null;
  2213. }
  2214. b.putByte(num);
  2215. }
  2216. return b.getBytes();
  2217. };
  2218. /**
  2219. * Converts an IPv6 string representation into bytes (in network order).
  2220. *
  2221. * @param ip the IPv6 address to convert.
  2222. *
  2223. * @return the 16-byte address or null if the address can't be parsed.
  2224. */
  2225. util.bytesFromIPv6 = function(ip) {
  2226. var blanks = 0;
  2227. ip = ip.split(':').filter(function(e) {
  2228. if(e.length === 0) ++blanks;
  2229. return true;
  2230. });
  2231. var zeros = (8 - ip.length + blanks) * 2;
  2232. var b = util.createBuffer();
  2233. for(var i = 0; i < 8; ++i) {
  2234. if(!ip[i] || ip[i].length === 0) {
  2235. b.fillWithByte(0, zeros);
  2236. zeros = 0;
  2237. continue;
  2238. }
  2239. var bytes = util.hexToBytes(ip[i]);
  2240. if(bytes.length < 2) {
  2241. b.putByte(0);
  2242. }
  2243. b.putBytes(bytes);
  2244. }
  2245. return b.getBytes();
  2246. };
  2247. /**
  2248. * Converts 4-bytes into an IPv4 string representation or 16-bytes into
  2249. * an IPv6 string representation. The bytes must be in network order.
  2250. *
  2251. * @param bytes the bytes to convert.
  2252. *
  2253. * @return the IPv4 or IPv6 string representation if 4 or 16 bytes,
  2254. * respectively, are given, otherwise null.
  2255. */
  2256. util.bytesToIP = function(bytes) {
  2257. if(bytes.length === 4) {
  2258. return util.bytesToIPv4(bytes);
  2259. }
  2260. if(bytes.length === 16) {
  2261. return util.bytesToIPv6(bytes);
  2262. }
  2263. return null;
  2264. };
  2265. /**
  2266. * Converts 4-bytes into an IPv4 string representation. The bytes must be
  2267. * in network order.
  2268. *
  2269. * @param bytes the bytes to convert.
  2270. *
  2271. * @return the IPv4 string representation or null for an invalid # of bytes.
  2272. */
  2273. util.bytesToIPv4 = function(bytes) {
  2274. if(bytes.length !== 4) {
  2275. return null;
  2276. }
  2277. var ip = [];
  2278. for(var i = 0; i < bytes.length; ++i) {
  2279. ip.push(bytes.charCodeAt(i));
  2280. }
  2281. return ip.join('.');
  2282. };
  2283. /**
  2284. * Converts 16-bytes into an IPv16 string representation. The bytes must be
  2285. * in network order.
  2286. *
  2287. * @param bytes the bytes to convert.
  2288. *
  2289. * @return the IPv16 string representation or null for an invalid # of bytes.
  2290. */
  2291. util.bytesToIPv6 = function(bytes) {
  2292. if(bytes.length !== 16) {
  2293. return null;
  2294. }
  2295. var ip = [];
  2296. var zeroGroups = [];
  2297. var zeroMaxGroup = 0;
  2298. for(var i = 0; i < bytes.length; i += 2) {
  2299. var hex = util.bytesToHex(bytes[i] + bytes[i + 1]);
  2300. // canonicalize zero representation
  2301. while(hex[0] === '0' && hex !== '0') {
  2302. hex = hex.substr(1);
  2303. }
  2304. if(hex === '0') {
  2305. var last = zeroGroups[zeroGroups.length - 1];
  2306. var idx = ip.length;
  2307. if(!last || idx !== last.end + 1) {
  2308. zeroGroups.push({start: idx, end: idx});
  2309. } else {
  2310. last.end = idx;
  2311. if((last.end - last.start) >
  2312. (zeroGroups[zeroMaxGroup].end - zeroGroups[zeroMaxGroup].start)) {
  2313. zeroMaxGroup = zeroGroups.length - 1;
  2314. }
  2315. }
  2316. }
  2317. ip.push(hex);
  2318. }
  2319. if(zeroGroups.length > 0) {
  2320. var group = zeroGroups[zeroMaxGroup];
  2321. // only shorten group of length > 0
  2322. if(group.end - group.start > 0) {
  2323. ip.splice(group.start, group.end - group.start + 1, '');
  2324. if(group.start === 0) {
  2325. ip.unshift('');
  2326. }
  2327. if(group.end === 7) {
  2328. ip.push('');
  2329. }
  2330. }
  2331. }
  2332. return ip.join(':');
  2333. };
  2334. /**
  2335. * Estimates the number of processes that can be run concurrently. If
  2336. * creating Web Workers, keep in mind that the main JavaScript process needs
  2337. * its own core.
  2338. *
  2339. * @param options the options to use:
  2340. * update true to force an update (not use the cached value).
  2341. * @param callback(err, max) called once the operation completes.
  2342. */
  2343. util.estimateCores = function(options, callback) {
  2344. if(typeof options === 'function') {
  2345. callback = options;
  2346. options = {};
  2347. }
  2348. options = options || {};
  2349. if('cores' in util && !options.update) {
  2350. return callback(null, util.cores);
  2351. }
  2352. if(typeof navigator !== 'undefined' &&
  2353. 'hardwareConcurrency' in navigator &&
  2354. navigator.hardwareConcurrency > 0) {
  2355. util.cores = navigator.hardwareConcurrency;
  2356. return callback(null, util.cores);
  2357. }
  2358. if(typeof Worker === 'undefined') {
  2359. // workers not available
  2360. util.cores = 1;
  2361. return callback(null, util.cores);
  2362. }
  2363. if(typeof Blob === 'undefined') {
  2364. // can't estimate, default to 2
  2365. util.cores = 2;
  2366. return callback(null, util.cores);
  2367. }
  2368. // create worker concurrency estimation code as blob
  2369. var blobUrl = URL.createObjectURL(new Blob(['(',
  2370. function() {
  2371. self.addEventListener('message', function(e) {
  2372. // run worker for 4 ms
  2373. var st = Date.now();
  2374. var et = st + 4;
  2375. while(Date.now() < et);
  2376. self.postMessage({st: st, et: et});
  2377. });
  2378. }.toString(),
  2379. ')()'], {type: 'application/javascript'}));
  2380. // take 5 samples using 16 workers
  2381. sample([], 5, 16);
  2382. function sample(max, samples, numWorkers) {
  2383. if(samples === 0) {
  2384. // get overlap average
  2385. var avg = Math.floor(max.reduce(function(avg, x) {
  2386. return avg + x;
  2387. }, 0) / max.length);
  2388. util.cores = Math.max(1, avg);
  2389. URL.revokeObjectURL(blobUrl);
  2390. return callback(null, util.cores);
  2391. }
  2392. map(numWorkers, function(err, results) {
  2393. max.push(reduce(numWorkers, results));
  2394. sample(max, samples - 1, numWorkers);
  2395. });
  2396. }
  2397. function map(numWorkers, callback) {
  2398. var workers = [];
  2399. var results = [];
  2400. for(var i = 0; i < numWorkers; ++i) {
  2401. var worker = new Worker(blobUrl);
  2402. worker.addEventListener('message', function(e) {
  2403. results.push(e.data);
  2404. if(results.length === numWorkers) {
  2405. for(var i = 0; i < numWorkers; ++i) {
  2406. workers[i].terminate();
  2407. }
  2408. callback(null, results);
  2409. }
  2410. });
  2411. workers.push(worker);
  2412. }
  2413. for(var i = 0; i < numWorkers; ++i) {
  2414. workers[i].postMessage(i);
  2415. }
  2416. }
  2417. function reduce(numWorkers, results) {
  2418. // find overlapping time windows
  2419. var overlaps = [];
  2420. for(var n = 0; n < numWorkers; ++n) {
  2421. var r1 = results[n];
  2422. var overlap = overlaps[n] = [];
  2423. for(var i = 0; i < numWorkers; ++i) {
  2424. if(n === i) {
  2425. continue;
  2426. }
  2427. var r2 = results[i];
  2428. if((r1.st > r2.st && r1.st < r2.et) ||
  2429. (r2.st > r1.st && r2.st < r1.et)) {
  2430. overlap.push(i);
  2431. }
  2432. }
  2433. }
  2434. // get maximum overlaps ... don't include overlapping worker itself
  2435. // as the main JS process was also being scheduled during the work and
  2436. // would have to be subtracted from the estimate anyway
  2437. return overlaps.reduce(function(max, overlap) {
  2438. return Math.max(max, overlap.length);
  2439. }, 0);
  2440. }
  2441. };