util.js 76 KB

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