util.js 77 KB

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