binaryjs.html 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345
  1. <script>
  2. /*! binary.js build:0.2.2, development. Copyright(c) 2012 Eric Zhang <eric@ericzhang.com> MIT Licensed */
  3. (function(exports){
  4. /*! binarypack.js build:0.0.9, production. Copyright(c) 2012 Eric Zhang <eric@ericzhang.com> MIT Licensed */(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  5. var BufferBuilder = require('./bufferbuilder').BufferBuilder;
  6. var binaryFeatures = require('./bufferbuilder').binaryFeatures;
  7. var BinaryPack = {
  8. unpack: function(data){
  9. var unpacker = new Unpacker(data);
  10. return unpacker.unpack();
  11. },
  12. pack: function(data){
  13. var packer = new Packer();
  14. packer.pack(data);
  15. var buffer = packer.getBuffer();
  16. return buffer;
  17. }
  18. };
  19. module.exports = BinaryPack;
  20. function Unpacker (data){
  21. // Data is ArrayBuffer
  22. this.index = 0;
  23. this.dataBuffer = data;
  24. this.dataView = new Uint8Array(this.dataBuffer);
  25. this.length = this.dataBuffer.byteLength;
  26. }
  27. Unpacker.prototype.unpack = function(){
  28. var type = this.unpack_uint8();
  29. if (type < 0x80){
  30. var positive_fixnum = type;
  31. return positive_fixnum;
  32. } else if ((type ^ 0xe0) < 0x20){
  33. var negative_fixnum = (type ^ 0xe0) - 0x20;
  34. return negative_fixnum;
  35. }
  36. var size;
  37. if ((size = type ^ 0xa0) <= 0x0f){
  38. return this.unpack_raw(size);
  39. } else if ((size = type ^ 0xb0) <= 0x0f){
  40. return this.unpack_string(size);
  41. } else if ((size = type ^ 0x90) <= 0x0f){
  42. return this.unpack_array(size);
  43. } else if ((size = type ^ 0x80) <= 0x0f){
  44. return this.unpack_map(size);
  45. }
  46. switch(type){
  47. case 0xc0:
  48. return null;
  49. case 0xc1:
  50. return undefined;
  51. case 0xc2:
  52. return false;
  53. case 0xc3:
  54. return true;
  55. case 0xca:
  56. return this.unpack_float();
  57. case 0xcb:
  58. return this.unpack_double();
  59. case 0xcc:
  60. return this.unpack_uint8();
  61. case 0xcd:
  62. return this.unpack_uint16();
  63. case 0xce:
  64. return this.unpack_uint32();
  65. case 0xcf:
  66. return this.unpack_uint64();
  67. case 0xd0:
  68. return this.unpack_int8();
  69. case 0xd1:
  70. return this.unpack_int16();
  71. case 0xd2:
  72. return this.unpack_int32();
  73. case 0xd3:
  74. return this.unpack_int64();
  75. case 0xd4:
  76. return undefined;
  77. case 0xd5:
  78. return undefined;
  79. case 0xd6:
  80. return undefined;
  81. case 0xd7:
  82. return undefined;
  83. case 0xd8:
  84. size = this.unpack_uint16();
  85. return this.unpack_string(size);
  86. case 0xd9:
  87. size = this.unpack_uint32();
  88. return this.unpack_string(size);
  89. case 0xda:
  90. size = this.unpack_uint16();
  91. return this.unpack_raw(size);
  92. case 0xdb:
  93. size = this.unpack_uint32();
  94. return this.unpack_raw(size);
  95. case 0xdc:
  96. size = this.unpack_uint16();
  97. return this.unpack_array(size);
  98. case 0xdd:
  99. size = this.unpack_uint32();
  100. return this.unpack_array(size);
  101. case 0xde:
  102. size = this.unpack_uint16();
  103. return this.unpack_map(size);
  104. case 0xdf:
  105. size = this.unpack_uint32();
  106. return this.unpack_map(size);
  107. }
  108. }
  109. Unpacker.prototype.unpack_uint8 = function(){
  110. var byte = this.dataView[this.index] & 0xff;
  111. this.index++;
  112. return byte;
  113. };
  114. Unpacker.prototype.unpack_uint16 = function(){
  115. var bytes = this.read(2);
  116. var uint16 =
  117. ((bytes[0] & 0xff) * 256) + (bytes[1] & 0xff);
  118. this.index += 2;
  119. return uint16;
  120. }
  121. Unpacker.prototype.unpack_uint32 = function(){
  122. var bytes = this.read(4);
  123. var uint32 =
  124. ((bytes[0] * 256 +
  125. bytes[1]) * 256 +
  126. bytes[2]) * 256 +
  127. bytes[3];
  128. this.index += 4;
  129. return uint32;
  130. }
  131. Unpacker.prototype.unpack_uint64 = function(){
  132. var bytes = this.read(8);
  133. var uint64 =
  134. ((((((bytes[0] * 256 +
  135. bytes[1]) * 256 +
  136. bytes[2]) * 256 +
  137. bytes[3]) * 256 +
  138. bytes[4]) * 256 +
  139. bytes[5]) * 256 +
  140. bytes[6]) * 256 +
  141. bytes[7];
  142. this.index += 8;
  143. return uint64;
  144. }
  145. Unpacker.prototype.unpack_int8 = function(){
  146. var uint8 = this.unpack_uint8();
  147. return (uint8 < 0x80 ) ? uint8 : uint8 - (1 << 8);
  148. };
  149. Unpacker.prototype.unpack_int16 = function(){
  150. var uint16 = this.unpack_uint16();
  151. return (uint16 < 0x8000 ) ? uint16 : uint16 - (1 << 16);
  152. }
  153. Unpacker.prototype.unpack_int32 = function(){
  154. var uint32 = this.unpack_uint32();
  155. return (uint32 < Math.pow(2, 31) ) ? uint32 :
  156. uint32 - Math.pow(2, 32);
  157. }
  158. Unpacker.prototype.unpack_int64 = function(){
  159. var uint64 = this.unpack_uint64();
  160. return (uint64 < Math.pow(2, 63) ) ? uint64 :
  161. uint64 - Math.pow(2, 64);
  162. }
  163. Unpacker.prototype.unpack_raw = function(size){
  164. if ( this.length < this.index + size){
  165. throw new Error('BinaryPackFailure: index is out of range'
  166. + ' ' + this.index + ' ' + size + ' ' + this.length);
  167. }
  168. var buf = this.dataBuffer.slice(this.index, this.index + size);
  169. this.index += size;
  170. //buf = util.bufferToString(buf);
  171. return buf;
  172. }
  173. Unpacker.prototype.unpack_string = function(size){
  174. var bytes = this.read(size);
  175. var i = 0, str = '', c, code;
  176. while(i < size){
  177. c = bytes[i];
  178. if ( c < 128){
  179. str += String.fromCharCode(c);
  180. i++;
  181. } else if ((c ^ 0xc0) < 32){
  182. code = ((c ^ 0xc0) << 6) | (bytes[i+1] & 63);
  183. str += String.fromCharCode(code);
  184. i += 2;
  185. } else {
  186. code = ((c & 15) << 12) | ((bytes[i+1] & 63) << 6) |
  187. (bytes[i+2] & 63);
  188. str += String.fromCharCode(code);
  189. i += 3;
  190. }
  191. }
  192. this.index += size;
  193. return str;
  194. }
  195. Unpacker.prototype.unpack_array = function(size){
  196. var objects = new Array(size);
  197. for(var i = 0; i < size ; i++){
  198. objects[i] = this.unpack();
  199. }
  200. return objects;
  201. }
  202. Unpacker.prototype.unpack_map = function(size){
  203. var map = {};
  204. for(var i = 0; i < size ; i++){
  205. var key = this.unpack();
  206. var value = this.unpack();
  207. map[key] = value;
  208. }
  209. return map;
  210. }
  211. Unpacker.prototype.unpack_float = function(){
  212. var uint32 = this.unpack_uint32();
  213. var sign = uint32 >> 31;
  214. var exp = ((uint32 >> 23) & 0xff) - 127;
  215. var fraction = ( uint32 & 0x7fffff ) | 0x800000;
  216. return (sign == 0 ? 1 : -1) *
  217. fraction * Math.pow(2, exp - 23);
  218. }
  219. Unpacker.prototype.unpack_double = function(){
  220. var h32 = this.unpack_uint32();
  221. var l32 = this.unpack_uint32();
  222. var sign = h32 >> 31;
  223. var exp = ((h32 >> 20) & 0x7ff) - 1023;
  224. var hfrac = ( h32 & 0xfffff ) | 0x100000;
  225. var frac = hfrac * Math.pow(2, exp - 20) +
  226. l32 * Math.pow(2, exp - 52);
  227. return (sign == 0 ? 1 : -1) * frac;
  228. }
  229. Unpacker.prototype.read = function(length){
  230. var j = this.index;
  231. if (j + length <= this.length) {
  232. return this.dataView.subarray(j, j + length);
  233. } else {
  234. throw new Error('BinaryPackFailure: read index out of range');
  235. }
  236. }
  237. function Packer(){
  238. this.bufferBuilder = new BufferBuilder();
  239. }
  240. Packer.prototype.getBuffer = function(){
  241. return this.bufferBuilder.getBuffer();
  242. }
  243. Packer.prototype.pack = function(value){
  244. var type = typeof(value);
  245. if (type == 'string'){
  246. this.pack_string(value);
  247. } else if (type == 'number'){
  248. if (Math.floor(value) === value){
  249. this.pack_integer(value);
  250. } else{
  251. this.pack_double(value);
  252. }
  253. } else if (type == 'boolean'){
  254. if (value === true){
  255. this.bufferBuilder.append(0xc3);
  256. } else if (value === false){
  257. this.bufferBuilder.append(0xc2);
  258. }
  259. } else if (type == 'undefined'){
  260. this.bufferBuilder.append(0xc0);
  261. } else if (type == 'object'){
  262. if (value === null){
  263. this.bufferBuilder.append(0xc0);
  264. } else {
  265. var constructor = value.constructor;
  266. if (constructor == Array){
  267. this.pack_array(value);
  268. } else if (constructor == Blob || constructor == File) {
  269. this.pack_bin(value);
  270. } else if (constructor == ArrayBuffer) {
  271. if(binaryFeatures.useArrayBufferView) {
  272. this.pack_bin(new Uint8Array(value));
  273. } else {
  274. this.pack_bin(value);
  275. }
  276. } else if ('BYTES_PER_ELEMENT' in value){
  277. if(binaryFeatures.useArrayBufferView) {
  278. this.pack_bin(new Uint8Array(value.buffer));
  279. } else {
  280. this.pack_bin(value.buffer);
  281. }
  282. } else if (constructor == Object){
  283. this.pack_object(value);
  284. } else if (constructor == Date){
  285. this.pack_string(value.toString());
  286. } else if (typeof value.toBinaryPack == 'function'){
  287. this.bufferBuilder.append(value.toBinaryPack());
  288. } else {
  289. throw new Error('Type "' + constructor.toString() + '" not yet supported');
  290. }
  291. }
  292. } else {
  293. throw new Error('Type "' + type + '" not yet supported');
  294. }
  295. this.bufferBuilder.flush();
  296. }
  297. Packer.prototype.pack_bin = function(blob){
  298. var length = blob.length || blob.byteLength || blob.size;
  299. if (length <= 0x0f){
  300. this.pack_uint8(0xa0 + length);
  301. } else if (length <= 0xffff){
  302. this.bufferBuilder.append(0xda) ;
  303. this.pack_uint16(length);
  304. } else if (length <= 0xffffffff){
  305. this.bufferBuilder.append(0xdb);
  306. this.pack_uint32(length);
  307. } else{
  308. throw new Error('Invalid length');
  309. }
  310. this.bufferBuilder.append(blob);
  311. }
  312. Packer.prototype.pack_string = function(str){
  313. var length = utf8Length(str);
  314. if (length <= 0x0f){
  315. this.pack_uint8(0xb0 + length);
  316. } else if (length <= 0xffff){
  317. this.bufferBuilder.append(0xd8) ;
  318. this.pack_uint16(length);
  319. } else if (length <= 0xffffffff){
  320. this.bufferBuilder.append(0xd9);
  321. this.pack_uint32(length);
  322. } else{
  323. throw new Error('Invalid length');
  324. }
  325. this.bufferBuilder.append(str);
  326. }
  327. Packer.prototype.pack_array = function(ary){
  328. var length = ary.length;
  329. if (length <= 0x0f){
  330. this.pack_uint8(0x90 + length);
  331. } else if (length <= 0xffff){
  332. this.bufferBuilder.append(0xdc)
  333. this.pack_uint16(length);
  334. } else if (length <= 0xffffffff){
  335. this.bufferBuilder.append(0xdd);
  336. this.pack_uint32(length);
  337. } else{
  338. throw new Error('Invalid length');
  339. }
  340. for(var i = 0; i < length ; i++){
  341. this.pack(ary[i]);
  342. }
  343. }
  344. Packer.prototype.pack_integer = function(num){
  345. if ( -0x20 <= num && num <= 0x7f){
  346. this.bufferBuilder.append(num & 0xff);
  347. } else if (0x00 <= num && num <= 0xff){
  348. this.bufferBuilder.append(0xcc);
  349. this.pack_uint8(num);
  350. } else if (-0x80 <= num && num <= 0x7f){
  351. this.bufferBuilder.append(0xd0);
  352. this.pack_int8(num);
  353. } else if ( 0x0000 <= num && num <= 0xffff){
  354. this.bufferBuilder.append(0xcd);
  355. this.pack_uint16(num);
  356. } else if (-0x8000 <= num && num <= 0x7fff){
  357. this.bufferBuilder.append(0xd1);
  358. this.pack_int16(num);
  359. } else if ( 0x00000000 <= num && num <= 0xffffffff){
  360. this.bufferBuilder.append(0xce);
  361. this.pack_uint32(num);
  362. } else if (-0x80000000 <= num && num <= 0x7fffffff){
  363. this.bufferBuilder.append(0xd2);
  364. this.pack_int32(num);
  365. } else if (-0x8000000000000000 <= num && num <= 0x7FFFFFFFFFFFFFFF){
  366. this.bufferBuilder.append(0xd3);
  367. this.pack_int64(num);
  368. } else if (0x0000000000000000 <= num && num <= 0xFFFFFFFFFFFFFFFF){
  369. this.bufferBuilder.append(0xcf);
  370. this.pack_uint64(num);
  371. } else{
  372. throw new Error('Invalid integer');
  373. }
  374. }
  375. Packer.prototype.pack_double = function(num){
  376. var sign = 0;
  377. if (num < 0){
  378. sign = 1;
  379. num = -num;
  380. }
  381. var exp = Math.floor(Math.log(num) / Math.LN2);
  382. var frac0 = num / Math.pow(2, exp) - 1;
  383. var frac1 = Math.floor(frac0 * Math.pow(2, 52));
  384. var b32 = Math.pow(2, 32);
  385. var h32 = (sign << 31) | ((exp+1023) << 20) |
  386. (frac1 / b32) & 0x0fffff;
  387. var l32 = frac1 % b32;
  388. this.bufferBuilder.append(0xcb);
  389. this.pack_int32(h32);
  390. this.pack_int32(l32);
  391. }
  392. Packer.prototype.pack_object = function(obj){
  393. var keys = Object.keys(obj);
  394. var length = keys.length;
  395. if (length <= 0x0f){
  396. this.pack_uint8(0x80 + length);
  397. } else if (length <= 0xffff){
  398. this.bufferBuilder.append(0xde);
  399. this.pack_uint16(length);
  400. } else if (length <= 0xffffffff){
  401. this.bufferBuilder.append(0xdf);
  402. this.pack_uint32(length);
  403. } else{
  404. throw new Error('Invalid length');
  405. }
  406. for(var prop in obj){
  407. if (obj.hasOwnProperty(prop)){
  408. this.pack(prop);
  409. this.pack(obj[prop]);
  410. }
  411. }
  412. }
  413. Packer.prototype.pack_uint8 = function(num){
  414. this.bufferBuilder.append(num);
  415. }
  416. Packer.prototype.pack_uint16 = function(num){
  417. this.bufferBuilder.append(num >> 8);
  418. this.bufferBuilder.append(num & 0xff);
  419. }
  420. Packer.prototype.pack_uint32 = function(num){
  421. var n = num & 0xffffffff;
  422. this.bufferBuilder.append((n & 0xff000000) >>> 24);
  423. this.bufferBuilder.append((n & 0x00ff0000) >>> 16);
  424. this.bufferBuilder.append((n & 0x0000ff00) >>> 8);
  425. this.bufferBuilder.append((n & 0x000000ff));
  426. }
  427. Packer.prototype.pack_uint64 = function(num){
  428. var high = num / Math.pow(2, 32);
  429. var low = num % Math.pow(2, 32);
  430. this.bufferBuilder.append((high & 0xff000000) >>> 24);
  431. this.bufferBuilder.append((high & 0x00ff0000) >>> 16);
  432. this.bufferBuilder.append((high & 0x0000ff00) >>> 8);
  433. this.bufferBuilder.append((high & 0x000000ff));
  434. this.bufferBuilder.append((low & 0xff000000) >>> 24);
  435. this.bufferBuilder.append((low & 0x00ff0000) >>> 16);
  436. this.bufferBuilder.append((low & 0x0000ff00) >>> 8);
  437. this.bufferBuilder.append((low & 0x000000ff));
  438. }
  439. Packer.prototype.pack_int8 = function(num){
  440. this.bufferBuilder.append(num & 0xff);
  441. }
  442. Packer.prototype.pack_int16 = function(num){
  443. this.bufferBuilder.append((num & 0xff00) >> 8);
  444. this.bufferBuilder.append(num & 0xff);
  445. }
  446. Packer.prototype.pack_int32 = function(num){
  447. this.bufferBuilder.append((num >>> 24) & 0xff);
  448. this.bufferBuilder.append((num & 0x00ff0000) >>> 16);
  449. this.bufferBuilder.append((num & 0x0000ff00) >>> 8);
  450. this.bufferBuilder.append((num & 0x000000ff));
  451. }
  452. Packer.prototype.pack_int64 = function(num){
  453. var high = Math.floor(num / Math.pow(2, 32));
  454. var low = num % Math.pow(2, 32);
  455. this.bufferBuilder.append((high & 0xff000000) >>> 24);
  456. this.bufferBuilder.append((high & 0x00ff0000) >>> 16);
  457. this.bufferBuilder.append((high & 0x0000ff00) >>> 8);
  458. this.bufferBuilder.append((high & 0x000000ff));
  459. this.bufferBuilder.append((low & 0xff000000) >>> 24);
  460. this.bufferBuilder.append((low & 0x00ff0000) >>> 16);
  461. this.bufferBuilder.append((low & 0x0000ff00) >>> 8);
  462. this.bufferBuilder.append((low & 0x000000ff));
  463. }
  464. function _utf8Replace(m){
  465. var code = m.charCodeAt(0);
  466. if(code <= 0x7ff) return '00';
  467. if(code <= 0xffff) return '000';
  468. if(code <= 0x1fffff) return '0000';
  469. if(code <= 0x3ffffff) return '00000';
  470. return '000000';
  471. }
  472. function utf8Length(str){
  473. if (str.length > 600) {
  474. // Blob method faster for large strings
  475. return (new Blob([str])).size;
  476. } else {
  477. return str.replace(/[^\u0000-\u007F]/g, _utf8Replace).length;
  478. }
  479. }
  480. },{"./bufferbuilder":2}],2:[function(require,module,exports){
  481. var binaryFeatures = {};
  482. binaryFeatures.useBlobBuilder = (function(){
  483. try {
  484. new Blob([]);
  485. return false;
  486. } catch (e) {
  487. return true;
  488. }
  489. })();
  490. binaryFeatures.useArrayBufferView = !binaryFeatures.useBlobBuilder && (function(){
  491. try {
  492. return (new Blob([new Uint8Array([])])).size === 0;
  493. } catch (e) {
  494. return true;
  495. }
  496. })();
  497. module.exports.binaryFeatures = binaryFeatures;
  498. var BlobBuilder = module.exports.BlobBuilder;
  499. if (typeof window != 'undefined') {
  500. BlobBuilder = module.exports.BlobBuilder = window.WebKitBlobBuilder ||
  501. window.MozBlobBuilder || window.MSBlobBuilder || window.BlobBuilder;
  502. }
  503. function BufferBuilder(){
  504. this._pieces = [];
  505. this._parts = [];
  506. }
  507. BufferBuilder.prototype.append = function(data) {
  508. if(typeof data === 'number') {
  509. this._pieces.push(data);
  510. } else {
  511. this.flush();
  512. this._parts.push(data);
  513. }
  514. };
  515. BufferBuilder.prototype.flush = function() {
  516. if (this._pieces.length > 0) {
  517. var buf = new Uint8Array(this._pieces);
  518. if(!binaryFeatures.useArrayBufferView) {
  519. buf = buf.buffer;
  520. }
  521. this._parts.push(buf);
  522. this._pieces = [];
  523. }
  524. };
  525. BufferBuilder.prototype.getBuffer = function() {
  526. this.flush();
  527. if(binaryFeatures.useBlobBuilder) {
  528. var builder = new BlobBuilder();
  529. for(var i = 0, ii = this._parts.length; i < ii; i++) {
  530. builder.append(this._parts[i]);
  531. }
  532. return builder.getBlob();
  533. } else {
  534. return new Blob(this._parts);
  535. }
  536. };
  537. module.exports.BufferBuilder = BufferBuilder;
  538. },{}],3:[function(require,module,exports){
  539. var BufferBuilderExports = require('./bufferbuilder');
  540. window.BufferBuilder = BufferBuilderExports.BufferBuilder;
  541. window.binaryFeatures = BufferBuilderExports.binaryFeatures;
  542. window.BlobBuilder = BufferBuilderExports.BlobBuilder;
  543. window.BinaryPack = require('./binarypack');
  544. },{"./binarypack":1,"./bufferbuilder":2}]},{},[3]);
  545. /**
  546. * Light EventEmitter. Ported from Node.js/events.js
  547. * Eric Zhang
  548. */
  549. /**
  550. * EventEmitter class
  551. * Creates an object with event registering and firing methods
  552. */
  553. function EventEmitter() {
  554. // Initialise required storage variables
  555. this._events = {};
  556. }
  557. var isArray = Array.isArray;
  558. EventEmitter.prototype.addListener = function(type, listener, scope, once) {
  559. if ('function' !== typeof listener) {
  560. throw new Error('addListener only takes instances of Function');
  561. }
  562. // To avoid recursion in the case that type == "newListeners"! Before
  563. // adding it to the listeners, first emit "newListeners".
  564. this.emit('newListener', type, typeof listener.listener === 'function' ?
  565. listener.listener : listener);
  566. if (!this._events[type]) {
  567. // Optimize the case of one listener. Don't need the extra array object.
  568. this._events[type] = listener;
  569. } else if (isArray(this._events[type])) {
  570. // If we've already got an array, just append.
  571. this._events[type].push(listener);
  572. } else {
  573. // Adding the second element, need to change to array.
  574. this._events[type] = [this._events[type], listener];
  575. }
  576. };
  577. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  578. EventEmitter.prototype.once = function(type, listener, scope) {
  579. if ('function' !== typeof listener) {
  580. throw new Error('.once only takes instances of Function');
  581. }
  582. var self = this;
  583. function g() {
  584. self.removeListener(type, g);
  585. listener.apply(this, arguments);
  586. };
  587. g.listener = listener;
  588. self.on(type, g);
  589. return this;
  590. };
  591. EventEmitter.prototype.removeListener = function(type, listener, scope) {
  592. if ('function' !== typeof listener) {
  593. throw new Error('removeListener only takes instances of Function');
  594. }
  595. // does not use listeners(), so no side effect of creating _events[type]
  596. if (!this._events[type]) return this;
  597. var list = this._events[type];
  598. if (isArray(list)) {
  599. var position = -1;
  600. for (var i = 0, length = list.length; i < length; i++) {
  601. if (list[i] === listener ||
  602. (list[i].listener && list[i].listener === listener))
  603. {
  604. position = i;
  605. break;
  606. }
  607. }
  608. if (position < 0) return this;
  609. list.splice(position, 1);
  610. if (list.length == 0)
  611. delete this._events[type];
  612. } else if (list === listener ||
  613. (list.listener && list.listener === listener))
  614. {
  615. delete this._events[type];
  616. }
  617. return this;
  618. };
  619. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  620. EventEmitter.prototype.removeAllListeners = function(type) {
  621. if (arguments.length === 0) {
  622. this._events = {};
  623. return this;
  624. }
  625. // does not use listeners(), so no side effect of creating _events[type]
  626. if (type && this._events && this._events[type]) this._events[type] = null;
  627. return this;
  628. };
  629. EventEmitter.prototype.listeners = function(type) {
  630. if (!this._events[type]) this._events[type] = [];
  631. if (!isArray(this._events[type])) {
  632. this._events[type] = [this._events[type]];
  633. }
  634. return this._events[type];
  635. };
  636. EventEmitter.prototype.emit = function(type) {
  637. var type = arguments[0];
  638. var handler = this._events[type];
  639. if (!handler) return false;
  640. if (typeof handler == 'function') {
  641. switch (arguments.length) {
  642. // fast cases
  643. case 1:
  644. handler.call(this);
  645. break;
  646. case 2:
  647. handler.call(this, arguments[1]);
  648. break;
  649. case 3:
  650. handler.call(this, arguments[1], arguments[2]);
  651. break;
  652. // slower
  653. default:
  654. var l = arguments.length;
  655. var args = new Array(l - 1);
  656. for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
  657. handler.apply(this, args);
  658. }
  659. return true;
  660. } else if (isArray(handler)) {
  661. var l = arguments.length;
  662. var args = new Array(l - 1);
  663. for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
  664. var listeners = handler.slice();
  665. for (var i = 0, l = listeners.length; i < l; i++) {
  666. listeners[i].apply(this, args);
  667. }
  668. return true;
  669. } else {
  670. return false;
  671. }
  672. };
  673. var util = {
  674. inherits: function(ctor, superCtor) {
  675. ctor.super_ = superCtor;
  676. ctor.prototype = Object.create(superCtor.prototype, {
  677. constructor: {
  678. value: ctor,
  679. enumerable: false,
  680. writable: true,
  681. configurable: true
  682. }
  683. });
  684. },
  685. extend: function(dest, source) {
  686. for(var key in source) {
  687. if(source.hasOwnProperty(key)) {
  688. dest[key] = source[key];
  689. }
  690. }
  691. return dest;
  692. },
  693. pack: BinaryPack.pack,
  694. unpack: BinaryPack.unpack,
  695. setZeroTimeout: (function(global) {
  696. var timeouts = [];
  697. var messageName = 'zero-timeout-message';
  698. // Like setTimeout, but only takes a function argument. There's
  699. // no time argument (always zero) and no arguments (you have to
  700. // use a closure).
  701. function setZeroTimeoutPostMessage(fn) {
  702. timeouts.push(fn);
  703. global.postMessage(messageName, '*');
  704. }
  705. function handleMessage(event) {
  706. if (event.source == global && event.data == messageName) {
  707. if (event.stopPropagation) {
  708. event.stopPropagation();
  709. }
  710. if (timeouts.length) {
  711. timeouts.shift()();
  712. }
  713. }
  714. }
  715. if (global.addEventListener) {
  716. global.addEventListener('message', handleMessage, true);
  717. } else if (global.attachEvent) {
  718. global.attachEvent('onmessage', handleMessage);
  719. }
  720. return setZeroTimeoutPostMessage;
  721. }(this))
  722. };
  723. exports.util = util;
  724. function Stream() {
  725. EventEmitter.call(this);
  726. }
  727. util.inherits(Stream, EventEmitter);
  728. Stream.prototype.pipe = function(dest, options) {
  729. var source = this;
  730. function ondata(chunk) {
  731. if (dest.writable) {
  732. if (false === dest.write(chunk) && source.pause) {
  733. source.pause();
  734. }
  735. }
  736. }
  737. source.on('data', ondata);
  738. function ondrain() {
  739. if (source.readable && source.resume) {
  740. source.resume();
  741. }
  742. }
  743. dest.on('drain', ondrain);
  744. // If the 'end' option is not supplied, dest.end() will be called when
  745. // source gets the 'end' or 'close' events. Only dest.end() once.
  746. if (!dest._isStdio && (!options || options.end !== false)) {
  747. source.on('end', onend);
  748. source.on('close', onclose);
  749. }
  750. var didOnEnd = false;
  751. function onend() {
  752. if (didOnEnd) return;
  753. didOnEnd = true;
  754. dest.end();
  755. }
  756. function onclose() {
  757. if (didOnEnd) return;
  758. didOnEnd = true;
  759. dest.destroy();
  760. }
  761. // don't leave dangling pipes when there are errors.
  762. function onerror(er) {
  763. cleanup();
  764. if (this.listeners('error').length === 0) {
  765. throw er; // Unhandled stream error in pipe.
  766. }
  767. }
  768. source.on('error', onerror);
  769. dest.on('error', onerror);
  770. // remove all the event listeners that were added.
  771. function cleanup() {
  772. source.removeListener('data', ondata);
  773. dest.removeListener('drain', ondrain);
  774. source.removeListener('end', onend);
  775. source.removeListener('close', onclose);
  776. source.removeListener('error', onerror);
  777. dest.removeListener('error', onerror);
  778. source.removeListener('end', cleanup);
  779. source.removeListener('close', cleanup);
  780. dest.removeListener('end', cleanup);
  781. dest.removeListener('close', cleanup);
  782. }
  783. source.on('end', cleanup);
  784. source.on('close', cleanup);
  785. dest.on('end', cleanup);
  786. dest.on('close', cleanup);
  787. dest.emit('pipe', source);
  788. // Allow for unix-like usage: A.pipe(B).pipe(C)
  789. return dest;
  790. };
  791. exports.Stream = Stream;
  792. function BlobReadStream(source, options){
  793. Stream.call(this);
  794. options = util.extend({
  795. readDelay: 0,
  796. paused: false
  797. }, options);
  798. this._source = source;
  799. this._start = 0;
  800. this._readChunkSize = options.chunkSize || source.size;
  801. this._readDelay = options.readDelay;
  802. this.readable = true;
  803. this.paused = options.paused;
  804. this._read();
  805. }
  806. util.inherits(BlobReadStream, Stream);
  807. BlobReadStream.prototype.pause = function(){
  808. this.paused = true;
  809. };
  810. BlobReadStream.prototype.resume = function(){
  811. this.paused = false;
  812. this._read();
  813. };
  814. BlobReadStream.prototype.destroy = function(){
  815. this.readable = false;
  816. clearTimeout(this._timeoutId);
  817. };
  818. BlobReadStream.prototype._read = function(){
  819. var self = this;
  820. function emitReadChunk(){
  821. self._emitReadChunk();
  822. }
  823. var readDelay = this._readDelay;
  824. if (readDelay !== 0){
  825. this._timeoutId = setTimeout(emitReadChunk, readDelay);
  826. } else {
  827. util.setZeroTimeout(emitReadChunk);
  828. }
  829. };
  830. BlobReadStream.prototype._emitReadChunk = function(){
  831. if(this.paused || !this.readable) return;
  832. var chunkSize = Math.min(this._source.size - this._start, this._readChunkSize);
  833. if(chunkSize === 0){
  834. this.readable = false;
  835. this.emit("end");
  836. return;
  837. }
  838. var sourceEnd = this._start + chunkSize;
  839. var chunk = (this._source.slice || this._source.webkitSlice || this._source.mozSlice).call(this._source, this._start, sourceEnd);
  840. this._start = sourceEnd;
  841. this._read();
  842. this.emit("data", chunk);
  843. };
  844. exports.BlobReadStream = BlobReadStream;
  845. function BinaryStream(socket, id, create, meta) {
  846. if (!(this instanceof BinaryStream)) return new BinaryStream(options);
  847. var self = this;
  848. Stream.call(this);
  849. this.id = id;
  850. this._socket = socket;
  851. this.writable = true;
  852. this.readable = true;
  853. this.paused = false;
  854. this._closed = false;
  855. this._ended = false;
  856. if(create) {
  857. // This is a stream we are creating
  858. this._write(1, meta, this.id);
  859. }
  860. }
  861. util.inherits(BinaryStream, Stream);
  862. BinaryStream.prototype._onDrain = function() {
  863. if(!this.paused) {
  864. this.emit('drain');
  865. }
  866. };
  867. BinaryStream.prototype._onClose = function() {
  868. // Emit close event
  869. if (this._closed) {
  870. return;
  871. }
  872. this.readable = false;
  873. this.writable = false;
  874. this._closed = true;
  875. this.emit('close');
  876. };
  877. BinaryStream.prototype._onError = function(error){
  878. this.readable = false;
  879. this.writable = false;
  880. this.emit('error', error);
  881. };
  882. // Write stream
  883. BinaryStream.prototype._onPause = function() {
  884. // Emit pause event
  885. this.paused = true;
  886. this.emit('pause');
  887. };
  888. BinaryStream.prototype._onResume = function() {
  889. // Emit resume event
  890. this.paused = false;
  891. this.emit('resume');
  892. this.emit('drain');
  893. };
  894. BinaryStream.prototype._write = function(code, data, bonus) {
  895. if (this._socket.readyState !== this._socket.constructor.OPEN) {
  896. return false;
  897. }
  898. var message = util.pack([code, data, bonus]);
  899. return this._socket.send(message) !== false;
  900. };
  901. BinaryStream.prototype.write = function(data) {
  902. if(this.writable) {
  903. var out = this._write(2, data, this.id);
  904. return !this.paused && out;
  905. } else {
  906. this.emit('error', new Error('Stream is not writable'));
  907. return false;
  908. }
  909. };
  910. BinaryStream.prototype.end = function() {
  911. this._ended = true;
  912. this.readable = false;
  913. this._write(5, null, this.id);
  914. };
  915. BinaryStream.prototype.destroy = BinaryStream.prototype.destroySoon = function() {
  916. this._onClose();
  917. this._write(6, null, this.id);
  918. };
  919. // Read stream
  920. BinaryStream.prototype._onEnd = function() {
  921. if(this._ended) {
  922. return;
  923. }
  924. this._ended = true;
  925. this.readable = false;
  926. this.emit('end');
  927. };
  928. BinaryStream.prototype._onData = function(data) {
  929. // Dispatch
  930. this.emit('data', data);
  931. };
  932. BinaryStream.prototype.pause = function() {
  933. this._onPause();
  934. this._write(3, null, this.id);
  935. };
  936. BinaryStream.prototype.resume = function() {
  937. this._onResume();
  938. this._write(4, null, this.id);
  939. };
  940. function BinaryClient(socket, options) {
  941. if (!(this instanceof BinaryClient)) return new BinaryClient(socket, options);
  942. EventEmitter.call(this);
  943. var self = this;
  944. this._options = util.extend({
  945. chunkSize: 40960
  946. }, options);
  947. this.streams = {};
  948. if(typeof socket === 'string') {
  949. this._nextId = 0;
  950. this._socket = new WebSocket(socket);
  951. } else {
  952. // Use odd numbered ids for server originated streams
  953. this._nextId = 1;
  954. this._socket = socket;
  955. }
  956. this._socket.binaryType = 'arraybuffer';
  957. this._socket.addEventListener('open', function(){
  958. self.emit('open');
  959. });
  960. this._socket.addEventListener('error', function(error){
  961. var ids = Object.keys(self.streams);
  962. for (var i = 0, ii = ids.length; i < ii; i++) {
  963. self.streams[ids[i]]._onError(error);
  964. }
  965. self.emit('error', error);
  966. });
  967. this._socket.addEventListener('close', function(code, message){
  968. var ids = Object.keys(self.streams);
  969. for (var i = 0, ii = ids.length; i < ii; i++) {
  970. self.streams[ids[i]]._onClose();
  971. }
  972. self.emit('close', code, message);
  973. });
  974. this._socket.addEventListener('message', function(data, flags){
  975. util.setZeroTimeout(function(){
  976. // Message format
  977. // [type, payload, bonus ]
  978. //
  979. // Reserved
  980. // [ 0 , X , X ]
  981. //
  982. //
  983. // New stream
  984. // [ 1 , Meta , new streamId ]
  985. //
  986. //
  987. // Data
  988. // [ 2 , Data , streamId ]
  989. //
  990. //
  991. // Pause
  992. // [ 3 , null , streamId ]
  993. //
  994. //
  995. // Resume
  996. // [ 4 , null , streamId ]
  997. //
  998. //
  999. // End
  1000. // [ 5 , null , streamId ]
  1001. //
  1002. //
  1003. // Close
  1004. // [ 6 , null , streamId ]
  1005. //
  1006. data = data.data;
  1007. try {
  1008. data = util.unpack(data);
  1009. } catch (ex) {
  1010. return self.emit('error', new Error('Received unparsable message: ' + ex));
  1011. }
  1012. if (!(data instanceof Array))
  1013. return self.emit('error', new Error('Received non-array message'));
  1014. if (data.length != 3)
  1015. return self.emit('error', new Error('Received message with wrong part count: ' + data.length));
  1016. if ('number' != typeof data[0])
  1017. return self.emit('error', new Error('Received message with non-number type: ' + data[0]));
  1018. switch(data[0]) {
  1019. case 0:
  1020. // Reserved
  1021. break;
  1022. case 1:
  1023. var meta = data[1];
  1024. var streamId = data[2];
  1025. var binaryStream = self._receiveStream(streamId);
  1026. self.emit('stream', binaryStream, meta);
  1027. break;
  1028. case 2:
  1029. var payload = data[1];
  1030. var streamId = data[2];
  1031. var binaryStream = self.streams[streamId];
  1032. if(binaryStream) {
  1033. binaryStream._onData(payload);
  1034. } else {
  1035. self.emit('error', new Error('Received `data` message for unknown stream: ' + streamId));
  1036. }
  1037. break;
  1038. case 3:
  1039. var streamId = data[2];
  1040. var binaryStream = self.streams[streamId];
  1041. if(binaryStream) {
  1042. binaryStream._onPause();
  1043. } else {
  1044. self.emit('error', new Error('Received `pause` message for unknown stream: ' + streamId));
  1045. }
  1046. break;
  1047. case 4:
  1048. var streamId = data[2];
  1049. var binaryStream = self.streams[streamId];
  1050. if(binaryStream) {
  1051. binaryStream._onResume();
  1052. } else {
  1053. self.emit('error', new Error('Received `resume` message for unknown stream: ' + streamId));
  1054. }
  1055. break;
  1056. case 5:
  1057. var streamId = data[2];
  1058. var binaryStream = self.streams[streamId];
  1059. if(binaryStream) {
  1060. binaryStream._onEnd();
  1061. } else {
  1062. self.emit('error', new Error('Received `end` message for unknown stream: ' + streamId));
  1063. }
  1064. break;
  1065. case 6:
  1066. var streamId = data[2];
  1067. var binaryStream = self.streams[streamId];
  1068. if(binaryStream) {
  1069. binaryStream._onClose();
  1070. } else {
  1071. self.emit('error', new Error('Received `close` message for unknown stream: ' + streamId));
  1072. }
  1073. break;
  1074. default:
  1075. self.emit('error', new Error('Unrecognized message type received: ' + data[0]));
  1076. }
  1077. });
  1078. });
  1079. }
  1080. util.inherits(BinaryClient, EventEmitter);
  1081. BinaryClient.prototype.send = function(data, meta){
  1082. var stream = this.createStream(meta);
  1083. if(data instanceof Stream) {
  1084. data.pipe(stream);
  1085. } else if (util.isNode === true) {
  1086. if(Buffer.isBuffer(data)) {
  1087. (new BufferReadStream(data, {chunkSize: this._options.chunkSize})).pipe(stream);
  1088. } else {
  1089. stream.write(data);
  1090. }
  1091. } else if (util.isNode !== true) {
  1092. if(data.constructor == Blob || data.constructor == File) {
  1093. (new BlobReadStream(data, {chunkSize: this._options.chunkSize})).pipe(stream);
  1094. } else if (data.constructor == ArrayBuffer) {
  1095. var blob;
  1096. if(binaryFeatures.useArrayBufferView) {
  1097. data = new Uint8Array(data);
  1098. }
  1099. if(binaryFeatures.useBlobBuilder) {
  1100. var builder = new BlobBuilder();
  1101. builder.append(data);
  1102. blob = builder.getBlob()
  1103. } else {
  1104. blob = new Blob([data]);
  1105. }
  1106. (new BlobReadStream(blob, {chunkSize: this._options.chunkSize})).pipe(stream);
  1107. } else if (typeof data === 'object' && 'BYTES_PER_ELEMENT' in data) {
  1108. var blob;
  1109. if(!binaryFeatures.useArrayBufferView) {
  1110. // Warn
  1111. data = data.buffer;
  1112. }
  1113. if(binaryFeatures.useBlobBuilder) {
  1114. var builder = new BlobBuilder();
  1115. builder.append(data);
  1116. blob = builder.getBlob()
  1117. } else {
  1118. blob = new Blob([data]);
  1119. }
  1120. (new BlobReadStream(blob, {chunkSize: this._options.chunkSize})).pipe(stream);
  1121. } else {
  1122. stream.write(data);
  1123. }
  1124. }
  1125. return stream;
  1126. };
  1127. BinaryClient.prototype._receiveStream = function(streamId){
  1128. var self = this;
  1129. var binaryStream = new BinaryStream(this._socket, streamId, false);
  1130. binaryStream.on('close', function(){
  1131. delete self.streams[streamId];
  1132. });
  1133. this.streams[streamId] = binaryStream;
  1134. return binaryStream;
  1135. };
  1136. BinaryClient.prototype.createStream = function(meta){
  1137. if(this._socket.readyState !== WebSocket.OPEN) {
  1138. throw new Error('Client is not yet connected or has closed');
  1139. return;
  1140. }
  1141. var self = this;
  1142. var streamId = this._nextId;
  1143. this._nextId += 2;
  1144. var binaryStream = new BinaryStream(this._socket, streamId, true, meta);
  1145. binaryStream.on('close', function(){
  1146. delete self.streams[streamId];
  1147. });
  1148. this.streams[streamId] = binaryStream;
  1149. return binaryStream;
  1150. };
  1151. BinaryClient.prototype.close = BinaryClient.prototype.destroy = function() {
  1152. this._socket.close();
  1153. };
  1154. exports.BinaryClient = BinaryClient;
  1155. })(this);
  1156. </script>