UNPKG

555 kBJavaScriptView Raw
1(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.eosEcc = f()}})(function(){var define,module,exports;return (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){
2(function (global){
3'use strict';
4
5// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
6// original notice:
7
8/*!
9 * The buffer module from node.js, for the browser.
10 *
11 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
12 * @license MIT
13 */
14function compare(a, b) {
15 if (a === b) {
16 return 0;
17 }
18
19 var x = a.length;
20 var y = b.length;
21
22 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
23 if (a[i] !== b[i]) {
24 x = a[i];
25 y = b[i];
26 break;
27 }
28 }
29
30 if (x < y) {
31 return -1;
32 }
33 if (y < x) {
34 return 1;
35 }
36 return 0;
37}
38function isBuffer(b) {
39 if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
40 return global.Buffer.isBuffer(b);
41 }
42 return !!(b != null && b._isBuffer);
43}
44
45// based on node assert, original notice:
46
47// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
48//
49// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
50//
51// Originally from narwhal.js (http://narwhaljs.org)
52// Copyright (c) 2009 Thomas Robinson <280north.com>
53//
54// Permission is hereby granted, free of charge, to any person obtaining a copy
55// of this software and associated documentation files (the 'Software'), to
56// deal in the Software without restriction, including without limitation the
57// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
58// sell copies of the Software, and to permit persons to whom the Software is
59// furnished to do so, subject to the following conditions:
60//
61// The above copyright notice and this permission notice shall be included in
62// all copies or substantial portions of the Software.
63//
64// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
65// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
66// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
67// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
68// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
69// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
70
71var util = require('util/');
72var hasOwn = Object.prototype.hasOwnProperty;
73var pSlice = Array.prototype.slice;
74var functionsHaveNames = (function () {
75 return function foo() {}.name === 'foo';
76}());
77function pToString (obj) {
78 return Object.prototype.toString.call(obj);
79}
80function isView(arrbuf) {
81 if (isBuffer(arrbuf)) {
82 return false;
83 }
84 if (typeof global.ArrayBuffer !== 'function') {
85 return false;
86 }
87 if (typeof ArrayBuffer.isView === 'function') {
88 return ArrayBuffer.isView(arrbuf);
89 }
90 if (!arrbuf) {
91 return false;
92 }
93 if (arrbuf instanceof DataView) {
94 return true;
95 }
96 if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
97 return true;
98 }
99 return false;
100}
101// 1. The assert module provides functions that throw
102// AssertionError's when particular conditions are not met. The
103// assert module must conform to the following interface.
104
105var assert = module.exports = ok;
106
107// 2. The AssertionError is defined in assert.
108// new assert.AssertionError({ message: message,
109// actual: actual,
110// expected: expected })
111
112var regex = /\s*function\s+([^\(\s]*)\s*/;
113// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
114function getName(func) {
115 if (!util.isFunction(func)) {
116 return;
117 }
118 if (functionsHaveNames) {
119 return func.name;
120 }
121 var str = func.toString();
122 var match = str.match(regex);
123 return match && match[1];
124}
125assert.AssertionError = function AssertionError(options) {
126 this.name = 'AssertionError';
127 this.actual = options.actual;
128 this.expected = options.expected;
129 this.operator = options.operator;
130 if (options.message) {
131 this.message = options.message;
132 this.generatedMessage = false;
133 } else {
134 this.message = getMessage(this);
135 this.generatedMessage = true;
136 }
137 var stackStartFunction = options.stackStartFunction || fail;
138 if (Error.captureStackTrace) {
139 Error.captureStackTrace(this, stackStartFunction);
140 } else {
141 // non v8 browsers so we can have a stacktrace
142 var err = new Error();
143 if (err.stack) {
144 var out = err.stack;
145
146 // try to strip useless frames
147 var fn_name = getName(stackStartFunction);
148 var idx = out.indexOf('\n' + fn_name);
149 if (idx >= 0) {
150 // once we have located the function frame
151 // we need to strip out everything before it (and its line)
152 var next_line = out.indexOf('\n', idx + 1);
153 out = out.substring(next_line + 1);
154 }
155
156 this.stack = out;
157 }
158 }
159};
160
161// assert.AssertionError instanceof Error
162util.inherits(assert.AssertionError, Error);
163
164function truncate(s, n) {
165 if (typeof s === 'string') {
166 return s.length < n ? s : s.slice(0, n);
167 } else {
168 return s;
169 }
170}
171function inspect(something) {
172 if (functionsHaveNames || !util.isFunction(something)) {
173 return util.inspect(something);
174 }
175 var rawname = getName(something);
176 var name = rawname ? ': ' + rawname : '';
177 return '[Function' + name + ']';
178}
179function getMessage(self) {
180 return truncate(inspect(self.actual), 128) + ' ' +
181 self.operator + ' ' +
182 truncate(inspect(self.expected), 128);
183}
184
185// At present only the three keys mentioned above are used and
186// understood by the spec. Implementations or sub modules can pass
187// other keys to the AssertionError's constructor - they will be
188// ignored.
189
190// 3. All of the following functions must throw an AssertionError
191// when a corresponding condition is not met, with a message that
192// may be undefined if not provided. All assertion methods provide
193// both the actual and expected values to the assertion error for
194// display purposes.
195
196function fail(actual, expected, message, operator, stackStartFunction) {
197 throw new assert.AssertionError({
198 message: message,
199 actual: actual,
200 expected: expected,
201 operator: operator,
202 stackStartFunction: stackStartFunction
203 });
204}
205
206// EXTENSION! allows for well behaved errors defined elsewhere.
207assert.fail = fail;
208
209// 4. Pure assertion tests whether a value is truthy, as determined
210// by !!guard.
211// assert.ok(guard, message_opt);
212// This statement is equivalent to assert.equal(true, !!guard,
213// message_opt);. To test strictly for the value true, use
214// assert.strictEqual(true, guard, message_opt);.
215
216function ok(value, message) {
217 if (!value) fail(value, true, message, '==', assert.ok);
218}
219assert.ok = ok;
220
221// 5. The equality assertion tests shallow, coercive equality with
222// ==.
223// assert.equal(actual, expected, message_opt);
224
225assert.equal = function equal(actual, expected, message) {
226 if (actual != expected) fail(actual, expected, message, '==', assert.equal);
227};
228
229// 6. The non-equality assertion tests for whether two objects are not equal
230// with != assert.notEqual(actual, expected, message_opt);
231
232assert.notEqual = function notEqual(actual, expected, message) {
233 if (actual == expected) {
234 fail(actual, expected, message, '!=', assert.notEqual);
235 }
236};
237
238// 7. The equivalence assertion tests a deep equality relation.
239// assert.deepEqual(actual, expected, message_opt);
240
241assert.deepEqual = function deepEqual(actual, expected, message) {
242 if (!_deepEqual(actual, expected, false)) {
243 fail(actual, expected, message, 'deepEqual', assert.deepEqual);
244 }
245};
246
247assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
248 if (!_deepEqual(actual, expected, true)) {
249 fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
250 }
251};
252
253function _deepEqual(actual, expected, strict, memos) {
254 // 7.1. All identical values are equivalent, as determined by ===.
255 if (actual === expected) {
256 return true;
257 } else if (isBuffer(actual) && isBuffer(expected)) {
258 return compare(actual, expected) === 0;
259
260 // 7.2. If the expected value is a Date object, the actual value is
261 // equivalent if it is also a Date object that refers to the same time.
262 } else if (util.isDate(actual) && util.isDate(expected)) {
263 return actual.getTime() === expected.getTime();
264
265 // 7.3 If the expected value is a RegExp object, the actual value is
266 // equivalent if it is also a RegExp object with the same source and
267 // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
268 } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
269 return actual.source === expected.source &&
270 actual.global === expected.global &&
271 actual.multiline === expected.multiline &&
272 actual.lastIndex === expected.lastIndex &&
273 actual.ignoreCase === expected.ignoreCase;
274
275 // 7.4. Other pairs that do not both pass typeof value == 'object',
276 // equivalence is determined by ==.
277 } else if ((actual === null || typeof actual !== 'object') &&
278 (expected === null || typeof expected !== 'object')) {
279 return strict ? actual === expected : actual == expected;
280
281 // If both values are instances of typed arrays, wrap their underlying
282 // ArrayBuffers in a Buffer each to increase performance
283 // This optimization requires the arrays to have the same type as checked by
284 // Object.prototype.toString (aka pToString). Never perform binary
285 // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
286 // bit patterns are not identical.
287 } else if (isView(actual) && isView(expected) &&
288 pToString(actual) === pToString(expected) &&
289 !(actual instanceof Float32Array ||
290 actual instanceof Float64Array)) {
291 return compare(new Uint8Array(actual.buffer),
292 new Uint8Array(expected.buffer)) === 0;
293
294 // 7.5 For all other Object pairs, including Array objects, equivalence is
295 // determined by having the same number of owned properties (as verified
296 // with Object.prototype.hasOwnProperty.call), the same set of keys
297 // (although not necessarily the same order), equivalent values for every
298 // corresponding key, and an identical 'prototype' property. Note: this
299 // accounts for both named and indexed properties on Arrays.
300 } else if (isBuffer(actual) !== isBuffer(expected)) {
301 return false;
302 } else {
303 memos = memos || {actual: [], expected: []};
304
305 var actualIndex = memos.actual.indexOf(actual);
306 if (actualIndex !== -1) {
307 if (actualIndex === memos.expected.indexOf(expected)) {
308 return true;
309 }
310 }
311
312 memos.actual.push(actual);
313 memos.expected.push(expected);
314
315 return objEquiv(actual, expected, strict, memos);
316 }
317}
318
319function isArguments(object) {
320 return Object.prototype.toString.call(object) == '[object Arguments]';
321}
322
323function objEquiv(a, b, strict, actualVisitedObjects) {
324 if (a === null || a === undefined || b === null || b === undefined)
325 return false;
326 // if one is a primitive, the other must be same
327 if (util.isPrimitive(a) || util.isPrimitive(b))
328 return a === b;
329 if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
330 return false;
331 var aIsArgs = isArguments(a);
332 var bIsArgs = isArguments(b);
333 if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
334 return false;
335 if (aIsArgs) {
336 a = pSlice.call(a);
337 b = pSlice.call(b);
338 return _deepEqual(a, b, strict);
339 }
340 var ka = objectKeys(a);
341 var kb = objectKeys(b);
342 var key, i;
343 // having the same number of owned properties (keys incorporates
344 // hasOwnProperty)
345 if (ka.length !== kb.length)
346 return false;
347 //the same set of keys (although not necessarily the same order),
348 ka.sort();
349 kb.sort();
350 //~~~cheap key test
351 for (i = ka.length - 1; i >= 0; i--) {
352 if (ka[i] !== kb[i])
353 return false;
354 }
355 //equivalent values for every corresponding key, and
356 //~~~possibly expensive deep test
357 for (i = ka.length - 1; i >= 0; i--) {
358 key = ka[i];
359 if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
360 return false;
361 }
362 return true;
363}
364
365// 8. The non-equivalence assertion tests for any deep inequality.
366// assert.notDeepEqual(actual, expected, message_opt);
367
368assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
369 if (_deepEqual(actual, expected, false)) {
370 fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
371 }
372};
373
374assert.notDeepStrictEqual = notDeepStrictEqual;
375function notDeepStrictEqual(actual, expected, message) {
376 if (_deepEqual(actual, expected, true)) {
377 fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
378 }
379}
380
381
382// 9. The strict equality assertion tests strict equality, as determined by ===.
383// assert.strictEqual(actual, expected, message_opt);
384
385assert.strictEqual = function strictEqual(actual, expected, message) {
386 if (actual !== expected) {
387 fail(actual, expected, message, '===', assert.strictEqual);
388 }
389};
390
391// 10. The strict non-equality assertion tests for strict inequality, as
392// determined by !==. assert.notStrictEqual(actual, expected, message_opt);
393
394assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
395 if (actual === expected) {
396 fail(actual, expected, message, '!==', assert.notStrictEqual);
397 }
398};
399
400function expectedException(actual, expected) {
401 if (!actual || !expected) {
402 return false;
403 }
404
405 if (Object.prototype.toString.call(expected) == '[object RegExp]') {
406 return expected.test(actual);
407 }
408
409 try {
410 if (actual instanceof expected) {
411 return true;
412 }
413 } catch (e) {
414 // Ignore. The instanceof check doesn't work for arrow functions.
415 }
416
417 if (Error.isPrototypeOf(expected)) {
418 return false;
419 }
420
421 return expected.call({}, actual) === true;
422}
423
424function _tryBlock(block) {
425 var error;
426 try {
427 block();
428 } catch (e) {
429 error = e;
430 }
431 return error;
432}
433
434function _throws(shouldThrow, block, expected, message) {
435 var actual;
436
437 if (typeof block !== 'function') {
438 throw new TypeError('"block" argument must be a function');
439 }
440
441 if (typeof expected === 'string') {
442 message = expected;
443 expected = null;
444 }
445
446 actual = _tryBlock(block);
447
448 message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
449 (message ? ' ' + message : '.');
450
451 if (shouldThrow && !actual) {
452 fail(actual, expected, 'Missing expected exception' + message);
453 }
454
455 var userProvidedMessage = typeof message === 'string';
456 var isUnwantedException = !shouldThrow && util.isError(actual);
457 var isUnexpectedException = !shouldThrow && actual && !expected;
458
459 if ((isUnwantedException &&
460 userProvidedMessage &&
461 expectedException(actual, expected)) ||
462 isUnexpectedException) {
463 fail(actual, expected, 'Got unwanted exception' + message);
464 }
465
466 if ((shouldThrow && actual && expected &&
467 !expectedException(actual, expected)) || (!shouldThrow && actual)) {
468 throw actual;
469 }
470}
471
472// 11. Expected to throw an error:
473// assert.throws(block, Error_opt, message_opt);
474
475assert.throws = function(block, /*optional*/error, /*optional*/message) {
476 _throws(true, block, error, message);
477};
478
479// EXTENSION! This is annoying to write outside this module.
480assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
481 _throws(false, block, error, message);
482};
483
484assert.ifError = function(err) { if (err) throw err; };
485
486var objectKeys = Object.keys || function (obj) {
487 var keys = [];
488 for (var key in obj) {
489 if (hasOwn.call(obj, key)) keys.push(key);
490 }
491 return keys;
492};
493
494}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
495},{"util/":33}],2:[function(require,module,exports){
496'use strict'
497
498exports.byteLength = byteLength
499exports.toByteArray = toByteArray
500exports.fromByteArray = fromByteArray
501
502var lookup = []
503var revLookup = []
504var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
505
506var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
507for (var i = 0, len = code.length; i < len; ++i) {
508 lookup[i] = code[i]
509 revLookup[code.charCodeAt(i)] = i
510}
511
512revLookup['-'.charCodeAt(0)] = 62
513revLookup['_'.charCodeAt(0)] = 63
514
515function placeHoldersCount (b64) {
516 var len = b64.length
517 if (len % 4 > 0) {
518 throw new Error('Invalid string. Length must be a multiple of 4')
519 }
520
521 // the number of equal signs (place holders)
522 // if there are two placeholders, than the two characters before it
523 // represent one byte
524 // if there is only one, then the three characters before it represent 2 bytes
525 // this is just a cheap hack to not do indexOf twice
526 return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
527}
528
529function byteLength (b64) {
530 // base64 is 4/3 + up to two characters of the original data
531 return b64.length * 3 / 4 - placeHoldersCount(b64)
532}
533
534function toByteArray (b64) {
535 var i, j, l, tmp, placeHolders, arr
536 var len = b64.length
537 placeHolders = placeHoldersCount(b64)
538
539 arr = new Arr(len * 3 / 4 - placeHolders)
540
541 // if there are placeholders, only get up to the last complete 4 chars
542 l = placeHolders > 0 ? len - 4 : len
543
544 var L = 0
545
546 for (i = 0, j = 0; i < l; i += 4, j += 3) {
547 tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
548 arr[L++] = (tmp >> 16) & 0xFF
549 arr[L++] = (tmp >> 8) & 0xFF
550 arr[L++] = tmp & 0xFF
551 }
552
553 if (placeHolders === 2) {
554 tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
555 arr[L++] = tmp & 0xFF
556 } else if (placeHolders === 1) {
557 tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
558 arr[L++] = (tmp >> 8) & 0xFF
559 arr[L++] = tmp & 0xFF
560 }
561
562 return arr
563}
564
565function tripletToBase64 (num) {
566 return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
567}
568
569function encodeChunk (uint8, start, end) {
570 var tmp
571 var output = []
572 for (var i = start; i < end; i += 3) {
573 tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
574 output.push(tripletToBase64(tmp))
575 }
576 return output.join('')
577}
578
579function fromByteArray (uint8) {
580 var tmp
581 var len = uint8.length
582 var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
583 var output = ''
584 var parts = []
585 var maxChunkLength = 16383 // must be multiple of 3
586
587 // go through the array every three bytes, we'll deal with trailing stuff later
588 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
589 parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
590 }
591
592 // pad the end with zeros, but make sure to not forget the extra bytes
593 if (extraBytes === 1) {
594 tmp = uint8[len - 1]
595 output += lookup[tmp >> 2]
596 output += lookup[(tmp << 4) & 0x3F]
597 output += '=='
598 } else if (extraBytes === 2) {
599 tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
600 output += lookup[tmp >> 10]
601 output += lookup[(tmp >> 4) & 0x3F]
602 output += lookup[(tmp << 2) & 0x3F]
603 output += '='
604 }
605
606 parts.push(output)
607
608 return parts.join('')
609}
610
611},{}],3:[function(require,module,exports){
612
613},{}],4:[function(require,module,exports){
614(function (global){
615'use strict';
616
617var buffer = require('buffer');
618var Buffer = buffer.Buffer;
619var SlowBuffer = buffer.SlowBuffer;
620var MAX_LEN = buffer.kMaxLength || 2147483647;
621exports.alloc = function alloc(size, fill, encoding) {
622 if (typeof Buffer.alloc === 'function') {
623 return Buffer.alloc(size, fill, encoding);
624 }
625 if (typeof encoding === 'number') {
626 throw new TypeError('encoding must not be number');
627 }
628 if (typeof size !== 'number') {
629 throw new TypeError('size must be a number');
630 }
631 if (size > MAX_LEN) {
632 throw new RangeError('size is too large');
633 }
634 var enc = encoding;
635 var _fill = fill;
636 if (_fill === undefined) {
637 enc = undefined;
638 _fill = 0;
639 }
640 var buf = new Buffer(size);
641 if (typeof _fill === 'string') {
642 var fillBuf = new Buffer(_fill, enc);
643 var flen = fillBuf.length;
644 var i = -1;
645 while (++i < size) {
646 buf[i] = fillBuf[i % flen];
647 }
648 } else {
649 buf.fill(_fill);
650 }
651 return buf;
652}
653exports.allocUnsafe = function allocUnsafe(size) {
654 if (typeof Buffer.allocUnsafe === 'function') {
655 return Buffer.allocUnsafe(size);
656 }
657 if (typeof size !== 'number') {
658 throw new TypeError('size must be a number');
659 }
660 if (size > MAX_LEN) {
661 throw new RangeError('size is too large');
662 }
663 return new Buffer(size);
664}
665exports.from = function from(value, encodingOrOffset, length) {
666 if (typeof Buffer.from === 'function' && (!global.Uint8Array || Uint8Array.from !== Buffer.from)) {
667 return Buffer.from(value, encodingOrOffset, length);
668 }
669 if (typeof value === 'number') {
670 throw new TypeError('"value" argument must not be a number');
671 }
672 if (typeof value === 'string') {
673 return new Buffer(value, encodingOrOffset);
674 }
675 if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
676 var offset = encodingOrOffset;
677 if (arguments.length === 1) {
678 return new Buffer(value);
679 }
680 if (typeof offset === 'undefined') {
681 offset = 0;
682 }
683 var len = length;
684 if (typeof len === 'undefined') {
685 len = value.byteLength - offset;
686 }
687 if (offset >= value.byteLength) {
688 throw new RangeError('\'offset\' is out of bounds');
689 }
690 if (len > value.byteLength - offset) {
691 throw new RangeError('\'length\' is out of bounds');
692 }
693 return new Buffer(value.slice(offset, offset + len));
694 }
695 if (Buffer.isBuffer(value)) {
696 var out = new Buffer(value.length);
697 value.copy(out, 0, 0, value.length);
698 return out;
699 }
700 if (value) {
701 if (Array.isArray(value) || (typeof ArrayBuffer !== 'undefined' && value.buffer instanceof ArrayBuffer) || 'length' in value) {
702 return new Buffer(value);
703 }
704 if (value.type === 'Buffer' && Array.isArray(value.data)) {
705 return new Buffer(value.data);
706 }
707 }
708
709 throw new TypeError('First argument must be a string, Buffer, ' + 'ArrayBuffer, Array, or array-like object.');
710}
711exports.allocUnsafeSlow = function allocUnsafeSlow(size) {
712 if (typeof Buffer.allocUnsafeSlow === 'function') {
713 return Buffer.allocUnsafeSlow(size);
714 }
715 if (typeof size !== 'number') {
716 throw new TypeError('size must be a number');
717 }
718 if (size >= MAX_LEN) {
719 throw new RangeError('size is too large');
720 }
721 return new SlowBuffer(size);
722}
723
724}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
725},{"buffer":5}],5:[function(require,module,exports){
726/*!
727 * The buffer module from node.js, for the browser.
728 *
729 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
730 * @license MIT
731 */
732/* eslint-disable no-proto */
733
734'use strict'
735
736var base64 = require('base64-js')
737var ieee754 = require('ieee754')
738
739exports.Buffer = Buffer
740exports.SlowBuffer = SlowBuffer
741exports.INSPECT_MAX_BYTES = 50
742
743var K_MAX_LENGTH = 0x7fffffff
744exports.kMaxLength = K_MAX_LENGTH
745
746/**
747 * If `Buffer.TYPED_ARRAY_SUPPORT`:
748 * === true Use Uint8Array implementation (fastest)
749 * === false Print warning and recommend using `buffer` v4.x which has an Object
750 * implementation (most compatible, even IE6)
751 *
752 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
753 * Opera 11.6+, iOS 4.2+.
754 *
755 * We report that the browser does not support typed arrays if the are not subclassable
756 * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
757 * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
758 * for __proto__ and has a buggy typed array implementation.
759 */
760Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
761
762if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
763 typeof console.error === 'function') {
764 console.error(
765 'This browser lacks typed array (Uint8Array) support which is required by ' +
766 '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
767 )
768}
769
770function typedArraySupport () {
771 // Can typed array instances can be augmented?
772 try {
773 var arr = new Uint8Array(1)
774 arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
775 return arr.foo() === 42
776 } catch (e) {
777 return false
778 }
779}
780
781function createBuffer (length) {
782 if (length > K_MAX_LENGTH) {
783 throw new RangeError('Invalid typed array length')
784 }
785 // Return an augmented `Uint8Array` instance
786 var buf = new Uint8Array(length)
787 buf.__proto__ = Buffer.prototype
788 return buf
789}
790
791/**
792 * The Buffer constructor returns instances of `Uint8Array` that have their
793 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
794 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
795 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
796 * returns a single octet.
797 *
798 * The `Uint8Array` prototype remains unmodified.
799 */
800
801function Buffer (arg, encodingOrOffset, length) {
802 // Common case.
803 if (typeof arg === 'number') {
804 if (typeof encodingOrOffset === 'string') {
805 throw new Error(
806 'If encoding is specified then the first argument must be a string'
807 )
808 }
809 return allocUnsafe(arg)
810 }
811 return from(arg, encodingOrOffset, length)
812}
813
814// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
815if (typeof Symbol !== 'undefined' && Symbol.species &&
816 Buffer[Symbol.species] === Buffer) {
817 Object.defineProperty(Buffer, Symbol.species, {
818 value: null,
819 configurable: true,
820 enumerable: false,
821 writable: false
822 })
823}
824
825Buffer.poolSize = 8192 // not used by this implementation
826
827function from (value, encodingOrOffset, length) {
828 if (typeof value === 'number') {
829 throw new TypeError('"value" argument must not be a number')
830 }
831
832 if (value instanceof ArrayBuffer) {
833 return fromArrayBuffer(value, encodingOrOffset, length)
834 }
835
836 if (typeof value === 'string') {
837 return fromString(value, encodingOrOffset)
838 }
839
840 return fromObject(value)
841}
842
843/**
844 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
845 * if value is a number.
846 * Buffer.from(str[, encoding])
847 * Buffer.from(array)
848 * Buffer.from(buffer)
849 * Buffer.from(arrayBuffer[, byteOffset[, length]])
850 **/
851Buffer.from = function (value, encodingOrOffset, length) {
852 return from(value, encodingOrOffset, length)
853}
854
855// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
856// https://github.com/feross/buffer/pull/148
857Buffer.prototype.__proto__ = Uint8Array.prototype
858Buffer.__proto__ = Uint8Array
859
860function assertSize (size) {
861 if (typeof size !== 'number') {
862 throw new TypeError('"size" argument must be a number')
863 } else if (size < 0) {
864 throw new RangeError('"size" argument must not be negative')
865 }
866}
867
868function alloc (size, fill, encoding) {
869 assertSize(size)
870 if (size <= 0) {
871 return createBuffer(size)
872 }
873 if (fill !== undefined) {
874 // Only pay attention to encoding if it's a string. This
875 // prevents accidentally sending in a number that would
876 // be interpretted as a start offset.
877 return typeof encoding === 'string'
878 ? createBuffer(size).fill(fill, encoding)
879 : createBuffer(size).fill(fill)
880 }
881 return createBuffer(size)
882}
883
884/**
885 * Creates a new filled Buffer instance.
886 * alloc(size[, fill[, encoding]])
887 **/
888Buffer.alloc = function (size, fill, encoding) {
889 return alloc(size, fill, encoding)
890}
891
892function allocUnsafe (size) {
893 assertSize(size)
894 return createBuffer(size < 0 ? 0 : checked(size) | 0)
895}
896
897/**
898 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
899 * */
900Buffer.allocUnsafe = function (size) {
901 return allocUnsafe(size)
902}
903/**
904 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
905 */
906Buffer.allocUnsafeSlow = function (size) {
907 return allocUnsafe(size)
908}
909
910function fromString (string, encoding) {
911 if (typeof encoding !== 'string' || encoding === '') {
912 encoding = 'utf8'
913 }
914
915 if (!Buffer.isEncoding(encoding)) {
916 throw new TypeError('"encoding" must be a valid string encoding')
917 }
918
919 var length = byteLength(string, encoding) | 0
920 var buf = createBuffer(length)
921
922 var actual = buf.write(string, encoding)
923
924 if (actual !== length) {
925 // Writing a hex string, for example, that contains invalid characters will
926 // cause everything after the first invalid character to be ignored. (e.g.
927 // 'abxxcd' will be treated as 'ab')
928 buf = buf.slice(0, actual)
929 }
930
931 return buf
932}
933
934function fromArrayLike (array) {
935 var length = array.length < 0 ? 0 : checked(array.length) | 0
936 var buf = createBuffer(length)
937 for (var i = 0; i < length; i += 1) {
938 buf[i] = array[i] & 255
939 }
940 return buf
941}
942
943function fromArrayBuffer (array, byteOffset, length) {
944 if (byteOffset < 0 || array.byteLength < byteOffset) {
945 throw new RangeError('\'offset\' is out of bounds')
946 }
947
948 if (array.byteLength < byteOffset + (length || 0)) {
949 throw new RangeError('\'length\' is out of bounds')
950 }
951
952 var buf
953 if (byteOffset === undefined && length === undefined) {
954 buf = new Uint8Array(array)
955 } else if (length === undefined) {
956 buf = new Uint8Array(array, byteOffset)
957 } else {
958 buf = new Uint8Array(array, byteOffset, length)
959 }
960
961 // Return an augmented `Uint8Array` instance
962 buf.__proto__ = Buffer.prototype
963 return buf
964}
965
966function fromObject (obj) {
967 if (Buffer.isBuffer(obj)) {
968 var len = checked(obj.length) | 0
969 var buf = createBuffer(len)
970
971 if (buf.length === 0) {
972 return buf
973 }
974
975 obj.copy(buf, 0, 0, len)
976 return buf
977 }
978
979 if (obj) {
980 if (isArrayBufferView(obj) || 'length' in obj) {
981 if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
982 return createBuffer(0)
983 }
984 return fromArrayLike(obj)
985 }
986
987 if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
988 return fromArrayLike(obj.data)
989 }
990 }
991
992 throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
993}
994
995function checked (length) {
996 // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
997 // length is NaN (which is otherwise coerced to zero.)
998 if (length >= K_MAX_LENGTH) {
999 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
1000 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
1001 }
1002 return length | 0
1003}
1004
1005function SlowBuffer (length) {
1006 if (+length != length) { // eslint-disable-line eqeqeq
1007 length = 0
1008 }
1009 return Buffer.alloc(+length)
1010}
1011
1012Buffer.isBuffer = function isBuffer (b) {
1013 return b != null && b._isBuffer === true
1014}
1015
1016Buffer.compare = function compare (a, b) {
1017 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
1018 throw new TypeError('Arguments must be Buffers')
1019 }
1020
1021 if (a === b) return 0
1022
1023 var x = a.length
1024 var y = b.length
1025
1026 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
1027 if (a[i] !== b[i]) {
1028 x = a[i]
1029 y = b[i]
1030 break
1031 }
1032 }
1033
1034 if (x < y) return -1
1035 if (y < x) return 1
1036 return 0
1037}
1038
1039Buffer.isEncoding = function isEncoding (encoding) {
1040 switch (String(encoding).toLowerCase()) {
1041 case 'hex':
1042 case 'utf8':
1043 case 'utf-8':
1044 case 'ascii':
1045 case 'latin1':
1046 case 'binary':
1047 case 'base64':
1048 case 'ucs2':
1049 case 'ucs-2':
1050 case 'utf16le':
1051 case 'utf-16le':
1052 return true
1053 default:
1054 return false
1055 }
1056}
1057
1058Buffer.concat = function concat (list, length) {
1059 if (!Array.isArray(list)) {
1060 throw new TypeError('"list" argument must be an Array of Buffers')
1061 }
1062
1063 if (list.length === 0) {
1064 return Buffer.alloc(0)
1065 }
1066
1067 var i
1068 if (length === undefined) {
1069 length = 0
1070 for (i = 0; i < list.length; ++i) {
1071 length += list[i].length
1072 }
1073 }
1074
1075 var buffer = Buffer.allocUnsafe(length)
1076 var pos = 0
1077 for (i = 0; i < list.length; ++i) {
1078 var buf = list[i]
1079 if (!Buffer.isBuffer(buf)) {
1080 throw new TypeError('"list" argument must be an Array of Buffers')
1081 }
1082 buf.copy(buffer, pos)
1083 pos += buf.length
1084 }
1085 return buffer
1086}
1087
1088function byteLength (string, encoding) {
1089 if (Buffer.isBuffer(string)) {
1090 return string.length
1091 }
1092 if (isArrayBufferView(string) || string instanceof ArrayBuffer) {
1093 return string.byteLength
1094 }
1095 if (typeof string !== 'string') {
1096 string = '' + string
1097 }
1098
1099 var len = string.length
1100 if (len === 0) return 0
1101
1102 // Use a for loop to avoid recursion
1103 var loweredCase = false
1104 for (;;) {
1105 switch (encoding) {
1106 case 'ascii':
1107 case 'latin1':
1108 case 'binary':
1109 return len
1110 case 'utf8':
1111 case 'utf-8':
1112 case undefined:
1113 return utf8ToBytes(string).length
1114 case 'ucs2':
1115 case 'ucs-2':
1116 case 'utf16le':
1117 case 'utf-16le':
1118 return len * 2
1119 case 'hex':
1120 return len >>> 1
1121 case 'base64':
1122 return base64ToBytes(string).length
1123 default:
1124 if (loweredCase) return utf8ToBytes(string).length // assume utf8
1125 encoding = ('' + encoding).toLowerCase()
1126 loweredCase = true
1127 }
1128 }
1129}
1130Buffer.byteLength = byteLength
1131
1132function slowToString (encoding, start, end) {
1133 var loweredCase = false
1134
1135 // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
1136 // property of a typed array.
1137
1138 // This behaves neither like String nor Uint8Array in that we set start/end
1139 // to their upper/lower bounds if the value passed is out of range.
1140 // undefined is handled specially as per ECMA-262 6th Edition,
1141 // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
1142 if (start === undefined || start < 0) {
1143 start = 0
1144 }
1145 // Return early if start > this.length. Done here to prevent potential uint32
1146 // coercion fail below.
1147 if (start > this.length) {
1148 return ''
1149 }
1150
1151 if (end === undefined || end > this.length) {
1152 end = this.length
1153 }
1154
1155 if (end <= 0) {
1156 return ''
1157 }
1158
1159 // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
1160 end >>>= 0
1161 start >>>= 0
1162
1163 if (end <= start) {
1164 return ''
1165 }
1166
1167 if (!encoding) encoding = 'utf8'
1168
1169 while (true) {
1170 switch (encoding) {
1171 case 'hex':
1172 return hexSlice(this, start, end)
1173
1174 case 'utf8':
1175 case 'utf-8':
1176 return utf8Slice(this, start, end)
1177
1178 case 'ascii':
1179 return asciiSlice(this, start, end)
1180
1181 case 'latin1':
1182 case 'binary':
1183 return latin1Slice(this, start, end)
1184
1185 case 'base64':
1186 return base64Slice(this, start, end)
1187
1188 case 'ucs2':
1189 case 'ucs-2':
1190 case 'utf16le':
1191 case 'utf-16le':
1192 return utf16leSlice(this, start, end)
1193
1194 default:
1195 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
1196 encoding = (encoding + '').toLowerCase()
1197 loweredCase = true
1198 }
1199 }
1200}
1201
1202// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
1203// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
1204// reliably in a browserify context because there could be multiple different
1205// copies of the 'buffer' package in use. This method works even for Buffer
1206// instances that were created from another copy of the `buffer` package.
1207// See: https://github.com/feross/buffer/issues/154
1208Buffer.prototype._isBuffer = true
1209
1210function swap (b, n, m) {
1211 var i = b[n]
1212 b[n] = b[m]
1213 b[m] = i
1214}
1215
1216Buffer.prototype.swap16 = function swap16 () {
1217 var len = this.length
1218 if (len % 2 !== 0) {
1219 throw new RangeError('Buffer size must be a multiple of 16-bits')
1220 }
1221 for (var i = 0; i < len; i += 2) {
1222 swap(this, i, i + 1)
1223 }
1224 return this
1225}
1226
1227Buffer.prototype.swap32 = function swap32 () {
1228 var len = this.length
1229 if (len % 4 !== 0) {
1230 throw new RangeError('Buffer size must be a multiple of 32-bits')
1231 }
1232 for (var i = 0; i < len; i += 4) {
1233 swap(this, i, i + 3)
1234 swap(this, i + 1, i + 2)
1235 }
1236 return this
1237}
1238
1239Buffer.prototype.swap64 = function swap64 () {
1240 var len = this.length
1241 if (len % 8 !== 0) {
1242 throw new RangeError('Buffer size must be a multiple of 64-bits')
1243 }
1244 for (var i = 0; i < len; i += 8) {
1245 swap(this, i, i + 7)
1246 swap(this, i + 1, i + 6)
1247 swap(this, i + 2, i + 5)
1248 swap(this, i + 3, i + 4)
1249 }
1250 return this
1251}
1252
1253Buffer.prototype.toString = function toString () {
1254 var length = this.length
1255 if (length === 0) return ''
1256 if (arguments.length === 0) return utf8Slice(this, 0, length)
1257 return slowToString.apply(this, arguments)
1258}
1259
1260Buffer.prototype.equals = function equals (b) {
1261 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
1262 if (this === b) return true
1263 return Buffer.compare(this, b) === 0
1264}
1265
1266Buffer.prototype.inspect = function inspect () {
1267 var str = ''
1268 var max = exports.INSPECT_MAX_BYTES
1269 if (this.length > 0) {
1270 str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
1271 if (this.length > max) str += ' ... '
1272 }
1273 return '<Buffer ' + str + '>'
1274}
1275
1276Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
1277 if (!Buffer.isBuffer(target)) {
1278 throw new TypeError('Argument must be a Buffer')
1279 }
1280
1281 if (start === undefined) {
1282 start = 0
1283 }
1284 if (end === undefined) {
1285 end = target ? target.length : 0
1286 }
1287 if (thisStart === undefined) {
1288 thisStart = 0
1289 }
1290 if (thisEnd === undefined) {
1291 thisEnd = this.length
1292 }
1293
1294 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
1295 throw new RangeError('out of range index')
1296 }
1297
1298 if (thisStart >= thisEnd && start >= end) {
1299 return 0
1300 }
1301 if (thisStart >= thisEnd) {
1302 return -1
1303 }
1304 if (start >= end) {
1305 return 1
1306 }
1307
1308 start >>>= 0
1309 end >>>= 0
1310 thisStart >>>= 0
1311 thisEnd >>>= 0
1312
1313 if (this === target) return 0
1314
1315 var x = thisEnd - thisStart
1316 var y = end - start
1317 var len = Math.min(x, y)
1318
1319 var thisCopy = this.slice(thisStart, thisEnd)
1320 var targetCopy = target.slice(start, end)
1321
1322 for (var i = 0; i < len; ++i) {
1323 if (thisCopy[i] !== targetCopy[i]) {
1324 x = thisCopy[i]
1325 y = targetCopy[i]
1326 break
1327 }
1328 }
1329
1330 if (x < y) return -1
1331 if (y < x) return 1
1332 return 0
1333}
1334
1335// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
1336// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
1337//
1338// Arguments:
1339// - buffer - a Buffer to search
1340// - val - a string, Buffer, or number
1341// - byteOffset - an index into `buffer`; will be clamped to an int32
1342// - encoding - an optional encoding, relevant is val is a string
1343// - dir - true for indexOf, false for lastIndexOf
1344function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
1345 // Empty buffer means no match
1346 if (buffer.length === 0) return -1
1347
1348 // Normalize byteOffset
1349 if (typeof byteOffset === 'string') {
1350 encoding = byteOffset
1351 byteOffset = 0
1352 } else if (byteOffset > 0x7fffffff) {
1353 byteOffset = 0x7fffffff
1354 } else if (byteOffset < -0x80000000) {
1355 byteOffset = -0x80000000
1356 }
1357 byteOffset = +byteOffset // Coerce to Number.
1358 if (numberIsNaN(byteOffset)) {
1359 // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
1360 byteOffset = dir ? 0 : (buffer.length - 1)
1361 }
1362
1363 // Normalize byteOffset: negative offsets start from the end of the buffer
1364 if (byteOffset < 0) byteOffset = buffer.length + byteOffset
1365 if (byteOffset >= buffer.length) {
1366 if (dir) return -1
1367 else byteOffset = buffer.length - 1
1368 } else if (byteOffset < 0) {
1369 if (dir) byteOffset = 0
1370 else return -1
1371 }
1372
1373 // Normalize val
1374 if (typeof val === 'string') {
1375 val = Buffer.from(val, encoding)
1376 }
1377
1378 // Finally, search either indexOf (if dir is true) or lastIndexOf
1379 if (Buffer.isBuffer(val)) {
1380 // Special case: looking for empty string/buffer always fails
1381 if (val.length === 0) {
1382 return -1
1383 }
1384 return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
1385 } else if (typeof val === 'number') {
1386 val = val & 0xFF // Search for a byte value [0-255]
1387 if (typeof Uint8Array.prototype.indexOf === 'function') {
1388 if (dir) {
1389 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
1390 } else {
1391 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
1392 }
1393 }
1394 return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
1395 }
1396
1397 throw new TypeError('val must be string, number or Buffer')
1398}
1399
1400function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
1401 var indexSize = 1
1402 var arrLength = arr.length
1403 var valLength = val.length
1404
1405 if (encoding !== undefined) {
1406 encoding = String(encoding).toLowerCase()
1407 if (encoding === 'ucs2' || encoding === 'ucs-2' ||
1408 encoding === 'utf16le' || encoding === 'utf-16le') {
1409 if (arr.length < 2 || val.length < 2) {
1410 return -1
1411 }
1412 indexSize = 2
1413 arrLength /= 2
1414 valLength /= 2
1415 byteOffset /= 2
1416 }
1417 }
1418
1419 function read (buf, i) {
1420 if (indexSize === 1) {
1421 return buf[i]
1422 } else {
1423 return buf.readUInt16BE(i * indexSize)
1424 }
1425 }
1426
1427 var i
1428 if (dir) {
1429 var foundIndex = -1
1430 for (i = byteOffset; i < arrLength; i++) {
1431 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
1432 if (foundIndex === -1) foundIndex = i
1433 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
1434 } else {
1435 if (foundIndex !== -1) i -= i - foundIndex
1436 foundIndex = -1
1437 }
1438 }
1439 } else {
1440 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
1441 for (i = byteOffset; i >= 0; i--) {
1442 var found = true
1443 for (var j = 0; j < valLength; j++) {
1444 if (read(arr, i + j) !== read(val, j)) {
1445 found = false
1446 break
1447 }
1448 }
1449 if (found) return i
1450 }
1451 }
1452
1453 return -1
1454}
1455
1456Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
1457 return this.indexOf(val, byteOffset, encoding) !== -1
1458}
1459
1460Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
1461 return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
1462}
1463
1464Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
1465 return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
1466}
1467
1468function hexWrite (buf, string, offset, length) {
1469 offset = Number(offset) || 0
1470 var remaining = buf.length - offset
1471 if (!length) {
1472 length = remaining
1473 } else {
1474 length = Number(length)
1475 if (length > remaining) {
1476 length = remaining
1477 }
1478 }
1479
1480 // must be an even number of digits
1481 var strLen = string.length
1482 if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
1483
1484 if (length > strLen / 2) {
1485 length = strLen / 2
1486 }
1487 for (var i = 0; i < length; ++i) {
1488 var parsed = parseInt(string.substr(i * 2, 2), 16)
1489 if (numberIsNaN(parsed)) return i
1490 buf[offset + i] = parsed
1491 }
1492 return i
1493}
1494
1495function utf8Write (buf, string, offset, length) {
1496 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
1497}
1498
1499function asciiWrite (buf, string, offset, length) {
1500 return blitBuffer(asciiToBytes(string), buf, offset, length)
1501}
1502
1503function latin1Write (buf, string, offset, length) {
1504 return asciiWrite(buf, string, offset, length)
1505}
1506
1507function base64Write (buf, string, offset, length) {
1508 return blitBuffer(base64ToBytes(string), buf, offset, length)
1509}
1510
1511function ucs2Write (buf, string, offset, length) {
1512 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
1513}
1514
1515Buffer.prototype.write = function write (string, offset, length, encoding) {
1516 // Buffer#write(string)
1517 if (offset === undefined) {
1518 encoding = 'utf8'
1519 length = this.length
1520 offset = 0
1521 // Buffer#write(string, encoding)
1522 } else if (length === undefined && typeof offset === 'string') {
1523 encoding = offset
1524 length = this.length
1525 offset = 0
1526 // Buffer#write(string, offset[, length][, encoding])
1527 } else if (isFinite(offset)) {
1528 offset = offset >>> 0
1529 if (isFinite(length)) {
1530 length = length >>> 0
1531 if (encoding === undefined) encoding = 'utf8'
1532 } else {
1533 encoding = length
1534 length = undefined
1535 }
1536 } else {
1537 throw new Error(
1538 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
1539 )
1540 }
1541
1542 var remaining = this.length - offset
1543 if (length === undefined || length > remaining) length = remaining
1544
1545 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
1546 throw new RangeError('Attempt to write outside buffer bounds')
1547 }
1548
1549 if (!encoding) encoding = 'utf8'
1550
1551 var loweredCase = false
1552 for (;;) {
1553 switch (encoding) {
1554 case 'hex':
1555 return hexWrite(this, string, offset, length)
1556
1557 case 'utf8':
1558 case 'utf-8':
1559 return utf8Write(this, string, offset, length)
1560
1561 case 'ascii':
1562 return asciiWrite(this, string, offset, length)
1563
1564 case 'latin1':
1565 case 'binary':
1566 return latin1Write(this, string, offset, length)
1567
1568 case 'base64':
1569 // Warning: maxLength not taken into account in base64Write
1570 return base64Write(this, string, offset, length)
1571
1572 case 'ucs2':
1573 case 'ucs-2':
1574 case 'utf16le':
1575 case 'utf-16le':
1576 return ucs2Write(this, string, offset, length)
1577
1578 default:
1579 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
1580 encoding = ('' + encoding).toLowerCase()
1581 loweredCase = true
1582 }
1583 }
1584}
1585
1586Buffer.prototype.toJSON = function toJSON () {
1587 return {
1588 type: 'Buffer',
1589 data: Array.prototype.slice.call(this._arr || this, 0)
1590 }
1591}
1592
1593function base64Slice (buf, start, end) {
1594 if (start === 0 && end === buf.length) {
1595 return base64.fromByteArray(buf)
1596 } else {
1597 return base64.fromByteArray(buf.slice(start, end))
1598 }
1599}
1600
1601function utf8Slice (buf, start, end) {
1602 end = Math.min(buf.length, end)
1603 var res = []
1604
1605 var i = start
1606 while (i < end) {
1607 var firstByte = buf[i]
1608 var codePoint = null
1609 var bytesPerSequence = (firstByte > 0xEF) ? 4
1610 : (firstByte > 0xDF) ? 3
1611 : (firstByte > 0xBF) ? 2
1612 : 1
1613
1614 if (i + bytesPerSequence <= end) {
1615 var secondByte, thirdByte, fourthByte, tempCodePoint
1616
1617 switch (bytesPerSequence) {
1618 case 1:
1619 if (firstByte < 0x80) {
1620 codePoint = firstByte
1621 }
1622 break
1623 case 2:
1624 secondByte = buf[i + 1]
1625 if ((secondByte & 0xC0) === 0x80) {
1626 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
1627 if (tempCodePoint > 0x7F) {
1628 codePoint = tempCodePoint
1629 }
1630 }
1631 break
1632 case 3:
1633 secondByte = buf[i + 1]
1634 thirdByte = buf[i + 2]
1635 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
1636 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
1637 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
1638 codePoint = tempCodePoint
1639 }
1640 }
1641 break
1642 case 4:
1643 secondByte = buf[i + 1]
1644 thirdByte = buf[i + 2]
1645 fourthByte = buf[i + 3]
1646 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
1647 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
1648 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
1649 codePoint = tempCodePoint
1650 }
1651 }
1652 }
1653 }
1654
1655 if (codePoint === null) {
1656 // we did not generate a valid codePoint so insert a
1657 // replacement char (U+FFFD) and advance only 1 byte
1658 codePoint = 0xFFFD
1659 bytesPerSequence = 1
1660 } else if (codePoint > 0xFFFF) {
1661 // encode to utf16 (surrogate pair dance)
1662 codePoint -= 0x10000
1663 res.push(codePoint >>> 10 & 0x3FF | 0xD800)
1664 codePoint = 0xDC00 | codePoint & 0x3FF
1665 }
1666
1667 res.push(codePoint)
1668 i += bytesPerSequence
1669 }
1670
1671 return decodeCodePointsArray(res)
1672}
1673
1674// Based on http://stackoverflow.com/a/22747272/680742, the browser with
1675// the lowest limit is Chrome, with 0x10000 args.
1676// We go 1 magnitude less, for safety
1677var MAX_ARGUMENTS_LENGTH = 0x1000
1678
1679function decodeCodePointsArray (codePoints) {
1680 var len = codePoints.length
1681 if (len <= MAX_ARGUMENTS_LENGTH) {
1682 return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
1683 }
1684
1685 // Decode in chunks to avoid "call stack size exceeded".
1686 var res = ''
1687 var i = 0
1688 while (i < len) {
1689 res += String.fromCharCode.apply(
1690 String,
1691 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
1692 )
1693 }
1694 return res
1695}
1696
1697function asciiSlice (buf, start, end) {
1698 var ret = ''
1699 end = Math.min(buf.length, end)
1700
1701 for (var i = start; i < end; ++i) {
1702 ret += String.fromCharCode(buf[i] & 0x7F)
1703 }
1704 return ret
1705}
1706
1707function latin1Slice (buf, start, end) {
1708 var ret = ''
1709 end = Math.min(buf.length, end)
1710
1711 for (var i = start; i < end; ++i) {
1712 ret += String.fromCharCode(buf[i])
1713 }
1714 return ret
1715}
1716
1717function hexSlice (buf, start, end) {
1718 var len = buf.length
1719
1720 if (!start || start < 0) start = 0
1721 if (!end || end < 0 || end > len) end = len
1722
1723 var out = ''
1724 for (var i = start; i < end; ++i) {
1725 out += toHex(buf[i])
1726 }
1727 return out
1728}
1729
1730function utf16leSlice (buf, start, end) {
1731 var bytes = buf.slice(start, end)
1732 var res = ''
1733 for (var i = 0; i < bytes.length; i += 2) {
1734 res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
1735 }
1736 return res
1737}
1738
1739Buffer.prototype.slice = function slice (start, end) {
1740 var len = this.length
1741 start = ~~start
1742 end = end === undefined ? len : ~~end
1743
1744 if (start < 0) {
1745 start += len
1746 if (start < 0) start = 0
1747 } else if (start > len) {
1748 start = len
1749 }
1750
1751 if (end < 0) {
1752 end += len
1753 if (end < 0) end = 0
1754 } else if (end > len) {
1755 end = len
1756 }
1757
1758 if (end < start) end = start
1759
1760 var newBuf = this.subarray(start, end)
1761 // Return an augmented `Uint8Array` instance
1762 newBuf.__proto__ = Buffer.prototype
1763 return newBuf
1764}
1765
1766/*
1767 * Need to make sure that buffer isn't trying to write out of bounds.
1768 */
1769function checkOffset (offset, ext, length) {
1770 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
1771 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
1772}
1773
1774Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
1775 offset = offset >>> 0
1776 byteLength = byteLength >>> 0
1777 if (!noAssert) checkOffset(offset, byteLength, this.length)
1778
1779 var val = this[offset]
1780 var mul = 1
1781 var i = 0
1782 while (++i < byteLength && (mul *= 0x100)) {
1783 val += this[offset + i] * mul
1784 }
1785
1786 return val
1787}
1788
1789Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
1790 offset = offset >>> 0
1791 byteLength = byteLength >>> 0
1792 if (!noAssert) {
1793 checkOffset(offset, byteLength, this.length)
1794 }
1795
1796 var val = this[offset + --byteLength]
1797 var mul = 1
1798 while (byteLength > 0 && (mul *= 0x100)) {
1799 val += this[offset + --byteLength] * mul
1800 }
1801
1802 return val
1803}
1804
1805Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
1806 offset = offset >>> 0
1807 if (!noAssert) checkOffset(offset, 1, this.length)
1808 return this[offset]
1809}
1810
1811Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
1812 offset = offset >>> 0
1813 if (!noAssert) checkOffset(offset, 2, this.length)
1814 return this[offset] | (this[offset + 1] << 8)
1815}
1816
1817Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
1818 offset = offset >>> 0
1819 if (!noAssert) checkOffset(offset, 2, this.length)
1820 return (this[offset] << 8) | this[offset + 1]
1821}
1822
1823Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
1824 offset = offset >>> 0
1825 if (!noAssert) checkOffset(offset, 4, this.length)
1826
1827 return ((this[offset]) |
1828 (this[offset + 1] << 8) |
1829 (this[offset + 2] << 16)) +
1830 (this[offset + 3] * 0x1000000)
1831}
1832
1833Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
1834 offset = offset >>> 0
1835 if (!noAssert) checkOffset(offset, 4, this.length)
1836
1837 return (this[offset] * 0x1000000) +
1838 ((this[offset + 1] << 16) |
1839 (this[offset + 2] << 8) |
1840 this[offset + 3])
1841}
1842
1843Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
1844 offset = offset >>> 0
1845 byteLength = byteLength >>> 0
1846 if (!noAssert) checkOffset(offset, byteLength, this.length)
1847
1848 var val = this[offset]
1849 var mul = 1
1850 var i = 0
1851 while (++i < byteLength && (mul *= 0x100)) {
1852 val += this[offset + i] * mul
1853 }
1854 mul *= 0x80
1855
1856 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
1857
1858 return val
1859}
1860
1861Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
1862 offset = offset >>> 0
1863 byteLength = byteLength >>> 0
1864 if (!noAssert) checkOffset(offset, byteLength, this.length)
1865
1866 var i = byteLength
1867 var mul = 1
1868 var val = this[offset + --i]
1869 while (i > 0 && (mul *= 0x100)) {
1870 val += this[offset + --i] * mul
1871 }
1872 mul *= 0x80
1873
1874 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
1875
1876 return val
1877}
1878
1879Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
1880 offset = offset >>> 0
1881 if (!noAssert) checkOffset(offset, 1, this.length)
1882 if (!(this[offset] & 0x80)) return (this[offset])
1883 return ((0xff - this[offset] + 1) * -1)
1884}
1885
1886Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
1887 offset = offset >>> 0
1888 if (!noAssert) checkOffset(offset, 2, this.length)
1889 var val = this[offset] | (this[offset + 1] << 8)
1890 return (val & 0x8000) ? val | 0xFFFF0000 : val
1891}
1892
1893Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
1894 offset = offset >>> 0
1895 if (!noAssert) checkOffset(offset, 2, this.length)
1896 var val = this[offset + 1] | (this[offset] << 8)
1897 return (val & 0x8000) ? val | 0xFFFF0000 : val
1898}
1899
1900Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
1901 offset = offset >>> 0
1902 if (!noAssert) checkOffset(offset, 4, this.length)
1903
1904 return (this[offset]) |
1905 (this[offset + 1] << 8) |
1906 (this[offset + 2] << 16) |
1907 (this[offset + 3] << 24)
1908}
1909
1910Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
1911 offset = offset >>> 0
1912 if (!noAssert) checkOffset(offset, 4, this.length)
1913
1914 return (this[offset] << 24) |
1915 (this[offset + 1] << 16) |
1916 (this[offset + 2] << 8) |
1917 (this[offset + 3])
1918}
1919
1920Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
1921 offset = offset >>> 0
1922 if (!noAssert) checkOffset(offset, 4, this.length)
1923 return ieee754.read(this, offset, true, 23, 4)
1924}
1925
1926Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
1927 offset = offset >>> 0
1928 if (!noAssert) checkOffset(offset, 4, this.length)
1929 return ieee754.read(this, offset, false, 23, 4)
1930}
1931
1932Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
1933 offset = offset >>> 0
1934 if (!noAssert) checkOffset(offset, 8, this.length)
1935 return ieee754.read(this, offset, true, 52, 8)
1936}
1937
1938Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
1939 offset = offset >>> 0
1940 if (!noAssert) checkOffset(offset, 8, this.length)
1941 return ieee754.read(this, offset, false, 52, 8)
1942}
1943
1944function checkInt (buf, value, offset, ext, max, min) {
1945 if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
1946 if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
1947 if (offset + ext > buf.length) throw new RangeError('Index out of range')
1948}
1949
1950Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
1951 value = +value
1952 offset = offset >>> 0
1953 byteLength = byteLength >>> 0
1954 if (!noAssert) {
1955 var maxBytes = Math.pow(2, 8 * byteLength) - 1
1956 checkInt(this, value, offset, byteLength, maxBytes, 0)
1957 }
1958
1959 var mul = 1
1960 var i = 0
1961 this[offset] = value & 0xFF
1962 while (++i < byteLength && (mul *= 0x100)) {
1963 this[offset + i] = (value / mul) & 0xFF
1964 }
1965
1966 return offset + byteLength
1967}
1968
1969Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
1970 value = +value
1971 offset = offset >>> 0
1972 byteLength = byteLength >>> 0
1973 if (!noAssert) {
1974 var maxBytes = Math.pow(2, 8 * byteLength) - 1
1975 checkInt(this, value, offset, byteLength, maxBytes, 0)
1976 }
1977
1978 var i = byteLength - 1
1979 var mul = 1
1980 this[offset + i] = value & 0xFF
1981 while (--i >= 0 && (mul *= 0x100)) {
1982 this[offset + i] = (value / mul) & 0xFF
1983 }
1984
1985 return offset + byteLength
1986}
1987
1988Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
1989 value = +value
1990 offset = offset >>> 0
1991 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
1992 this[offset] = (value & 0xff)
1993 return offset + 1
1994}
1995
1996Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
1997 value = +value
1998 offset = offset >>> 0
1999 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
2000 this[offset] = (value & 0xff)
2001 this[offset + 1] = (value >>> 8)
2002 return offset + 2
2003}
2004
2005Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
2006 value = +value
2007 offset = offset >>> 0
2008 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
2009 this[offset] = (value >>> 8)
2010 this[offset + 1] = (value & 0xff)
2011 return offset + 2
2012}
2013
2014Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
2015 value = +value
2016 offset = offset >>> 0
2017 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
2018 this[offset + 3] = (value >>> 24)
2019 this[offset + 2] = (value >>> 16)
2020 this[offset + 1] = (value >>> 8)
2021 this[offset] = (value & 0xff)
2022 return offset + 4
2023}
2024
2025Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
2026 value = +value
2027 offset = offset >>> 0
2028 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
2029 this[offset] = (value >>> 24)
2030 this[offset + 1] = (value >>> 16)
2031 this[offset + 2] = (value >>> 8)
2032 this[offset + 3] = (value & 0xff)
2033 return offset + 4
2034}
2035
2036Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
2037 value = +value
2038 offset = offset >>> 0
2039 if (!noAssert) {
2040 var limit = Math.pow(2, (8 * byteLength) - 1)
2041
2042 checkInt(this, value, offset, byteLength, limit - 1, -limit)
2043 }
2044
2045 var i = 0
2046 var mul = 1
2047 var sub = 0
2048 this[offset] = value & 0xFF
2049 while (++i < byteLength && (mul *= 0x100)) {
2050 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
2051 sub = 1
2052 }
2053 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
2054 }
2055
2056 return offset + byteLength
2057}
2058
2059Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
2060 value = +value
2061 offset = offset >>> 0
2062 if (!noAssert) {
2063 var limit = Math.pow(2, (8 * byteLength) - 1)
2064
2065 checkInt(this, value, offset, byteLength, limit - 1, -limit)
2066 }
2067
2068 var i = byteLength - 1
2069 var mul = 1
2070 var sub = 0
2071 this[offset + i] = value & 0xFF
2072 while (--i >= 0 && (mul *= 0x100)) {
2073 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
2074 sub = 1
2075 }
2076 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
2077 }
2078
2079 return offset + byteLength
2080}
2081
2082Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
2083 value = +value
2084 offset = offset >>> 0
2085 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
2086 if (value < 0) value = 0xff + value + 1
2087 this[offset] = (value & 0xff)
2088 return offset + 1
2089}
2090
2091Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
2092 value = +value
2093 offset = offset >>> 0
2094 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
2095 this[offset] = (value & 0xff)
2096 this[offset + 1] = (value >>> 8)
2097 return offset + 2
2098}
2099
2100Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
2101 value = +value
2102 offset = offset >>> 0
2103 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
2104 this[offset] = (value >>> 8)
2105 this[offset + 1] = (value & 0xff)
2106 return offset + 2
2107}
2108
2109Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
2110 value = +value
2111 offset = offset >>> 0
2112 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
2113 this[offset] = (value & 0xff)
2114 this[offset + 1] = (value >>> 8)
2115 this[offset + 2] = (value >>> 16)
2116 this[offset + 3] = (value >>> 24)
2117 return offset + 4
2118}
2119
2120Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
2121 value = +value
2122 offset = offset >>> 0
2123 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
2124 if (value < 0) value = 0xffffffff + value + 1
2125 this[offset] = (value >>> 24)
2126 this[offset + 1] = (value >>> 16)
2127 this[offset + 2] = (value >>> 8)
2128 this[offset + 3] = (value & 0xff)
2129 return offset + 4
2130}
2131
2132function checkIEEE754 (buf, value, offset, ext, max, min) {
2133 if (offset + ext > buf.length) throw new RangeError('Index out of range')
2134 if (offset < 0) throw new RangeError('Index out of range')
2135}
2136
2137function writeFloat (buf, value, offset, littleEndian, noAssert) {
2138 value = +value
2139 offset = offset >>> 0
2140 if (!noAssert) {
2141 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
2142 }
2143 ieee754.write(buf, value, offset, littleEndian, 23, 4)
2144 return offset + 4
2145}
2146
2147Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
2148 return writeFloat(this, value, offset, true, noAssert)
2149}
2150
2151Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
2152 return writeFloat(this, value, offset, false, noAssert)
2153}
2154
2155function writeDouble (buf, value, offset, littleEndian, noAssert) {
2156 value = +value
2157 offset = offset >>> 0
2158 if (!noAssert) {
2159 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
2160 }
2161 ieee754.write(buf, value, offset, littleEndian, 52, 8)
2162 return offset + 8
2163}
2164
2165Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
2166 return writeDouble(this, value, offset, true, noAssert)
2167}
2168
2169Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
2170 return writeDouble(this, value, offset, false, noAssert)
2171}
2172
2173// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
2174Buffer.prototype.copy = function copy (target, targetStart, start, end) {
2175 if (!start) start = 0
2176 if (!end && end !== 0) end = this.length
2177 if (targetStart >= target.length) targetStart = target.length
2178 if (!targetStart) targetStart = 0
2179 if (end > 0 && end < start) end = start
2180
2181 // Copy 0 bytes; we're done
2182 if (end === start) return 0
2183 if (target.length === 0 || this.length === 0) return 0
2184
2185 // Fatal error conditions
2186 if (targetStart < 0) {
2187 throw new RangeError('targetStart out of bounds')
2188 }
2189 if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
2190 if (end < 0) throw new RangeError('sourceEnd out of bounds')
2191
2192 // Are we oob?
2193 if (end > this.length) end = this.length
2194 if (target.length - targetStart < end - start) {
2195 end = target.length - targetStart + start
2196 }
2197
2198 var len = end - start
2199 var i
2200
2201 if (this === target && start < targetStart && targetStart < end) {
2202 // descending copy from end
2203 for (i = len - 1; i >= 0; --i) {
2204 target[i + targetStart] = this[i + start]
2205 }
2206 } else if (len < 1000) {
2207 // ascending copy from start
2208 for (i = 0; i < len; ++i) {
2209 target[i + targetStart] = this[i + start]
2210 }
2211 } else {
2212 Uint8Array.prototype.set.call(
2213 target,
2214 this.subarray(start, start + len),
2215 targetStart
2216 )
2217 }
2218
2219 return len
2220}
2221
2222// Usage:
2223// buffer.fill(number[, offset[, end]])
2224// buffer.fill(buffer[, offset[, end]])
2225// buffer.fill(string[, offset[, end]][, encoding])
2226Buffer.prototype.fill = function fill (val, start, end, encoding) {
2227 // Handle string cases:
2228 if (typeof val === 'string') {
2229 if (typeof start === 'string') {
2230 encoding = start
2231 start = 0
2232 end = this.length
2233 } else if (typeof end === 'string') {
2234 encoding = end
2235 end = this.length
2236 }
2237 if (val.length === 1) {
2238 var code = val.charCodeAt(0)
2239 if (code < 256) {
2240 val = code
2241 }
2242 }
2243 if (encoding !== undefined && typeof encoding !== 'string') {
2244 throw new TypeError('encoding must be a string')
2245 }
2246 if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
2247 throw new TypeError('Unknown encoding: ' + encoding)
2248 }
2249 } else if (typeof val === 'number') {
2250 val = val & 255
2251 }
2252
2253 // Invalid ranges are not set to a default, so can range check early.
2254 if (start < 0 || this.length < start || this.length < end) {
2255 throw new RangeError('Out of range index')
2256 }
2257
2258 if (end <= start) {
2259 return this
2260 }
2261
2262 start = start >>> 0
2263 end = end === undefined ? this.length : end >>> 0
2264
2265 if (!val) val = 0
2266
2267 var i
2268 if (typeof val === 'number') {
2269 for (i = start; i < end; ++i) {
2270 this[i] = val
2271 }
2272 } else {
2273 var bytes = Buffer.isBuffer(val)
2274 ? val
2275 : new Buffer(val, encoding)
2276 var len = bytes.length
2277 for (i = 0; i < end - start; ++i) {
2278 this[i + start] = bytes[i % len]
2279 }
2280 }
2281
2282 return this
2283}
2284
2285// HELPER FUNCTIONS
2286// ================
2287
2288var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
2289
2290function base64clean (str) {
2291 // Node strips out invalid characters like \n and \t from the string, base64-js does not
2292 str = str.trim().replace(INVALID_BASE64_RE, '')
2293 // Node converts strings with length < 2 to ''
2294 if (str.length < 2) return ''
2295 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
2296 while (str.length % 4 !== 0) {
2297 str = str + '='
2298 }
2299 return str
2300}
2301
2302function toHex (n) {
2303 if (n < 16) return '0' + n.toString(16)
2304 return n.toString(16)
2305}
2306
2307function utf8ToBytes (string, units) {
2308 units = units || Infinity
2309 var codePoint
2310 var length = string.length
2311 var leadSurrogate = null
2312 var bytes = []
2313
2314 for (var i = 0; i < length; ++i) {
2315 codePoint = string.charCodeAt(i)
2316
2317 // is surrogate component
2318 if (codePoint > 0xD7FF && codePoint < 0xE000) {
2319 // last char was a lead
2320 if (!leadSurrogate) {
2321 // no lead yet
2322 if (codePoint > 0xDBFF) {
2323 // unexpected trail
2324 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2325 continue
2326 } else if (i + 1 === length) {
2327 // unpaired lead
2328 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2329 continue
2330 }
2331
2332 // valid lead
2333 leadSurrogate = codePoint
2334
2335 continue
2336 }
2337
2338 // 2 leads in a row
2339 if (codePoint < 0xDC00) {
2340 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2341 leadSurrogate = codePoint
2342 continue
2343 }
2344
2345 // valid surrogate pair
2346 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
2347 } else if (leadSurrogate) {
2348 // valid bmp char, but last char was a lead
2349 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2350 }
2351
2352 leadSurrogate = null
2353
2354 // encode utf8
2355 if (codePoint < 0x80) {
2356 if ((units -= 1) < 0) break
2357 bytes.push(codePoint)
2358 } else if (codePoint < 0x800) {
2359 if ((units -= 2) < 0) break
2360 bytes.push(
2361 codePoint >> 0x6 | 0xC0,
2362 codePoint & 0x3F | 0x80
2363 )
2364 } else if (codePoint < 0x10000) {
2365 if ((units -= 3) < 0) break
2366 bytes.push(
2367 codePoint >> 0xC | 0xE0,
2368 codePoint >> 0x6 & 0x3F | 0x80,
2369 codePoint & 0x3F | 0x80
2370 )
2371 } else if (codePoint < 0x110000) {
2372 if ((units -= 4) < 0) break
2373 bytes.push(
2374 codePoint >> 0x12 | 0xF0,
2375 codePoint >> 0xC & 0x3F | 0x80,
2376 codePoint >> 0x6 & 0x3F | 0x80,
2377 codePoint & 0x3F | 0x80
2378 )
2379 } else {
2380 throw new Error('Invalid code point')
2381 }
2382 }
2383
2384 return bytes
2385}
2386
2387function asciiToBytes (str) {
2388 var byteArray = []
2389 for (var i = 0; i < str.length; ++i) {
2390 // Node's code seems to be doing this and not & 0x7F..
2391 byteArray.push(str.charCodeAt(i) & 0xFF)
2392 }
2393 return byteArray
2394}
2395
2396function utf16leToBytes (str, units) {
2397 var c, hi, lo
2398 var byteArray = []
2399 for (var i = 0; i < str.length; ++i) {
2400 if ((units -= 2) < 0) break
2401
2402 c = str.charCodeAt(i)
2403 hi = c >> 8
2404 lo = c % 256
2405 byteArray.push(lo)
2406 byteArray.push(hi)
2407 }
2408
2409 return byteArray
2410}
2411
2412function base64ToBytes (str) {
2413 return base64.toByteArray(base64clean(str))
2414}
2415
2416function blitBuffer (src, dst, offset, length) {
2417 for (var i = 0; i < length; ++i) {
2418 if ((i + offset >= dst.length) || (i >= src.length)) break
2419 dst[i + offset] = src[i]
2420 }
2421 return i
2422}
2423
2424// Node 0.10 supports `ArrayBuffer` but lacks `ArrayBuffer.isView`
2425function isArrayBufferView (obj) {
2426 return (typeof ArrayBuffer.isView === 'function') && ArrayBuffer.isView(obj)
2427}
2428
2429function numberIsNaN (obj) {
2430 return obj !== obj // eslint-disable-line no-self-compare
2431}
2432
2433},{"base64-js":2,"ieee754":8}],6:[function(require,module,exports){
2434(function (Buffer){
2435// Copyright Joyent, Inc. and other Node contributors.
2436//
2437// Permission is hereby granted, free of charge, to any person obtaining a
2438// copy of this software and associated documentation files (the
2439// "Software"), to deal in the Software without restriction, including
2440// without limitation the rights to use, copy, modify, merge, publish,
2441// distribute, sublicense, and/or sell copies of the Software, and to permit
2442// persons to whom the Software is furnished to do so, subject to the
2443// following conditions:
2444//
2445// The above copyright notice and this permission notice shall be included
2446// in all copies or substantial portions of the Software.
2447//
2448// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
2449// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
2450// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
2451// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
2452// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
2453// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
2454// USE OR OTHER DEALINGS IN THE SOFTWARE.
2455
2456// NOTE: These type checking functions intentionally don't use `instanceof`
2457// because it is fragile and can be easily faked with `Object.create()`.
2458
2459function isArray(arg) {
2460 if (Array.isArray) {
2461 return Array.isArray(arg);
2462 }
2463 return objectToString(arg) === '[object Array]';
2464}
2465exports.isArray = isArray;
2466
2467function isBoolean(arg) {
2468 return typeof arg === 'boolean';
2469}
2470exports.isBoolean = isBoolean;
2471
2472function isNull(arg) {
2473 return arg === null;
2474}
2475exports.isNull = isNull;
2476
2477function isNullOrUndefined(arg) {
2478 return arg == null;
2479}
2480exports.isNullOrUndefined = isNullOrUndefined;
2481
2482function isNumber(arg) {
2483 return typeof arg === 'number';
2484}
2485exports.isNumber = isNumber;
2486
2487function isString(arg) {
2488 return typeof arg === 'string';
2489}
2490exports.isString = isString;
2491
2492function isSymbol(arg) {
2493 return typeof arg === 'symbol';
2494}
2495exports.isSymbol = isSymbol;
2496
2497function isUndefined(arg) {
2498 return arg === void 0;
2499}
2500exports.isUndefined = isUndefined;
2501
2502function isRegExp(re) {
2503 return objectToString(re) === '[object RegExp]';
2504}
2505exports.isRegExp = isRegExp;
2506
2507function isObject(arg) {
2508 return typeof arg === 'object' && arg !== null;
2509}
2510exports.isObject = isObject;
2511
2512function isDate(d) {
2513 return objectToString(d) === '[object Date]';
2514}
2515exports.isDate = isDate;
2516
2517function isError(e) {
2518 return (objectToString(e) === '[object Error]' || e instanceof Error);
2519}
2520exports.isError = isError;
2521
2522function isFunction(arg) {
2523 return typeof arg === 'function';
2524}
2525exports.isFunction = isFunction;
2526
2527function isPrimitive(arg) {
2528 return arg === null ||
2529 typeof arg === 'boolean' ||
2530 typeof arg === 'number' ||
2531 typeof arg === 'string' ||
2532 typeof arg === 'symbol' || // ES6 symbol
2533 typeof arg === 'undefined';
2534}
2535exports.isPrimitive = isPrimitive;
2536
2537exports.isBuffer = Buffer.isBuffer;
2538
2539function objectToString(o) {
2540 return Object.prototype.toString.call(o);
2541}
2542
2543}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
2544},{"../../is-buffer/index.js":10}],7:[function(require,module,exports){
2545// Copyright Joyent, Inc. and other Node contributors.
2546//
2547// Permission is hereby granted, free of charge, to any person obtaining a
2548// copy of this software and associated documentation files (the
2549// "Software"), to deal in the Software without restriction, including
2550// without limitation the rights to use, copy, modify, merge, publish,
2551// distribute, sublicense, and/or sell copies of the Software, and to permit
2552// persons to whom the Software is furnished to do so, subject to the
2553// following conditions:
2554//
2555// The above copyright notice and this permission notice shall be included
2556// in all copies or substantial portions of the Software.
2557//
2558// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
2559// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
2560// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
2561// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
2562// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
2563// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
2564// USE OR OTHER DEALINGS IN THE SOFTWARE.
2565
2566function EventEmitter() {
2567 this._events = this._events || {};
2568 this._maxListeners = this._maxListeners || undefined;
2569}
2570module.exports = EventEmitter;
2571
2572// Backwards-compat with node 0.10.x
2573EventEmitter.EventEmitter = EventEmitter;
2574
2575EventEmitter.prototype._events = undefined;
2576EventEmitter.prototype._maxListeners = undefined;
2577
2578// By default EventEmitters will print a warning if more than 10 listeners are
2579// added to it. This is a useful default which helps finding memory leaks.
2580EventEmitter.defaultMaxListeners = 10;
2581
2582// Obviously not all Emitters should be limited to 10. This function allows
2583// that to be increased. Set to zero for unlimited.
2584EventEmitter.prototype.setMaxListeners = function(n) {
2585 if (!isNumber(n) || n < 0 || isNaN(n))
2586 throw TypeError('n must be a positive number');
2587 this._maxListeners = n;
2588 return this;
2589};
2590
2591EventEmitter.prototype.emit = function(type) {
2592 var er, handler, len, args, i, listeners;
2593
2594 if (!this._events)
2595 this._events = {};
2596
2597 // If there is no 'error' event listener then throw.
2598 if (type === 'error') {
2599 if (!this._events.error ||
2600 (isObject(this._events.error) && !this._events.error.length)) {
2601 er = arguments[1];
2602 if (er instanceof Error) {
2603 throw er; // Unhandled 'error' event
2604 } else {
2605 // At least give some kind of context to the user
2606 var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
2607 err.context = er;
2608 throw err;
2609 }
2610 }
2611 }
2612
2613 handler = this._events[type];
2614
2615 if (isUndefined(handler))
2616 return false;
2617
2618 if (isFunction(handler)) {
2619 switch (arguments.length) {
2620 // fast cases
2621 case 1:
2622 handler.call(this);
2623 break;
2624 case 2:
2625 handler.call(this, arguments[1]);
2626 break;
2627 case 3:
2628 handler.call(this, arguments[1], arguments[2]);
2629 break;
2630 // slower
2631 default:
2632 args = Array.prototype.slice.call(arguments, 1);
2633 handler.apply(this, args);
2634 }
2635 } else if (isObject(handler)) {
2636 args = Array.prototype.slice.call(arguments, 1);
2637 listeners = handler.slice();
2638 len = listeners.length;
2639 for (i = 0; i < len; i++)
2640 listeners[i].apply(this, args);
2641 }
2642
2643 return true;
2644};
2645
2646EventEmitter.prototype.addListener = function(type, listener) {
2647 var m;
2648
2649 if (!isFunction(listener))
2650 throw TypeError('listener must be a function');
2651
2652 if (!this._events)
2653 this._events = {};
2654
2655 // To avoid recursion in the case that type === "newListener"! Before
2656 // adding it to the listeners, first emit "newListener".
2657 if (this._events.newListener)
2658 this.emit('newListener', type,
2659 isFunction(listener.listener) ?
2660 listener.listener : listener);
2661
2662 if (!this._events[type])
2663 // Optimize the case of one listener. Don't need the extra array object.
2664 this._events[type] = listener;
2665 else if (isObject(this._events[type]))
2666 // If we've already got an array, just append.
2667 this._events[type].push(listener);
2668 else
2669 // Adding the second element, need to change to array.
2670 this._events[type] = [this._events[type], listener];
2671
2672 // Check for listener leak
2673 if (isObject(this._events[type]) && !this._events[type].warned) {
2674 if (!isUndefined(this._maxListeners)) {
2675 m = this._maxListeners;
2676 } else {
2677 m = EventEmitter.defaultMaxListeners;
2678 }
2679
2680 if (m && m > 0 && this._events[type].length > m) {
2681 this._events[type].warned = true;
2682 console.error('(node) warning: possible EventEmitter memory ' +
2683 'leak detected. %d listeners added. ' +
2684 'Use emitter.setMaxListeners() to increase limit.',
2685 this._events[type].length);
2686 if (typeof console.trace === 'function') {
2687 // not supported in IE 10
2688 console.trace();
2689 }
2690 }
2691 }
2692
2693 return this;
2694};
2695
2696EventEmitter.prototype.on = EventEmitter.prototype.addListener;
2697
2698EventEmitter.prototype.once = function(type, listener) {
2699 if (!isFunction(listener))
2700 throw TypeError('listener must be a function');
2701
2702 var fired = false;
2703
2704 function g() {
2705 this.removeListener(type, g);
2706
2707 if (!fired) {
2708 fired = true;
2709 listener.apply(this, arguments);
2710 }
2711 }
2712
2713 g.listener = listener;
2714 this.on(type, g);
2715
2716 return this;
2717};
2718
2719// emits a 'removeListener' event iff the listener was removed
2720EventEmitter.prototype.removeListener = function(type, listener) {
2721 var list, position, length, i;
2722
2723 if (!isFunction(listener))
2724 throw TypeError('listener must be a function');
2725
2726 if (!this._events || !this._events[type])
2727 return this;
2728
2729 list = this._events[type];
2730 length = list.length;
2731 position = -1;
2732
2733 if (list === listener ||
2734 (isFunction(list.listener) && list.listener === listener)) {
2735 delete this._events[type];
2736 if (this._events.removeListener)
2737 this.emit('removeListener', type, listener);
2738
2739 } else if (isObject(list)) {
2740 for (i = length; i-- > 0;) {
2741 if (list[i] === listener ||
2742 (list[i].listener && list[i].listener === listener)) {
2743 position = i;
2744 break;
2745 }
2746 }
2747
2748 if (position < 0)
2749 return this;
2750
2751 if (list.length === 1) {
2752 list.length = 0;
2753 delete this._events[type];
2754 } else {
2755 list.splice(position, 1);
2756 }
2757
2758 if (this._events.removeListener)
2759 this.emit('removeListener', type, listener);
2760 }
2761
2762 return this;
2763};
2764
2765EventEmitter.prototype.removeAllListeners = function(type) {
2766 var key, listeners;
2767
2768 if (!this._events)
2769 return this;
2770
2771 // not listening for removeListener, no need to emit
2772 if (!this._events.removeListener) {
2773 if (arguments.length === 0)
2774 this._events = {};
2775 else if (this._events[type])
2776 delete this._events[type];
2777 return this;
2778 }
2779
2780 // emit removeListener for all listeners on all events
2781 if (arguments.length === 0) {
2782 for (key in this._events) {
2783 if (key === 'removeListener') continue;
2784 this.removeAllListeners(key);
2785 }
2786 this.removeAllListeners('removeListener');
2787 this._events = {};
2788 return this;
2789 }
2790
2791 listeners = this._events[type];
2792
2793 if (isFunction(listeners)) {
2794 this.removeListener(type, listeners);
2795 } else if (listeners) {
2796 // LIFO order
2797 while (listeners.length)
2798 this.removeListener(type, listeners[listeners.length - 1]);
2799 }
2800 delete this._events[type];
2801
2802 return this;
2803};
2804
2805EventEmitter.prototype.listeners = function(type) {
2806 var ret;
2807 if (!this._events || !this._events[type])
2808 ret = [];
2809 else if (isFunction(this._events[type]))
2810 ret = [this._events[type]];
2811 else
2812 ret = this._events[type].slice();
2813 return ret;
2814};
2815
2816EventEmitter.prototype.listenerCount = function(type) {
2817 if (this._events) {
2818 var evlistener = this._events[type];
2819
2820 if (isFunction(evlistener))
2821 return 1;
2822 else if (evlistener)
2823 return evlistener.length;
2824 }
2825 return 0;
2826};
2827
2828EventEmitter.listenerCount = function(emitter, type) {
2829 return emitter.listenerCount(type);
2830};
2831
2832function isFunction(arg) {
2833 return typeof arg === 'function';
2834}
2835
2836function isNumber(arg) {
2837 return typeof arg === 'number';
2838}
2839
2840function isObject(arg) {
2841 return typeof arg === 'object' && arg !== null;
2842}
2843
2844function isUndefined(arg) {
2845 return arg === void 0;
2846}
2847
2848},{}],8:[function(require,module,exports){
2849exports.read = function (buffer, offset, isLE, mLen, nBytes) {
2850 var e, m
2851 var eLen = nBytes * 8 - mLen - 1
2852 var eMax = (1 << eLen) - 1
2853 var eBias = eMax >> 1
2854 var nBits = -7
2855 var i = isLE ? (nBytes - 1) : 0
2856 var d = isLE ? -1 : 1
2857 var s = buffer[offset + i]
2858
2859 i += d
2860
2861 e = s & ((1 << (-nBits)) - 1)
2862 s >>= (-nBits)
2863 nBits += eLen
2864 for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
2865
2866 m = e & ((1 << (-nBits)) - 1)
2867 e >>= (-nBits)
2868 nBits += mLen
2869 for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
2870
2871 if (e === 0) {
2872 e = 1 - eBias
2873 } else if (e === eMax) {
2874 return m ? NaN : ((s ? -1 : 1) * Infinity)
2875 } else {
2876 m = m + Math.pow(2, mLen)
2877 e = e - eBias
2878 }
2879 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
2880}
2881
2882exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
2883 var e, m, c
2884 var eLen = nBytes * 8 - mLen - 1
2885 var eMax = (1 << eLen) - 1
2886 var eBias = eMax >> 1
2887 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
2888 var i = isLE ? 0 : (nBytes - 1)
2889 var d = isLE ? 1 : -1
2890 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
2891
2892 value = Math.abs(value)
2893
2894 if (isNaN(value) || value === Infinity) {
2895 m = isNaN(value) ? 1 : 0
2896 e = eMax
2897 } else {
2898 e = Math.floor(Math.log(value) / Math.LN2)
2899 if (value * (c = Math.pow(2, -e)) < 1) {
2900 e--
2901 c *= 2
2902 }
2903 if (e + eBias >= 1) {
2904 value += rt / c
2905 } else {
2906 value += rt * Math.pow(2, 1 - eBias)
2907 }
2908 if (value * c >= 2) {
2909 e++
2910 c /= 2
2911 }
2912
2913 if (e + eBias >= eMax) {
2914 m = 0
2915 e = eMax
2916 } else if (e + eBias >= 1) {
2917 m = (value * c - 1) * Math.pow(2, mLen)
2918 e = e + eBias
2919 } else {
2920 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
2921 e = 0
2922 }
2923 }
2924
2925 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
2926
2927 e = (e << mLen) | m
2928 eLen += mLen
2929 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
2930
2931 buffer[offset + i - d] |= s * 128
2932}
2933
2934},{}],9:[function(require,module,exports){
2935if (typeof Object.create === 'function') {
2936 // implementation from standard node.js 'util' module
2937 module.exports = function inherits(ctor, superCtor) {
2938 ctor.super_ = superCtor
2939 ctor.prototype = Object.create(superCtor.prototype, {
2940 constructor: {
2941 value: ctor,
2942 enumerable: false,
2943 writable: true,
2944 configurable: true
2945 }
2946 });
2947 };
2948} else {
2949 // old school shim for old browsers
2950 module.exports = function inherits(ctor, superCtor) {
2951 ctor.super_ = superCtor
2952 var TempCtor = function () {}
2953 TempCtor.prototype = superCtor.prototype
2954 ctor.prototype = new TempCtor()
2955 ctor.prototype.constructor = ctor
2956 }
2957}
2958
2959},{}],10:[function(require,module,exports){
2960/*!
2961 * Determine if an object is a Buffer
2962 *
2963 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
2964 * @license MIT
2965 */
2966
2967// The _isBuffer check is for Safari 5-7 support, because it's missing
2968// Object.prototype.constructor. Remove this eventually
2969module.exports = function (obj) {
2970 return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
2971}
2972
2973function isBuffer (obj) {
2974 return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
2975}
2976
2977// For Node v0.10 support. Remove this eventually.
2978function isSlowBuffer (obj) {
2979 return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
2980}
2981
2982},{}],11:[function(require,module,exports){
2983var toString = {}.toString;
2984
2985module.exports = Array.isArray || function (arr) {
2986 return toString.call(arr) == '[object Array]';
2987};
2988
2989},{}],12:[function(require,module,exports){
2990(function (process){
2991'use strict';
2992
2993if (!process.version ||
2994 process.version.indexOf('v0.') === 0 ||
2995 process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
2996 module.exports = nextTick;
2997} else {
2998 module.exports = process.nextTick;
2999}
3000
3001function nextTick(fn, arg1, arg2, arg3) {
3002 if (typeof fn !== 'function') {
3003 throw new TypeError('"callback" argument must be a function');
3004 }
3005 var len = arguments.length;
3006 var args, i;
3007 switch (len) {
3008 case 0:
3009 case 1:
3010 return process.nextTick(fn);
3011 case 2:
3012 return process.nextTick(function afterTickOne() {
3013 fn.call(null, arg1);
3014 });
3015 case 3:
3016 return process.nextTick(function afterTickTwo() {
3017 fn.call(null, arg1, arg2);
3018 });
3019 case 4:
3020 return process.nextTick(function afterTickThree() {
3021 fn.call(null, arg1, arg2, arg3);
3022 });
3023 default:
3024 args = new Array(len - 1);
3025 i = 0;
3026 while (i < args.length) {
3027 args[i++] = arguments[i];
3028 }
3029 return process.nextTick(function afterTick() {
3030 fn.apply(null, args);
3031 });
3032 }
3033}
3034
3035}).call(this,require('_process'))
3036},{"_process":13}],13:[function(require,module,exports){
3037// shim for using process in browser
3038var process = module.exports = {};
3039
3040// cached from whatever global is present so that test runners that stub it
3041// don't break things. But we need to wrap it in a try catch in case it is
3042// wrapped in strict mode code which doesn't define any globals. It's inside a
3043// function because try/catches deoptimize in certain engines.
3044
3045var cachedSetTimeout;
3046var cachedClearTimeout;
3047
3048function defaultSetTimout() {
3049 throw new Error('setTimeout has not been defined');
3050}
3051function defaultClearTimeout () {
3052 throw new Error('clearTimeout has not been defined');
3053}
3054(function () {
3055 try {
3056 if (typeof setTimeout === 'function') {
3057 cachedSetTimeout = setTimeout;
3058 } else {
3059 cachedSetTimeout = defaultSetTimout;
3060 }
3061 } catch (e) {
3062 cachedSetTimeout = defaultSetTimout;
3063 }
3064 try {
3065 if (typeof clearTimeout === 'function') {
3066 cachedClearTimeout = clearTimeout;
3067 } else {
3068 cachedClearTimeout = defaultClearTimeout;
3069 }
3070 } catch (e) {
3071 cachedClearTimeout = defaultClearTimeout;
3072 }
3073} ())
3074function runTimeout(fun) {
3075 if (cachedSetTimeout === setTimeout) {
3076 //normal enviroments in sane situations
3077 return setTimeout(fun, 0);
3078 }
3079 // if setTimeout wasn't available but was latter defined
3080 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
3081 cachedSetTimeout = setTimeout;
3082 return setTimeout(fun, 0);
3083 }
3084 try {
3085 // when when somebody has screwed with setTimeout but no I.E. maddness
3086 return cachedSetTimeout(fun, 0);
3087 } catch(e){
3088 try {
3089 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
3090 return cachedSetTimeout.call(null, fun, 0);
3091 } catch(e){
3092 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
3093 return cachedSetTimeout.call(this, fun, 0);
3094 }
3095 }
3096
3097
3098}
3099function runClearTimeout(marker) {
3100 if (cachedClearTimeout === clearTimeout) {
3101 //normal enviroments in sane situations
3102 return clearTimeout(marker);
3103 }
3104 // if clearTimeout wasn't available but was latter defined
3105 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
3106 cachedClearTimeout = clearTimeout;
3107 return clearTimeout(marker);
3108 }
3109 try {
3110 // when when somebody has screwed with setTimeout but no I.E. maddness
3111 return cachedClearTimeout(marker);
3112 } catch (e){
3113 try {
3114 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
3115 return cachedClearTimeout.call(null, marker);
3116 } catch (e){
3117 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
3118 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
3119 return cachedClearTimeout.call(this, marker);
3120 }
3121 }
3122
3123
3124
3125}
3126var queue = [];
3127var draining = false;
3128var currentQueue;
3129var queueIndex = -1;
3130
3131function cleanUpNextTick() {
3132 if (!draining || !currentQueue) {
3133 return;
3134 }
3135 draining = false;
3136 if (currentQueue.length) {
3137 queue = currentQueue.concat(queue);
3138 } else {
3139 queueIndex = -1;
3140 }
3141 if (queue.length) {
3142 drainQueue();
3143 }
3144}
3145
3146function drainQueue() {
3147 if (draining) {
3148 return;
3149 }
3150 var timeout = runTimeout(cleanUpNextTick);
3151 draining = true;
3152
3153 var len = queue.length;
3154 while(len) {
3155 currentQueue = queue;
3156 queue = [];
3157 while (++queueIndex < len) {
3158 if (currentQueue) {
3159 currentQueue[queueIndex].run();
3160 }
3161 }
3162 queueIndex = -1;
3163 len = queue.length;
3164 }
3165 currentQueue = null;
3166 draining = false;
3167 runClearTimeout(timeout);
3168}
3169
3170process.nextTick = function (fun) {
3171 var args = new Array(arguments.length - 1);
3172 if (arguments.length > 1) {
3173 for (var i = 1; i < arguments.length; i++) {
3174 args[i - 1] = arguments[i];
3175 }
3176 }
3177 queue.push(new Item(fun, args));
3178 if (queue.length === 1 && !draining) {
3179 runTimeout(drainQueue);
3180 }
3181};
3182
3183// v8 likes predictible objects
3184function Item(fun, array) {
3185 this.fun = fun;
3186 this.array = array;
3187}
3188Item.prototype.run = function () {
3189 this.fun.apply(null, this.array);
3190};
3191process.title = 'browser';
3192process.browser = true;
3193process.env = {};
3194process.argv = [];
3195process.version = ''; // empty string to avoid regexp issues
3196process.versions = {};
3197
3198function noop() {}
3199
3200process.on = noop;
3201process.addListener = noop;
3202process.once = noop;
3203process.off = noop;
3204process.removeListener = noop;
3205process.removeAllListeners = noop;
3206process.emit = noop;
3207process.prependListener = noop;
3208process.prependOnceListener = noop;
3209
3210process.listeners = function (name) { return [] }
3211
3212process.binding = function (name) {
3213 throw new Error('process.binding is not supported');
3214};
3215
3216process.cwd = function () { return '/' };
3217process.chdir = function (dir) {
3218 throw new Error('process.chdir is not supported');
3219};
3220process.umask = function() { return 0; };
3221
3222},{}],14:[function(require,module,exports){
3223module.exports = require('./lib/_stream_duplex.js');
3224
3225},{"./lib/_stream_duplex.js":15}],15:[function(require,module,exports){
3226// a duplex stream is just a stream that is both readable and writable.
3227// Since JS doesn't have multiple prototypal inheritance, this class
3228// prototypally inherits from Readable, and then parasitically from
3229// Writable.
3230
3231'use strict';
3232
3233/*<replacement>*/
3234
3235var objectKeys = Object.keys || function (obj) {
3236 var keys = [];
3237 for (var key in obj) {
3238 keys.push(key);
3239 }return keys;
3240};
3241/*</replacement>*/
3242
3243module.exports = Duplex;
3244
3245/*<replacement>*/
3246var processNextTick = require('process-nextick-args');
3247/*</replacement>*/
3248
3249/*<replacement>*/
3250var util = require('core-util-is');
3251util.inherits = require('inherits');
3252/*</replacement>*/
3253
3254var Readable = require('./_stream_readable');
3255var Writable = require('./_stream_writable');
3256
3257util.inherits(Duplex, Readable);
3258
3259var keys = objectKeys(Writable.prototype);
3260for (var v = 0; v < keys.length; v++) {
3261 var method = keys[v];
3262 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
3263}
3264
3265function Duplex(options) {
3266 if (!(this instanceof Duplex)) return new Duplex(options);
3267
3268 Readable.call(this, options);
3269 Writable.call(this, options);
3270
3271 if (options && options.readable === false) this.readable = false;
3272
3273 if (options && options.writable === false) this.writable = false;
3274
3275 this.allowHalfOpen = true;
3276 if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
3277
3278 this.once('end', onend);
3279}
3280
3281// the no-half-open enforcer
3282function onend() {
3283 // if we allow half-open state, or if the writable side ended,
3284 // then we're ok.
3285 if (this.allowHalfOpen || this._writableState.ended) return;
3286
3287 // no more data can be written.
3288 // But allow more writes to happen in this tick.
3289 processNextTick(onEndNT, this);
3290}
3291
3292function onEndNT(self) {
3293 self.end();
3294}
3295
3296function forEach(xs, f) {
3297 for (var i = 0, l = xs.length; i < l; i++) {
3298 f(xs[i], i);
3299 }
3300}
3301},{"./_stream_readable":17,"./_stream_writable":19,"core-util-is":6,"inherits":9,"process-nextick-args":12}],16:[function(require,module,exports){
3302// a passthrough stream.
3303// basically just the most minimal sort of Transform stream.
3304// Every written chunk gets output as-is.
3305
3306'use strict';
3307
3308module.exports = PassThrough;
3309
3310var Transform = require('./_stream_transform');
3311
3312/*<replacement>*/
3313var util = require('core-util-is');
3314util.inherits = require('inherits');
3315/*</replacement>*/
3316
3317util.inherits(PassThrough, Transform);
3318
3319function PassThrough(options) {
3320 if (!(this instanceof PassThrough)) return new PassThrough(options);
3321
3322 Transform.call(this, options);
3323}
3324
3325PassThrough.prototype._transform = function (chunk, encoding, cb) {
3326 cb(null, chunk);
3327};
3328},{"./_stream_transform":18,"core-util-is":6,"inherits":9}],17:[function(require,module,exports){
3329(function (process){
3330'use strict';
3331
3332module.exports = Readable;
3333
3334/*<replacement>*/
3335var processNextTick = require('process-nextick-args');
3336/*</replacement>*/
3337
3338/*<replacement>*/
3339var isArray = require('isarray');
3340/*</replacement>*/
3341
3342/*<replacement>*/
3343var Duplex;
3344/*</replacement>*/
3345
3346Readable.ReadableState = ReadableState;
3347
3348/*<replacement>*/
3349var EE = require('events').EventEmitter;
3350
3351var EElistenerCount = function (emitter, type) {
3352 return emitter.listeners(type).length;
3353};
3354/*</replacement>*/
3355
3356/*<replacement>*/
3357var Stream = require('./internal/streams/stream');
3358/*</replacement>*/
3359
3360var Buffer = require('buffer').Buffer;
3361/*<replacement>*/
3362var bufferShim = require('buffer-shims');
3363/*</replacement>*/
3364
3365/*<replacement>*/
3366var util = require('core-util-is');
3367util.inherits = require('inherits');
3368/*</replacement>*/
3369
3370/*<replacement>*/
3371var debugUtil = require('util');
3372var debug = void 0;
3373if (debugUtil && debugUtil.debuglog) {
3374 debug = debugUtil.debuglog('stream');
3375} else {
3376 debug = function () {};
3377}
3378/*</replacement>*/
3379
3380var BufferList = require('./internal/streams/BufferList');
3381var StringDecoder;
3382
3383util.inherits(Readable, Stream);
3384
3385var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
3386
3387function prependListener(emitter, event, fn) {
3388 // Sadly this is not cacheable as some libraries bundle their own
3389 // event emitter implementation with them.
3390 if (typeof emitter.prependListener === 'function') {
3391 return emitter.prependListener(event, fn);
3392 } else {
3393 // This is a hack to make sure that our error handler is attached before any
3394 // userland ones. NEVER DO THIS. This is here only because this code needs
3395 // to continue to work with older versions of Node.js that do not include
3396 // the prependListener() method. The goal is to eventually remove this hack.
3397 if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
3398 }
3399}
3400
3401function ReadableState(options, stream) {
3402 Duplex = Duplex || require('./_stream_duplex');
3403
3404 options = options || {};
3405
3406 // object stream flag. Used to make read(n) ignore n and to
3407 // make all the buffer merging and length checks go away
3408 this.objectMode = !!options.objectMode;
3409
3410 if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
3411
3412 // the point at which it stops calling _read() to fill the buffer
3413 // Note: 0 is a valid value, means "don't call _read preemptively ever"
3414 var hwm = options.highWaterMark;
3415 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
3416 this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
3417
3418 // cast to ints.
3419 this.highWaterMark = ~~this.highWaterMark;
3420
3421 // A linked list is used to store data chunks instead of an array because the
3422 // linked list can remove elements from the beginning faster than
3423 // array.shift()
3424 this.buffer = new BufferList();
3425 this.length = 0;
3426 this.pipes = null;
3427 this.pipesCount = 0;
3428 this.flowing = null;
3429 this.ended = false;
3430 this.endEmitted = false;
3431 this.reading = false;
3432
3433 // a flag to be able to tell if the onwrite cb is called immediately,
3434 // or on a later tick. We set this to true at first, because any
3435 // actions that shouldn't happen until "later" should generally also
3436 // not happen before the first write call.
3437 this.sync = true;
3438
3439 // whenever we return null, then we set a flag to say
3440 // that we're awaiting a 'readable' event emission.
3441 this.needReadable = false;
3442 this.emittedReadable = false;
3443 this.readableListening = false;
3444 this.resumeScheduled = false;
3445
3446 // Crypto is kind of old and crusty. Historically, its default string
3447 // encoding is 'binary' so we have to make this configurable.
3448 // Everything else in the universe uses 'utf8', though.
3449 this.defaultEncoding = options.defaultEncoding || 'utf8';
3450
3451 // when piping, we only care about 'readable' events that happen
3452 // after read()ing all the bytes and not getting any pushback.
3453 this.ranOut = false;
3454
3455 // the number of writers that are awaiting a drain event in .pipe()s
3456 this.awaitDrain = 0;
3457
3458 // if true, a maybeReadMore has been scheduled
3459 this.readingMore = false;
3460
3461 this.decoder = null;
3462 this.encoding = null;
3463 if (options.encoding) {
3464 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
3465 this.decoder = new StringDecoder(options.encoding);
3466 this.encoding = options.encoding;
3467 }
3468}
3469
3470function Readable(options) {
3471 Duplex = Duplex || require('./_stream_duplex');
3472
3473 if (!(this instanceof Readable)) return new Readable(options);
3474
3475 this._readableState = new ReadableState(options, this);
3476
3477 // legacy
3478 this.readable = true;
3479
3480 if (options && typeof options.read === 'function') this._read = options.read;
3481
3482 Stream.call(this);
3483}
3484
3485// Manually shove something into the read() buffer.
3486// This returns true if the highWaterMark has not been hit yet,
3487// similar to how Writable.write() returns true if you should
3488// write() some more.
3489Readable.prototype.push = function (chunk, encoding) {
3490 var state = this._readableState;
3491
3492 if (!state.objectMode && typeof chunk === 'string') {
3493 encoding = encoding || state.defaultEncoding;
3494 if (encoding !== state.encoding) {
3495 chunk = bufferShim.from(chunk, encoding);
3496 encoding = '';
3497 }
3498 }
3499
3500 return readableAddChunk(this, state, chunk, encoding, false);
3501};
3502
3503// Unshift should *always* be something directly out of read()
3504Readable.prototype.unshift = function (chunk) {
3505 var state = this._readableState;
3506 return readableAddChunk(this, state, chunk, '', true);
3507};
3508
3509Readable.prototype.isPaused = function () {
3510 return this._readableState.flowing === false;
3511};
3512
3513function readableAddChunk(stream, state, chunk, encoding, addToFront) {
3514 var er = chunkInvalid(state, chunk);
3515 if (er) {
3516 stream.emit('error', er);
3517 } else if (chunk === null) {
3518 state.reading = false;
3519 onEofChunk(stream, state);
3520 } else if (state.objectMode || chunk && chunk.length > 0) {
3521 if (state.ended && !addToFront) {
3522 var e = new Error('stream.push() after EOF');
3523 stream.emit('error', e);
3524 } else if (state.endEmitted && addToFront) {
3525 var _e = new Error('stream.unshift() after end event');
3526 stream.emit('error', _e);
3527 } else {
3528 var skipAdd;
3529 if (state.decoder && !addToFront && !encoding) {
3530 chunk = state.decoder.write(chunk);
3531 skipAdd = !state.objectMode && chunk.length === 0;
3532 }
3533
3534 if (!addToFront) state.reading = false;
3535
3536 // Don't add to the buffer if we've decoded to an empty string chunk and
3537 // we're not in object mode
3538 if (!skipAdd) {
3539 // if we want the data now, just emit it.
3540 if (state.flowing && state.length === 0 && !state.sync) {
3541 stream.emit('data', chunk);
3542 stream.read(0);
3543 } else {
3544 // update the buffer info.
3545 state.length += state.objectMode ? 1 : chunk.length;
3546 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
3547
3548 if (state.needReadable) emitReadable(stream);
3549 }
3550 }
3551
3552 maybeReadMore(stream, state);
3553 }
3554 } else if (!addToFront) {
3555 state.reading = false;
3556 }
3557
3558 return needMoreData(state);
3559}
3560
3561// if it's past the high water mark, we can push in some more.
3562// Also, if we have no data yet, we can stand some
3563// more bytes. This is to work around cases where hwm=0,
3564// such as the repl. Also, if the push() triggered a
3565// readable event, and the user called read(largeNumber) such that
3566// needReadable was set, then we ought to push more, so that another
3567// 'readable' event will be triggered.
3568function needMoreData(state) {
3569 return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
3570}
3571
3572// backwards compatibility.
3573Readable.prototype.setEncoding = function (enc) {
3574 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
3575 this._readableState.decoder = new StringDecoder(enc);
3576 this._readableState.encoding = enc;
3577 return this;
3578};
3579
3580// Don't raise the hwm > 8MB
3581var MAX_HWM = 0x800000;
3582function computeNewHighWaterMark(n) {
3583 if (n >= MAX_HWM) {
3584 n = MAX_HWM;
3585 } else {
3586 // Get the next highest power of 2 to prevent increasing hwm excessively in
3587 // tiny amounts
3588 n--;
3589 n |= n >>> 1;
3590 n |= n >>> 2;
3591 n |= n >>> 4;
3592 n |= n >>> 8;
3593 n |= n >>> 16;
3594 n++;
3595 }
3596 return n;
3597}
3598
3599// This function is designed to be inlinable, so please take care when making
3600// changes to the function body.
3601function howMuchToRead(n, state) {
3602 if (n <= 0 || state.length === 0 && state.ended) return 0;
3603 if (state.objectMode) return 1;
3604 if (n !== n) {
3605 // Only flow one buffer at a time
3606 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
3607 }
3608 // If we're asking for more than the current hwm, then raise the hwm.
3609 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
3610 if (n <= state.length) return n;
3611 // Don't have enough
3612 if (!state.ended) {
3613 state.needReadable = true;
3614 return 0;
3615 }
3616 return state.length;
3617}
3618
3619// you can override either this method, or the async _read(n) below.
3620Readable.prototype.read = function (n) {
3621 debug('read', n);
3622 n = parseInt(n, 10);
3623 var state = this._readableState;
3624 var nOrig = n;
3625
3626 if (n !== 0) state.emittedReadable = false;
3627
3628 // if we're doing read(0) to trigger a readable event, but we
3629 // already have a bunch of data in the buffer, then just trigger
3630 // the 'readable' event and move on.
3631 if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
3632 debug('read: emitReadable', state.length, state.ended);
3633 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
3634 return null;
3635 }
3636
3637 n = howMuchToRead(n, state);
3638
3639 // if we've ended, and we're now clear, then finish it up.
3640 if (n === 0 && state.ended) {
3641 if (state.length === 0) endReadable(this);
3642 return null;
3643 }
3644
3645 // All the actual chunk generation logic needs to be
3646 // *below* the call to _read. The reason is that in certain
3647 // synthetic stream cases, such as passthrough streams, _read
3648 // may be a completely synchronous operation which may change
3649 // the state of the read buffer, providing enough data when
3650 // before there was *not* enough.
3651 //
3652 // So, the steps are:
3653 // 1. Figure out what the state of things will be after we do
3654 // a read from the buffer.
3655 //
3656 // 2. If that resulting state will trigger a _read, then call _read.
3657 // Note that this may be asynchronous, or synchronous. Yes, it is
3658 // deeply ugly to write APIs this way, but that still doesn't mean
3659 // that the Readable class should behave improperly, as streams are
3660 // designed to be sync/async agnostic.
3661 // Take note if the _read call is sync or async (ie, if the read call
3662 // has returned yet), so that we know whether or not it's safe to emit
3663 // 'readable' etc.
3664 //
3665 // 3. Actually pull the requested chunks out of the buffer and return.
3666
3667 // if we need a readable event, then we need to do some reading.
3668 var doRead = state.needReadable;
3669 debug('need readable', doRead);
3670
3671 // if we currently have less than the highWaterMark, then also read some
3672 if (state.length === 0 || state.length - n < state.highWaterMark) {
3673 doRead = true;
3674 debug('length less than watermark', doRead);
3675 }
3676
3677 // however, if we've ended, then there's no point, and if we're already
3678 // reading, then it's unnecessary.
3679 if (state.ended || state.reading) {
3680 doRead = false;
3681 debug('reading or ended', doRead);
3682 } else if (doRead) {
3683 debug('do read');
3684 state.reading = true;
3685 state.sync = true;
3686 // if the length is currently zero, then we *need* a readable event.
3687 if (state.length === 0) state.needReadable = true;
3688 // call internal read method
3689 this._read(state.highWaterMark);
3690 state.sync = false;
3691 // If _read pushed data synchronously, then `reading` will be false,
3692 // and we need to re-evaluate how much data we can return to the user.
3693 if (!state.reading) n = howMuchToRead(nOrig, state);
3694 }
3695
3696 var ret;
3697 if (n > 0) ret = fromList(n, state);else ret = null;
3698
3699 if (ret === null) {
3700 state.needReadable = true;
3701 n = 0;
3702 } else {
3703 state.length -= n;
3704 }
3705
3706 if (state.length === 0) {
3707 // If we have nothing in the buffer, then we want to know
3708 // as soon as we *do* get something into the buffer.
3709 if (!state.ended) state.needReadable = true;
3710
3711 // If we tried to read() past the EOF, then emit end on the next tick.
3712 if (nOrig !== n && state.ended) endReadable(this);
3713 }
3714
3715 if (ret !== null) this.emit('data', ret);
3716
3717 return ret;
3718};
3719
3720function chunkInvalid(state, chunk) {
3721 var er = null;
3722 if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) {
3723 er = new TypeError('Invalid non-string/buffer chunk');
3724 }
3725 return er;
3726}
3727
3728function onEofChunk(stream, state) {
3729 if (state.ended) return;
3730 if (state.decoder) {
3731 var chunk = state.decoder.end();
3732 if (chunk && chunk.length) {
3733 state.buffer.push(chunk);
3734 state.length += state.objectMode ? 1 : chunk.length;
3735 }
3736 }
3737 state.ended = true;
3738
3739 // emit 'readable' now to make sure it gets picked up.
3740 emitReadable(stream);
3741}
3742
3743// Don't emit readable right away in sync mode, because this can trigger
3744// another read() call => stack overflow. This way, it might trigger
3745// a nextTick recursion warning, but that's not so bad.
3746function emitReadable(stream) {
3747 var state = stream._readableState;
3748 state.needReadable = false;
3749 if (!state.emittedReadable) {
3750 debug('emitReadable', state.flowing);
3751 state.emittedReadable = true;
3752 if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream);
3753 }
3754}
3755
3756function emitReadable_(stream) {
3757 debug('emit readable');
3758 stream.emit('readable');
3759 flow(stream);
3760}
3761
3762// at this point, the user has presumably seen the 'readable' event,
3763// and called read() to consume some data. that may have triggered
3764// in turn another _read(n) call, in which case reading = true if
3765// it's in progress.
3766// However, if we're not ended, or reading, and the length < hwm,
3767// then go ahead and try to read some more preemptively.
3768function maybeReadMore(stream, state) {
3769 if (!state.readingMore) {
3770 state.readingMore = true;
3771 processNextTick(maybeReadMore_, stream, state);
3772 }
3773}
3774
3775function maybeReadMore_(stream, state) {
3776 var len = state.length;
3777 while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
3778 debug('maybeReadMore read 0');
3779 stream.read(0);
3780 if (len === state.length)
3781 // didn't get any data, stop spinning.
3782 break;else len = state.length;
3783 }
3784 state.readingMore = false;
3785}
3786
3787// abstract method. to be overridden in specific implementation classes.
3788// call cb(er, data) where data is <= n in length.
3789// for virtual (non-string, non-buffer) streams, "length" is somewhat
3790// arbitrary, and perhaps not very meaningful.
3791Readable.prototype._read = function (n) {
3792 this.emit('error', new Error('_read() is not implemented'));
3793};
3794
3795Readable.prototype.pipe = function (dest, pipeOpts) {
3796 var src = this;
3797 var state = this._readableState;
3798
3799 switch (state.pipesCount) {
3800 case 0:
3801 state.pipes = dest;
3802 break;
3803 case 1:
3804 state.pipes = [state.pipes, dest];
3805 break;
3806 default:
3807 state.pipes.push(dest);
3808 break;
3809 }
3810 state.pipesCount += 1;
3811 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
3812
3813 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
3814
3815 var endFn = doEnd ? onend : cleanup;
3816 if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn);
3817
3818 dest.on('unpipe', onunpipe);
3819 function onunpipe(readable) {
3820 debug('onunpipe');
3821 if (readable === src) {
3822 cleanup();
3823 }
3824 }
3825
3826 function onend() {
3827 debug('onend');
3828 dest.end();
3829 }
3830
3831 // when the dest drains, it reduces the awaitDrain counter
3832 // on the source. This would be more elegant with a .once()
3833 // handler in flow(), but adding and removing repeatedly is
3834 // too slow.
3835 var ondrain = pipeOnDrain(src);
3836 dest.on('drain', ondrain);
3837
3838 var cleanedUp = false;
3839 function cleanup() {
3840 debug('cleanup');
3841 // cleanup event handlers once the pipe is broken
3842 dest.removeListener('close', onclose);
3843 dest.removeListener('finish', onfinish);
3844 dest.removeListener('drain', ondrain);
3845 dest.removeListener('error', onerror);
3846 dest.removeListener('unpipe', onunpipe);
3847 src.removeListener('end', onend);
3848 src.removeListener('end', cleanup);
3849 src.removeListener('data', ondata);
3850
3851 cleanedUp = true;
3852
3853 // if the reader is waiting for a drain event from this
3854 // specific writer, then it would cause it to never start
3855 // flowing again.
3856 // So, if this is awaiting a drain, then we just call it now.
3857 // If we don't know, then assume that we are waiting for one.
3858 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
3859 }
3860
3861 // If the user pushes more data while we're writing to dest then we'll end up
3862 // in ondata again. However, we only want to increase awaitDrain once because
3863 // dest will only emit one 'drain' event for the multiple writes.
3864 // => Introduce a guard on increasing awaitDrain.
3865 var increasedAwaitDrain = false;
3866 src.on('data', ondata);
3867 function ondata(chunk) {
3868 debug('ondata');
3869 increasedAwaitDrain = false;
3870 var ret = dest.write(chunk);
3871 if (false === ret && !increasedAwaitDrain) {
3872 // If the user unpiped during `dest.write()`, it is possible
3873 // to get stuck in a permanently paused state if that write
3874 // also returned false.
3875 // => Check whether `dest` is still a piping destination.
3876 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
3877 debug('false write response, pause', src._readableState.awaitDrain);
3878 src._readableState.awaitDrain++;
3879 increasedAwaitDrain = true;
3880 }
3881 src.pause();
3882 }
3883 }
3884
3885 // if the dest has an error, then stop piping into it.
3886 // however, don't suppress the throwing behavior for this.
3887 function onerror(er) {
3888 debug('onerror', er);
3889 unpipe();
3890 dest.removeListener('error', onerror);
3891 if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
3892 }
3893
3894 // Make sure our error handler is attached before userland ones.
3895 prependListener(dest, 'error', onerror);
3896
3897 // Both close and finish should trigger unpipe, but only once.
3898 function onclose() {
3899 dest.removeListener('finish', onfinish);
3900 unpipe();
3901 }
3902 dest.once('close', onclose);
3903 function onfinish() {
3904 debug('onfinish');
3905 dest.removeListener('close', onclose);
3906 unpipe();
3907 }
3908 dest.once('finish', onfinish);
3909
3910 function unpipe() {
3911 debug('unpipe');
3912 src.unpipe(dest);
3913 }
3914
3915 // tell the dest that it's being piped to
3916 dest.emit('pipe', src);
3917
3918 // start the flow if it hasn't been started already.
3919 if (!state.flowing) {
3920 debug('pipe resume');
3921 src.resume();
3922 }
3923
3924 return dest;
3925};
3926
3927function pipeOnDrain(src) {
3928 return function () {
3929 var state = src._readableState;
3930 debug('pipeOnDrain', state.awaitDrain);
3931 if (state.awaitDrain) state.awaitDrain--;
3932 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
3933 state.flowing = true;
3934 flow(src);
3935 }
3936 };
3937}
3938
3939Readable.prototype.unpipe = function (dest) {
3940 var state = this._readableState;
3941
3942 // if we're not piping anywhere, then do nothing.
3943 if (state.pipesCount === 0) return this;
3944
3945 // just one destination. most common case.
3946 if (state.pipesCount === 1) {
3947 // passed in one, but it's not the right one.
3948 if (dest && dest !== state.pipes) return this;
3949
3950 if (!dest) dest = state.pipes;
3951
3952 // got a match.
3953 state.pipes = null;
3954 state.pipesCount = 0;
3955 state.flowing = false;
3956 if (dest) dest.emit('unpipe', this);
3957 return this;
3958 }
3959
3960 // slow case. multiple pipe destinations.
3961
3962 if (!dest) {
3963 // remove all.
3964 var dests = state.pipes;
3965 var len = state.pipesCount;
3966 state.pipes = null;
3967 state.pipesCount = 0;
3968 state.flowing = false;
3969
3970 for (var i = 0; i < len; i++) {
3971 dests[i].emit('unpipe', this);
3972 }return this;
3973 }
3974
3975 // try to find the right one.
3976 var index = indexOf(state.pipes, dest);
3977 if (index === -1) return this;
3978
3979 state.pipes.splice(index, 1);
3980 state.pipesCount -= 1;
3981 if (state.pipesCount === 1) state.pipes = state.pipes[0];
3982
3983 dest.emit('unpipe', this);
3984
3985 return this;
3986};
3987
3988// set up data events if they are asked for
3989// Ensure readable listeners eventually get something
3990Readable.prototype.on = function (ev, fn) {
3991 var res = Stream.prototype.on.call(this, ev, fn);
3992
3993 if (ev === 'data') {
3994 // Start flowing on next tick if stream isn't explicitly paused
3995 if (this._readableState.flowing !== false) this.resume();
3996 } else if (ev === 'readable') {
3997 var state = this._readableState;
3998 if (!state.endEmitted && !state.readableListening) {
3999 state.readableListening = state.needReadable = true;
4000 state.emittedReadable = false;
4001 if (!state.reading) {
4002 processNextTick(nReadingNextTick, this);
4003 } else if (state.length) {
4004 emitReadable(this, state);
4005 }
4006 }
4007 }
4008
4009 return res;
4010};
4011Readable.prototype.addListener = Readable.prototype.on;
4012
4013function nReadingNextTick(self) {
4014 debug('readable nexttick read 0');
4015 self.read(0);
4016}
4017
4018// pause() and resume() are remnants of the legacy readable stream API
4019// If the user uses them, then switch into old mode.
4020Readable.prototype.resume = function () {
4021 var state = this._readableState;
4022 if (!state.flowing) {
4023 debug('resume');
4024 state.flowing = true;
4025 resume(this, state);
4026 }
4027 return this;
4028};
4029
4030function resume(stream, state) {
4031 if (!state.resumeScheduled) {
4032 state.resumeScheduled = true;
4033 processNextTick(resume_, stream, state);
4034 }
4035}
4036
4037function resume_(stream, state) {
4038 if (!state.reading) {
4039 debug('resume read 0');
4040 stream.read(0);
4041 }
4042
4043 state.resumeScheduled = false;
4044 state.awaitDrain = 0;
4045 stream.emit('resume');
4046 flow(stream);
4047 if (state.flowing && !state.reading) stream.read(0);
4048}
4049
4050Readable.prototype.pause = function () {
4051 debug('call pause flowing=%j', this._readableState.flowing);
4052 if (false !== this._readableState.flowing) {
4053 debug('pause');
4054 this._readableState.flowing = false;
4055 this.emit('pause');
4056 }
4057 return this;
4058};
4059
4060function flow(stream) {
4061 var state = stream._readableState;
4062 debug('flow', state.flowing);
4063 while (state.flowing && stream.read() !== null) {}
4064}
4065
4066// wrap an old-style stream as the async data source.
4067// This is *not* part of the readable stream interface.
4068// It is an ugly unfortunate mess of history.
4069Readable.prototype.wrap = function (stream) {
4070 var state = this._readableState;
4071 var paused = false;
4072
4073 var self = this;
4074 stream.on('end', function () {
4075 debug('wrapped end');
4076 if (state.decoder && !state.ended) {
4077 var chunk = state.decoder.end();
4078 if (chunk && chunk.length) self.push(chunk);
4079 }
4080
4081 self.push(null);
4082 });
4083
4084 stream.on('data', function (chunk) {
4085 debug('wrapped data');
4086 if (state.decoder) chunk = state.decoder.write(chunk);
4087
4088 // don't skip over falsy values in objectMode
4089 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
4090
4091 var ret = self.push(chunk);
4092 if (!ret) {
4093 paused = true;
4094 stream.pause();
4095 }
4096 });
4097
4098 // proxy all the other methods.
4099 // important when wrapping filters and duplexes.
4100 for (var i in stream) {
4101 if (this[i] === undefined && typeof stream[i] === 'function') {
4102 this[i] = function (method) {
4103 return function () {
4104 return stream[method].apply(stream, arguments);
4105 };
4106 }(i);
4107 }
4108 }
4109
4110 // proxy certain important events.
4111 for (var n = 0; n < kProxyEvents.length; n++) {
4112 stream.on(kProxyEvents[n], self.emit.bind(self, kProxyEvents[n]));
4113 }
4114
4115 // when we try to consume some more bytes, simply unpause the
4116 // underlying stream.
4117 self._read = function (n) {
4118 debug('wrapped _read', n);
4119 if (paused) {
4120 paused = false;
4121 stream.resume();
4122 }
4123 };
4124
4125 return self;
4126};
4127
4128// exposed for testing purposes only.
4129Readable._fromList = fromList;
4130
4131// Pluck off n bytes from an array of buffers.
4132// Length is the combined lengths of all the buffers in the list.
4133// This function is designed to be inlinable, so please take care when making
4134// changes to the function body.
4135function fromList(n, state) {
4136 // nothing buffered
4137 if (state.length === 0) return null;
4138
4139 var ret;
4140 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
4141 // read it all, truncate the list
4142 if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
4143 state.buffer.clear();
4144 } else {
4145 // read part of list
4146 ret = fromListPartial(n, state.buffer, state.decoder);
4147 }
4148
4149 return ret;
4150}
4151
4152// Extracts only enough buffered data to satisfy the amount requested.
4153// This function is designed to be inlinable, so please take care when making
4154// changes to the function body.
4155function fromListPartial(n, list, hasStrings) {
4156 var ret;
4157 if (n < list.head.data.length) {
4158 // slice is the same for buffers and strings
4159 ret = list.head.data.slice(0, n);
4160 list.head.data = list.head.data.slice(n);
4161 } else if (n === list.head.data.length) {
4162 // first chunk is a perfect match
4163 ret = list.shift();
4164 } else {
4165 // result spans more than one buffer
4166 ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
4167 }
4168 return ret;
4169}
4170
4171// Copies a specified amount of characters from the list of buffered data
4172// chunks.
4173// This function is designed to be inlinable, so please take care when making
4174// changes to the function body.
4175function copyFromBufferString(n, list) {
4176 var p = list.head;
4177 var c = 1;
4178 var ret = p.data;
4179 n -= ret.length;
4180 while (p = p.next) {
4181 var str = p.data;
4182 var nb = n > str.length ? str.length : n;
4183 if (nb === str.length) ret += str;else ret += str.slice(0, n);
4184 n -= nb;
4185 if (n === 0) {
4186 if (nb === str.length) {
4187 ++c;
4188 if (p.next) list.head = p.next;else list.head = list.tail = null;
4189 } else {
4190 list.head = p;
4191 p.data = str.slice(nb);
4192 }
4193 break;
4194 }
4195 ++c;
4196 }
4197 list.length -= c;
4198 return ret;
4199}
4200
4201// Copies a specified amount of bytes from the list of buffered data chunks.
4202// This function is designed to be inlinable, so please take care when making
4203// changes to the function body.
4204function copyFromBuffer(n, list) {
4205 var ret = bufferShim.allocUnsafe(n);
4206 var p = list.head;
4207 var c = 1;
4208 p.data.copy(ret);
4209 n -= p.data.length;
4210 while (p = p.next) {
4211 var buf = p.data;
4212 var nb = n > buf.length ? buf.length : n;
4213 buf.copy(ret, ret.length - n, 0, nb);
4214 n -= nb;
4215 if (n === 0) {
4216 if (nb === buf.length) {
4217 ++c;
4218 if (p.next) list.head = p.next;else list.head = list.tail = null;
4219 } else {
4220 list.head = p;
4221 p.data = buf.slice(nb);
4222 }
4223 break;
4224 }
4225 ++c;
4226 }
4227 list.length -= c;
4228 return ret;
4229}
4230
4231function endReadable(stream) {
4232 var state = stream._readableState;
4233
4234 // If we get here before consuming all the bytes, then that is a
4235 // bug in node. Should never happen.
4236 if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
4237
4238 if (!state.endEmitted) {
4239 state.ended = true;
4240 processNextTick(endReadableNT, state, stream);
4241 }
4242}
4243
4244function endReadableNT(state, stream) {
4245 // Check that we didn't get one last unshift.
4246 if (!state.endEmitted && state.length === 0) {
4247 state.endEmitted = true;
4248 stream.readable = false;
4249 stream.emit('end');
4250 }
4251}
4252
4253function forEach(xs, f) {
4254 for (var i = 0, l = xs.length; i < l; i++) {
4255 f(xs[i], i);
4256 }
4257}
4258
4259function indexOf(xs, x) {
4260 for (var i = 0, l = xs.length; i < l; i++) {
4261 if (xs[i] === x) return i;
4262 }
4263 return -1;
4264}
4265}).call(this,require('_process'))
4266},{"./_stream_duplex":15,"./internal/streams/BufferList":20,"./internal/streams/stream":21,"_process":13,"buffer":5,"buffer-shims":4,"core-util-is":6,"events":7,"inherits":9,"isarray":11,"process-nextick-args":12,"string_decoder/":22,"util":3}],18:[function(require,module,exports){
4267// a transform stream is a readable/writable stream where you do
4268// something with the data. Sometimes it's called a "filter",
4269// but that's not a great name for it, since that implies a thing where
4270// some bits pass through, and others are simply ignored. (That would
4271// be a valid example of a transform, of course.)
4272//
4273// While the output is causally related to the input, it's not a
4274// necessarily symmetric or synchronous transformation. For example,
4275// a zlib stream might take multiple plain-text writes(), and then
4276// emit a single compressed chunk some time in the future.
4277//
4278// Here's how this works:
4279//
4280// The Transform stream has all the aspects of the readable and writable
4281// stream classes. When you write(chunk), that calls _write(chunk,cb)
4282// internally, and returns false if there's a lot of pending writes
4283// buffered up. When you call read(), that calls _read(n) until
4284// there's enough pending readable data buffered up.
4285//
4286// In a transform stream, the written data is placed in a buffer. When
4287// _read(n) is called, it transforms the queued up data, calling the
4288// buffered _write cb's as it consumes chunks. If consuming a single
4289// written chunk would result in multiple output chunks, then the first
4290// outputted bit calls the readcb, and subsequent chunks just go into
4291// the read buffer, and will cause it to emit 'readable' if necessary.
4292//
4293// This way, back-pressure is actually determined by the reading side,
4294// since _read has to be called to start processing a new chunk. However,
4295// a pathological inflate type of transform can cause excessive buffering
4296// here. For example, imagine a stream where every byte of input is
4297// interpreted as an integer from 0-255, and then results in that many
4298// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
4299// 1kb of data being output. In this case, you could write a very small
4300// amount of input, and end up with a very large amount of output. In
4301// such a pathological inflating mechanism, there'd be no way to tell
4302// the system to stop doing the transform. A single 4MB write could
4303// cause the system to run out of memory.
4304//
4305// However, even in such a pathological case, only a single written chunk
4306// would be consumed, and then the rest would wait (un-transformed) until
4307// the results of the previous transformed chunk were consumed.
4308
4309'use strict';
4310
4311module.exports = Transform;
4312
4313var Duplex = require('./_stream_duplex');
4314
4315/*<replacement>*/
4316var util = require('core-util-is');
4317util.inherits = require('inherits');
4318/*</replacement>*/
4319
4320util.inherits(Transform, Duplex);
4321
4322function TransformState(stream) {
4323 this.afterTransform = function (er, data) {
4324 return afterTransform(stream, er, data);
4325 };
4326
4327 this.needTransform = false;
4328 this.transforming = false;
4329 this.writecb = null;
4330 this.writechunk = null;
4331 this.writeencoding = null;
4332}
4333
4334function afterTransform(stream, er, data) {
4335 var ts = stream._transformState;
4336 ts.transforming = false;
4337
4338 var cb = ts.writecb;
4339
4340 if (!cb) return stream.emit('error', new Error('no writecb in Transform class'));
4341
4342 ts.writechunk = null;
4343 ts.writecb = null;
4344
4345 if (data !== null && data !== undefined) stream.push(data);
4346
4347 cb(er);
4348
4349 var rs = stream._readableState;
4350 rs.reading = false;
4351 if (rs.needReadable || rs.length < rs.highWaterMark) {
4352 stream._read(rs.highWaterMark);
4353 }
4354}
4355
4356function Transform(options) {
4357 if (!(this instanceof Transform)) return new Transform(options);
4358
4359 Duplex.call(this, options);
4360
4361 this._transformState = new TransformState(this);
4362
4363 var stream = this;
4364
4365 // start out asking for a readable event once data is transformed.
4366 this._readableState.needReadable = true;
4367
4368 // we have implemented the _read method, and done the other things
4369 // that Readable wants before the first _read call, so unset the
4370 // sync guard flag.
4371 this._readableState.sync = false;
4372
4373 if (options) {
4374 if (typeof options.transform === 'function') this._transform = options.transform;
4375
4376 if (typeof options.flush === 'function') this._flush = options.flush;
4377 }
4378
4379 // When the writable side finishes, then flush out anything remaining.
4380 this.once('prefinish', function () {
4381 if (typeof this._flush === 'function') this._flush(function (er, data) {
4382 done(stream, er, data);
4383 });else done(stream);
4384 });
4385}
4386
4387Transform.prototype.push = function (chunk, encoding) {
4388 this._transformState.needTransform = false;
4389 return Duplex.prototype.push.call(this, chunk, encoding);
4390};
4391
4392// This is the part where you do stuff!
4393// override this function in implementation classes.
4394// 'chunk' is an input chunk.
4395//
4396// Call `push(newChunk)` to pass along transformed output
4397// to the readable side. You may call 'push' zero or more times.
4398//
4399// Call `cb(err)` when you are done with this chunk. If you pass
4400// an error, then that'll put the hurt on the whole operation. If you
4401// never call cb(), then you'll never get another chunk.
4402Transform.prototype._transform = function (chunk, encoding, cb) {
4403 throw new Error('_transform() is not implemented');
4404};
4405
4406Transform.prototype._write = function (chunk, encoding, cb) {
4407 var ts = this._transformState;
4408 ts.writecb = cb;
4409 ts.writechunk = chunk;
4410 ts.writeencoding = encoding;
4411 if (!ts.transforming) {
4412 var rs = this._readableState;
4413 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
4414 }
4415};
4416
4417// Doesn't matter what the args are here.
4418// _transform does all the work.
4419// That we got here means that the readable side wants more data.
4420Transform.prototype._read = function (n) {
4421 var ts = this._transformState;
4422
4423 if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
4424 ts.transforming = true;
4425 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
4426 } else {
4427 // mark that we need a transform, so that any data that comes in
4428 // will get processed, now that we've asked for it.
4429 ts.needTransform = true;
4430 }
4431};
4432
4433function done(stream, er, data) {
4434 if (er) return stream.emit('error', er);
4435
4436 if (data !== null && data !== undefined) stream.push(data);
4437
4438 // if there's nothing in the write buffer, then that means
4439 // that nothing more will ever be provided
4440 var ws = stream._writableState;
4441 var ts = stream._transformState;
4442
4443 if (ws.length) throw new Error('Calling transform done when ws.length != 0');
4444
4445 if (ts.transforming) throw new Error('Calling transform done when still transforming');
4446
4447 return stream.push(null);
4448}
4449},{"./_stream_duplex":15,"core-util-is":6,"inherits":9}],19:[function(require,module,exports){
4450(function (process){
4451// A bit simpler than readable streams.
4452// Implement an async ._write(chunk, encoding, cb), and it'll handle all
4453// the drain event emission and buffering.
4454
4455'use strict';
4456
4457module.exports = Writable;
4458
4459/*<replacement>*/
4460var processNextTick = require('process-nextick-args');
4461/*</replacement>*/
4462
4463/*<replacement>*/
4464var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick;
4465/*</replacement>*/
4466
4467/*<replacement>*/
4468var Duplex;
4469/*</replacement>*/
4470
4471Writable.WritableState = WritableState;
4472
4473/*<replacement>*/
4474var util = require('core-util-is');
4475util.inherits = require('inherits');
4476/*</replacement>*/
4477
4478/*<replacement>*/
4479var internalUtil = {
4480 deprecate: require('util-deprecate')
4481};
4482/*</replacement>*/
4483
4484/*<replacement>*/
4485var Stream = require('./internal/streams/stream');
4486/*</replacement>*/
4487
4488var Buffer = require('buffer').Buffer;
4489/*<replacement>*/
4490var bufferShim = require('buffer-shims');
4491/*</replacement>*/
4492
4493util.inherits(Writable, Stream);
4494
4495function nop() {}
4496
4497function WriteReq(chunk, encoding, cb) {
4498 this.chunk = chunk;
4499 this.encoding = encoding;
4500 this.callback = cb;
4501 this.next = null;
4502}
4503
4504function WritableState(options, stream) {
4505 Duplex = Duplex || require('./_stream_duplex');
4506
4507 options = options || {};
4508
4509 // object stream flag to indicate whether or not this stream
4510 // contains buffers or objects.
4511 this.objectMode = !!options.objectMode;
4512
4513 if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
4514
4515 // the point at which write() starts returning false
4516 // Note: 0 is a valid value, means that we always return false if
4517 // the entire buffer is not flushed immediately on write()
4518 var hwm = options.highWaterMark;
4519 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
4520 this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
4521
4522 // cast to ints.
4523 this.highWaterMark = ~~this.highWaterMark;
4524
4525 // drain event flag.
4526 this.needDrain = false;
4527 // at the start of calling end()
4528 this.ending = false;
4529 // when end() has been called, and returned
4530 this.ended = false;
4531 // when 'finish' is emitted
4532 this.finished = false;
4533
4534 // should we decode strings into buffers before passing to _write?
4535 // this is here so that some node-core streams can optimize string
4536 // handling at a lower level.
4537 var noDecode = options.decodeStrings === false;
4538 this.decodeStrings = !noDecode;
4539
4540 // Crypto is kind of old and crusty. Historically, its default string
4541 // encoding is 'binary' so we have to make this configurable.
4542 // Everything else in the universe uses 'utf8', though.
4543 this.defaultEncoding = options.defaultEncoding || 'utf8';
4544
4545 // not an actual buffer we keep track of, but a measurement
4546 // of how much we're waiting to get pushed to some underlying
4547 // socket or file.
4548 this.length = 0;
4549
4550 // a flag to see when we're in the middle of a write.
4551 this.writing = false;
4552
4553 // when true all writes will be buffered until .uncork() call
4554 this.corked = 0;
4555
4556 // a flag to be able to tell if the onwrite cb is called immediately,
4557 // or on a later tick. We set this to true at first, because any
4558 // actions that shouldn't happen until "later" should generally also
4559 // not happen before the first write call.
4560 this.sync = true;
4561
4562 // a flag to know if we're processing previously buffered items, which
4563 // may call the _write() callback in the same tick, so that we don't
4564 // end up in an overlapped onwrite situation.
4565 this.bufferProcessing = false;
4566
4567 // the callback that's passed to _write(chunk,cb)
4568 this.onwrite = function (er) {
4569 onwrite(stream, er);
4570 };
4571
4572 // the callback that the user supplies to write(chunk,encoding,cb)
4573 this.writecb = null;
4574
4575 // the amount that is being written when _write is called.
4576 this.writelen = 0;
4577
4578 this.bufferedRequest = null;
4579 this.lastBufferedRequest = null;
4580
4581 // number of pending user-supplied write callbacks
4582 // this must be 0 before 'finish' can be emitted
4583 this.pendingcb = 0;
4584
4585 // emit prefinish if the only thing we're waiting for is _write cbs
4586 // This is relevant for synchronous Transform streams
4587 this.prefinished = false;
4588
4589 // True if the error was already emitted and should not be thrown again
4590 this.errorEmitted = false;
4591
4592 // count buffered requests
4593 this.bufferedRequestCount = 0;
4594
4595 // allocate the first CorkedRequest, there is always
4596 // one allocated and free to use, and we maintain at most two
4597 this.corkedRequestsFree = new CorkedRequest(this);
4598}
4599
4600WritableState.prototype.getBuffer = function getBuffer() {
4601 var current = this.bufferedRequest;
4602 var out = [];
4603 while (current) {
4604 out.push(current);
4605 current = current.next;
4606 }
4607 return out;
4608};
4609
4610(function () {
4611 try {
4612 Object.defineProperty(WritableState.prototype, 'buffer', {
4613 get: internalUtil.deprecate(function () {
4614 return this.getBuffer();
4615 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.')
4616 });
4617 } catch (_) {}
4618})();
4619
4620// Test _writableState for inheritance to account for Duplex streams,
4621// whose prototype chain only points to Readable.
4622var realHasInstance;
4623if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
4624 realHasInstance = Function.prototype[Symbol.hasInstance];
4625 Object.defineProperty(Writable, Symbol.hasInstance, {
4626 value: function (object) {
4627 if (realHasInstance.call(this, object)) return true;
4628
4629 return object && object._writableState instanceof WritableState;
4630 }
4631 });
4632} else {
4633 realHasInstance = function (object) {
4634 return object instanceof this;
4635 };
4636}
4637
4638function Writable(options) {
4639 Duplex = Duplex || require('./_stream_duplex');
4640
4641 // Writable ctor is applied to Duplexes, too.
4642 // `realHasInstance` is necessary because using plain `instanceof`
4643 // would return false, as no `_writableState` property is attached.
4644
4645 // Trying to use the custom `instanceof` for Writable here will also break the
4646 // Node.js LazyTransform implementation, which has a non-trivial getter for
4647 // `_writableState` that would lead to infinite recursion.
4648 if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
4649 return new Writable(options);
4650 }
4651
4652 this._writableState = new WritableState(options, this);
4653
4654 // legacy.
4655 this.writable = true;
4656
4657 if (options) {
4658 if (typeof options.write === 'function') this._write = options.write;
4659
4660 if (typeof options.writev === 'function') this._writev = options.writev;
4661 }
4662
4663 Stream.call(this);
4664}
4665
4666// Otherwise people can pipe Writable streams, which is just wrong.
4667Writable.prototype.pipe = function () {
4668 this.emit('error', new Error('Cannot pipe, not readable'));
4669};
4670
4671function writeAfterEnd(stream, cb) {
4672 var er = new Error('write after end');
4673 // TODO: defer error events consistently everywhere, not just the cb
4674 stream.emit('error', er);
4675 processNextTick(cb, er);
4676}
4677
4678// Checks that a user-supplied chunk is valid, especially for the particular
4679// mode the stream is in. Currently this means that `null` is never accepted
4680// and undefined/non-string values are only allowed in object mode.
4681function validChunk(stream, state, chunk, cb) {
4682 var valid = true;
4683 var er = false;
4684
4685 if (chunk === null) {
4686 er = new TypeError('May not write null values to stream');
4687 } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
4688 er = new TypeError('Invalid non-string/buffer chunk');
4689 }
4690 if (er) {
4691 stream.emit('error', er);
4692 processNextTick(cb, er);
4693 valid = false;
4694 }
4695 return valid;
4696}
4697
4698Writable.prototype.write = function (chunk, encoding, cb) {
4699 var state = this._writableState;
4700 var ret = false;
4701 var isBuf = Buffer.isBuffer(chunk);
4702
4703 if (typeof encoding === 'function') {
4704 cb = encoding;
4705 encoding = null;
4706 }
4707
4708 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
4709
4710 if (typeof cb !== 'function') cb = nop;
4711
4712 if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
4713 state.pendingcb++;
4714 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
4715 }
4716
4717 return ret;
4718};
4719
4720Writable.prototype.cork = function () {
4721 var state = this._writableState;
4722
4723 state.corked++;
4724};
4725
4726Writable.prototype.uncork = function () {
4727 var state = this._writableState;
4728
4729 if (state.corked) {
4730 state.corked--;
4731
4732 if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
4733 }
4734};
4735
4736Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
4737 // node::ParseEncoding() requires lower case.
4738 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
4739 if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);
4740 this._writableState.defaultEncoding = encoding;
4741 return this;
4742};
4743
4744function decodeChunk(state, chunk, encoding) {
4745 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
4746 chunk = bufferShim.from(chunk, encoding);
4747 }
4748 return chunk;
4749}
4750
4751// if we're already writing something, then just put this
4752// in the queue, and wait our turn. Otherwise, call _write
4753// If we return false, then we need a drain event, so set that flag.
4754function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
4755 if (!isBuf) {
4756 chunk = decodeChunk(state, chunk, encoding);
4757 if (Buffer.isBuffer(chunk)) encoding = 'buffer';
4758 }
4759 var len = state.objectMode ? 1 : chunk.length;
4760
4761 state.length += len;
4762
4763 var ret = state.length < state.highWaterMark;
4764 // we must ensure that previous needDrain will not be reset to false.
4765 if (!ret) state.needDrain = true;
4766
4767 if (state.writing || state.corked) {
4768 var last = state.lastBufferedRequest;
4769 state.lastBufferedRequest = new WriteReq(chunk, encoding, cb);
4770 if (last) {
4771 last.next = state.lastBufferedRequest;
4772 } else {
4773 state.bufferedRequest = state.lastBufferedRequest;
4774 }
4775 state.bufferedRequestCount += 1;
4776 } else {
4777 doWrite(stream, state, false, len, chunk, encoding, cb);
4778 }
4779
4780 return ret;
4781}
4782
4783function doWrite(stream, state, writev, len, chunk, encoding, cb) {
4784 state.writelen = len;
4785 state.writecb = cb;
4786 state.writing = true;
4787 state.sync = true;
4788 if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
4789 state.sync = false;
4790}
4791
4792function onwriteError(stream, state, sync, er, cb) {
4793 --state.pendingcb;
4794 if (sync) processNextTick(cb, er);else cb(er);
4795
4796 stream._writableState.errorEmitted = true;
4797 stream.emit('error', er);
4798}
4799
4800function onwriteStateUpdate(state) {
4801 state.writing = false;
4802 state.writecb = null;
4803 state.length -= state.writelen;
4804 state.writelen = 0;
4805}
4806
4807function onwrite(stream, er) {
4808 var state = stream._writableState;
4809 var sync = state.sync;
4810 var cb = state.writecb;
4811
4812 onwriteStateUpdate(state);
4813
4814 if (er) onwriteError(stream, state, sync, er, cb);else {
4815 // Check if we're actually ready to finish, but don't emit yet
4816 var finished = needFinish(state);
4817
4818 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
4819 clearBuffer(stream, state);
4820 }
4821
4822 if (sync) {
4823 /*<replacement>*/
4824 asyncWrite(afterWrite, stream, state, finished, cb);
4825 /*</replacement>*/
4826 } else {
4827 afterWrite(stream, state, finished, cb);
4828 }
4829 }
4830}
4831
4832function afterWrite(stream, state, finished, cb) {
4833 if (!finished) onwriteDrain(stream, state);
4834 state.pendingcb--;
4835 cb();
4836 finishMaybe(stream, state);
4837}
4838
4839// Must force callback to be called on nextTick, so that we don't
4840// emit 'drain' before the write() consumer gets the 'false' return
4841// value, and has a chance to attach a 'drain' listener.
4842function onwriteDrain(stream, state) {
4843 if (state.length === 0 && state.needDrain) {
4844 state.needDrain = false;
4845 stream.emit('drain');
4846 }
4847}
4848
4849// if there's something in the buffer waiting, then process it
4850function clearBuffer(stream, state) {
4851 state.bufferProcessing = true;
4852 var entry = state.bufferedRequest;
4853
4854 if (stream._writev && entry && entry.next) {
4855 // Fast case, write everything using _writev()
4856 var l = state.bufferedRequestCount;
4857 var buffer = new Array(l);
4858 var holder = state.corkedRequestsFree;
4859 holder.entry = entry;
4860
4861 var count = 0;
4862 while (entry) {
4863 buffer[count] = entry;
4864 entry = entry.next;
4865 count += 1;
4866 }
4867
4868 doWrite(stream, state, true, state.length, buffer, '', holder.finish);
4869
4870 // doWrite is almost always async, defer these to save a bit of time
4871 // as the hot path ends with doWrite
4872 state.pendingcb++;
4873 state.lastBufferedRequest = null;
4874 if (holder.next) {
4875 state.corkedRequestsFree = holder.next;
4876 holder.next = null;
4877 } else {
4878 state.corkedRequestsFree = new CorkedRequest(state);
4879 }
4880 } else {
4881 // Slow case, write chunks one-by-one
4882 while (entry) {
4883 var chunk = entry.chunk;
4884 var encoding = entry.encoding;
4885 var cb = entry.callback;
4886 var len = state.objectMode ? 1 : chunk.length;
4887
4888 doWrite(stream, state, false, len, chunk, encoding, cb);
4889 entry = entry.next;
4890 // if we didn't call the onwrite immediately, then
4891 // it means that we need to wait until it does.
4892 // also, that means that the chunk and cb are currently
4893 // being processed, so move the buffer counter past them.
4894 if (state.writing) {
4895 break;
4896 }
4897 }
4898
4899 if (entry === null) state.lastBufferedRequest = null;
4900 }
4901
4902 state.bufferedRequestCount = 0;
4903 state.bufferedRequest = entry;
4904 state.bufferProcessing = false;
4905}
4906
4907Writable.prototype._write = function (chunk, encoding, cb) {
4908 cb(new Error('_write() is not implemented'));
4909};
4910
4911Writable.prototype._writev = null;
4912
4913Writable.prototype.end = function (chunk, encoding, cb) {
4914 var state = this._writableState;
4915
4916 if (typeof chunk === 'function') {
4917 cb = chunk;
4918 chunk = null;
4919 encoding = null;
4920 } else if (typeof encoding === 'function') {
4921 cb = encoding;
4922 encoding = null;
4923 }
4924
4925 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
4926
4927 // .end() fully uncorks
4928 if (state.corked) {
4929 state.corked = 1;
4930 this.uncork();
4931 }
4932
4933 // ignore unnecessary end() calls.
4934 if (!state.ending && !state.finished) endWritable(this, state, cb);
4935};
4936
4937function needFinish(state) {
4938 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
4939}
4940
4941function prefinish(stream, state) {
4942 if (!state.prefinished) {
4943 state.prefinished = true;
4944 stream.emit('prefinish');
4945 }
4946}
4947
4948function finishMaybe(stream, state) {
4949 var need = needFinish(state);
4950 if (need) {
4951 if (state.pendingcb === 0) {
4952 prefinish(stream, state);
4953 state.finished = true;
4954 stream.emit('finish');
4955 } else {
4956 prefinish(stream, state);
4957 }
4958 }
4959 return need;
4960}
4961
4962function endWritable(stream, state, cb) {
4963 state.ending = true;
4964 finishMaybe(stream, state);
4965 if (cb) {
4966 if (state.finished) processNextTick(cb);else stream.once('finish', cb);
4967 }
4968 state.ended = true;
4969 stream.writable = false;
4970}
4971
4972// It seems a linked list but it is not
4973// there will be only 2 of these for each stream
4974function CorkedRequest(state) {
4975 var _this = this;
4976
4977 this.next = null;
4978 this.entry = null;
4979 this.finish = function (err) {
4980 var entry = _this.entry;
4981 _this.entry = null;
4982 while (entry) {
4983 var cb = entry.callback;
4984 state.pendingcb--;
4985 cb(err);
4986 entry = entry.next;
4987 }
4988 if (state.corkedRequestsFree) {
4989 state.corkedRequestsFree.next = _this;
4990 } else {
4991 state.corkedRequestsFree = _this;
4992 }
4993 };
4994}
4995}).call(this,require('_process'))
4996},{"./_stream_duplex":15,"./internal/streams/stream":21,"_process":13,"buffer":5,"buffer-shims":4,"core-util-is":6,"inherits":9,"process-nextick-args":12,"util-deprecate":30}],20:[function(require,module,exports){
4997'use strict';
4998
4999var Buffer = require('buffer').Buffer;
5000/*<replacement>*/
5001var bufferShim = require('buffer-shims');
5002/*</replacement>*/
5003
5004module.exports = BufferList;
5005
5006function BufferList() {
5007 this.head = null;
5008 this.tail = null;
5009 this.length = 0;
5010}
5011
5012BufferList.prototype.push = function (v) {
5013 var entry = { data: v, next: null };
5014 if (this.length > 0) this.tail.next = entry;else this.head = entry;
5015 this.tail = entry;
5016 ++this.length;
5017};
5018
5019BufferList.prototype.unshift = function (v) {
5020 var entry = { data: v, next: this.head };
5021 if (this.length === 0) this.tail = entry;
5022 this.head = entry;
5023 ++this.length;
5024};
5025
5026BufferList.prototype.shift = function () {
5027 if (this.length === 0) return;
5028 var ret = this.head.data;
5029 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
5030 --this.length;
5031 return ret;
5032};
5033
5034BufferList.prototype.clear = function () {
5035 this.head = this.tail = null;
5036 this.length = 0;
5037};
5038
5039BufferList.prototype.join = function (s) {
5040 if (this.length === 0) return '';
5041 var p = this.head;
5042 var ret = '' + p.data;
5043 while (p = p.next) {
5044 ret += s + p.data;
5045 }return ret;
5046};
5047
5048BufferList.prototype.concat = function (n) {
5049 if (this.length === 0) return bufferShim.alloc(0);
5050 if (this.length === 1) return this.head.data;
5051 var ret = bufferShim.allocUnsafe(n >>> 0);
5052 var p = this.head;
5053 var i = 0;
5054 while (p) {
5055 p.data.copy(ret, i);
5056 i += p.data.length;
5057 p = p.next;
5058 }
5059 return ret;
5060};
5061},{"buffer":5,"buffer-shims":4}],21:[function(require,module,exports){
5062module.exports = require('events').EventEmitter;
5063
5064},{"events":7}],22:[function(require,module,exports){
5065'use strict';
5066
5067var Buffer = require('safe-buffer').Buffer;
5068
5069var isEncoding = Buffer.isEncoding || function (encoding) {
5070 encoding = '' + encoding;
5071 switch (encoding && encoding.toLowerCase()) {
5072 case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':
5073 return true;
5074 default:
5075 return false;
5076 }
5077};
5078
5079function _normalizeEncoding(enc) {
5080 if (!enc) return 'utf8';
5081 var retried;
5082 while (true) {
5083 switch (enc) {
5084 case 'utf8':
5085 case 'utf-8':
5086 return 'utf8';
5087 case 'ucs2':
5088 case 'ucs-2':
5089 case 'utf16le':
5090 case 'utf-16le':
5091 return 'utf16le';
5092 case 'latin1':
5093 case 'binary':
5094 return 'latin1';
5095 case 'base64':
5096 case 'ascii':
5097 case 'hex':
5098 return enc;
5099 default:
5100 if (retried) return; // undefined
5101 enc = ('' + enc).toLowerCase();
5102 retried = true;
5103 }
5104 }
5105};
5106
5107// Do not cache `Buffer.isEncoding` when checking encoding names as some
5108// modules monkey-patch it to support additional encodings
5109function normalizeEncoding(enc) {
5110 var nenc = _normalizeEncoding(enc);
5111 if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
5112 return nenc || enc;
5113}
5114
5115// StringDecoder provides an interface for efficiently splitting a series of
5116// buffers into a series of JS strings without breaking apart multi-byte
5117// characters.
5118exports.StringDecoder = StringDecoder;
5119function StringDecoder(encoding) {
5120 this.encoding = normalizeEncoding(encoding);
5121 var nb;
5122 switch (this.encoding) {
5123 case 'utf16le':
5124 this.text = utf16Text;
5125 this.end = utf16End;
5126 nb = 4;
5127 break;
5128 case 'utf8':
5129 this.fillLast = utf8FillLast;
5130 nb = 4;
5131 break;
5132 case 'base64':
5133 this.text = base64Text;
5134 this.end = base64End;
5135 nb = 3;
5136 break;
5137 default:
5138 this.write = simpleWrite;
5139 this.end = simpleEnd;
5140 return;
5141 }
5142 this.lastNeed = 0;
5143 this.lastTotal = 0;
5144 this.lastChar = Buffer.allocUnsafe(nb);
5145}
5146
5147StringDecoder.prototype.write = function (buf) {
5148 if (buf.length === 0) return '';
5149 var r;
5150 var i;
5151 if (this.lastNeed) {
5152 r = this.fillLast(buf);
5153 if (r === undefined) return '';
5154 i = this.lastNeed;
5155 this.lastNeed = 0;
5156 } else {
5157 i = 0;
5158 }
5159 if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
5160 return r || '';
5161};
5162
5163StringDecoder.prototype.end = utf8End;
5164
5165// Returns only complete characters in a Buffer
5166StringDecoder.prototype.text = utf8Text;
5167
5168// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
5169StringDecoder.prototype.fillLast = function (buf) {
5170 if (this.lastNeed <= buf.length) {
5171 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
5172 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
5173 }
5174 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
5175 this.lastNeed -= buf.length;
5176};
5177
5178// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
5179// continuation byte.
5180function utf8CheckByte(byte) {
5181 if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
5182 return -1;
5183}
5184
5185// Checks at most 3 bytes at the end of a Buffer in order to detect an
5186// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
5187// needed to complete the UTF-8 character (if applicable) are returned.
5188function utf8CheckIncomplete(self, buf, i) {
5189 var j = buf.length - 1;
5190 if (j < i) return 0;
5191 var nb = utf8CheckByte(buf[j]);
5192 if (nb >= 0) {
5193 if (nb > 0) self.lastNeed = nb - 1;
5194 return nb;
5195 }
5196 if (--j < i) return 0;
5197 nb = utf8CheckByte(buf[j]);
5198 if (nb >= 0) {
5199 if (nb > 0) self.lastNeed = nb - 2;
5200 return nb;
5201 }
5202 if (--j < i) return 0;
5203 nb = utf8CheckByte(buf[j]);
5204 if (nb >= 0) {
5205 if (nb > 0) {
5206 if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
5207 }
5208 return nb;
5209 }
5210 return 0;
5211}
5212
5213// Validates as many continuation bytes for a multi-byte UTF-8 character as
5214// needed or are available. If we see a non-continuation byte where we expect
5215// one, we "replace" the validated continuation bytes we've seen so far with
5216// UTF-8 replacement characters ('\ufffd'), to match v8's UTF-8 decoding
5217// behavior. The continuation byte check is included three times in the case
5218// where all of the continuation bytes for a character exist in the same buffer.
5219// It is also done this way as a slight performance increase instead of using a
5220// loop.
5221function utf8CheckExtraBytes(self, buf, p) {
5222 if ((buf[0] & 0xC0) !== 0x80) {
5223 self.lastNeed = 0;
5224 return '\ufffd'.repeat(p);
5225 }
5226 if (self.lastNeed > 1 && buf.length > 1) {
5227 if ((buf[1] & 0xC0) !== 0x80) {
5228 self.lastNeed = 1;
5229 return '\ufffd'.repeat(p + 1);
5230 }
5231 if (self.lastNeed > 2 && buf.length > 2) {
5232 if ((buf[2] & 0xC0) !== 0x80) {
5233 self.lastNeed = 2;
5234 return '\ufffd'.repeat(p + 2);
5235 }
5236 }
5237 }
5238}
5239
5240// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
5241function utf8FillLast(buf) {
5242 var p = this.lastTotal - this.lastNeed;
5243 var r = utf8CheckExtraBytes(this, buf, p);
5244 if (r !== undefined) return r;
5245 if (this.lastNeed <= buf.length) {
5246 buf.copy(this.lastChar, p, 0, this.lastNeed);
5247 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
5248 }
5249 buf.copy(this.lastChar, p, 0, buf.length);
5250 this.lastNeed -= buf.length;
5251}
5252
5253// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
5254// partial character, the character's bytes are buffered until the required
5255// number of bytes are available.
5256function utf8Text(buf, i) {
5257 var total = utf8CheckIncomplete(this, buf, i);
5258 if (!this.lastNeed) return buf.toString('utf8', i);
5259 this.lastTotal = total;
5260 var end = buf.length - (total - this.lastNeed);
5261 buf.copy(this.lastChar, 0, end);
5262 return buf.toString('utf8', i, end);
5263}
5264
5265// For UTF-8, a replacement character for each buffered byte of a (partial)
5266// character needs to be added to the output.
5267function utf8End(buf) {
5268 var r = buf && buf.length ? this.write(buf) : '';
5269 if (this.lastNeed) return r + '\ufffd'.repeat(this.lastTotal - this.lastNeed);
5270 return r;
5271}
5272
5273// UTF-16LE typically needs two bytes per character, but even if we have an even
5274// number of bytes available, we need to check if we end on a leading/high
5275// surrogate. In that case, we need to wait for the next two bytes in order to
5276// decode the last character properly.
5277function utf16Text(buf, i) {
5278 if ((buf.length - i) % 2 === 0) {
5279 var r = buf.toString('utf16le', i);
5280 if (r) {
5281 var c = r.charCodeAt(r.length - 1);
5282 if (c >= 0xD800 && c <= 0xDBFF) {
5283 this.lastNeed = 2;
5284 this.lastTotal = 4;
5285 this.lastChar[0] = buf[buf.length - 2];
5286 this.lastChar[1] = buf[buf.length - 1];
5287 return r.slice(0, -1);
5288 }
5289 }
5290 return r;
5291 }
5292 this.lastNeed = 1;
5293 this.lastTotal = 2;
5294 this.lastChar[0] = buf[buf.length - 1];
5295 return buf.toString('utf16le', i, buf.length - 1);
5296}
5297
5298// For UTF-16LE we do not explicitly append special replacement characters if we
5299// end on a partial character, we simply let v8 handle that.
5300function utf16End(buf) {
5301 var r = buf && buf.length ? this.write(buf) : '';
5302 if (this.lastNeed) {
5303 var end = this.lastTotal - this.lastNeed;
5304 return r + this.lastChar.toString('utf16le', 0, end);
5305 }
5306 return r;
5307}
5308
5309function base64Text(buf, i) {
5310 var n = (buf.length - i) % 3;
5311 if (n === 0) return buf.toString('base64', i);
5312 this.lastNeed = 3 - n;
5313 this.lastTotal = 3;
5314 if (n === 1) {
5315 this.lastChar[0] = buf[buf.length - 1];
5316 } else {
5317 this.lastChar[0] = buf[buf.length - 2];
5318 this.lastChar[1] = buf[buf.length - 1];
5319 }
5320 return buf.toString('base64', i, buf.length - n);
5321}
5322
5323function base64End(buf) {
5324 var r = buf && buf.length ? this.write(buf) : '';
5325 if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
5326 return r;
5327}
5328
5329// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
5330function simpleWrite(buf) {
5331 return buf.toString(this.encoding);
5332}
5333
5334function simpleEnd(buf) {
5335 return buf && buf.length ? this.write(buf) : '';
5336}
5337},{"safe-buffer":27}],23:[function(require,module,exports){
5338module.exports = require('./readable').PassThrough
5339
5340},{"./readable":24}],24:[function(require,module,exports){
5341exports = module.exports = require('./lib/_stream_readable.js');
5342exports.Stream = exports;
5343exports.Readable = exports;
5344exports.Writable = require('./lib/_stream_writable.js');
5345exports.Duplex = require('./lib/_stream_duplex.js');
5346exports.Transform = require('./lib/_stream_transform.js');
5347exports.PassThrough = require('./lib/_stream_passthrough.js');
5348
5349},{"./lib/_stream_duplex.js":15,"./lib/_stream_passthrough.js":16,"./lib/_stream_readable.js":17,"./lib/_stream_transform.js":18,"./lib/_stream_writable.js":19}],25:[function(require,module,exports){
5350module.exports = require('./readable').Transform
5351
5352},{"./readable":24}],26:[function(require,module,exports){
5353module.exports = require('./lib/_stream_writable.js');
5354
5355},{"./lib/_stream_writable.js":19}],27:[function(require,module,exports){
5356module.exports = require('buffer')
5357
5358},{"buffer":5}],28:[function(require,module,exports){
5359// Copyright Joyent, Inc. and other Node contributors.
5360//
5361// Permission is hereby granted, free of charge, to any person obtaining a
5362// copy of this software and associated documentation files (the
5363// "Software"), to deal in the Software without restriction, including
5364// without limitation the rights to use, copy, modify, merge, publish,
5365// distribute, sublicense, and/or sell copies of the Software, and to permit
5366// persons to whom the Software is furnished to do so, subject to the
5367// following conditions:
5368//
5369// The above copyright notice and this permission notice shall be included
5370// in all copies or substantial portions of the Software.
5371//
5372// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
5373// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
5374// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
5375// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
5376// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
5377// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
5378// USE OR OTHER DEALINGS IN THE SOFTWARE.
5379
5380module.exports = Stream;
5381
5382var EE = require('events').EventEmitter;
5383var inherits = require('inherits');
5384
5385inherits(Stream, EE);
5386Stream.Readable = require('readable-stream/readable.js');
5387Stream.Writable = require('readable-stream/writable.js');
5388Stream.Duplex = require('readable-stream/duplex.js');
5389Stream.Transform = require('readable-stream/transform.js');
5390Stream.PassThrough = require('readable-stream/passthrough.js');
5391
5392// Backwards-compat with node 0.4.x
5393Stream.Stream = Stream;
5394
5395
5396
5397// old-style streams. Note that the pipe method (the only relevant
5398// part of this class) is overridden in the Readable class.
5399
5400function Stream() {
5401 EE.call(this);
5402}
5403
5404Stream.prototype.pipe = function(dest, options) {
5405 var source = this;
5406
5407 function ondata(chunk) {
5408 if (dest.writable) {
5409 if (false === dest.write(chunk) && source.pause) {
5410 source.pause();
5411 }
5412 }
5413 }
5414
5415 source.on('data', ondata);
5416
5417 function ondrain() {
5418 if (source.readable && source.resume) {
5419 source.resume();
5420 }
5421 }
5422
5423 dest.on('drain', ondrain);
5424
5425 // If the 'end' option is not supplied, dest.end() will be called when
5426 // source gets the 'end' or 'close' events. Only dest.end() once.
5427 if (!dest._isStdio && (!options || options.end !== false)) {
5428 source.on('end', onend);
5429 source.on('close', onclose);
5430 }
5431
5432 var didOnEnd = false;
5433 function onend() {
5434 if (didOnEnd) return;
5435 didOnEnd = true;
5436
5437 dest.end();
5438 }
5439
5440
5441 function onclose() {
5442 if (didOnEnd) return;
5443 didOnEnd = true;
5444
5445 if (typeof dest.destroy === 'function') dest.destroy();
5446 }
5447
5448 // don't leave dangling pipes when there are errors.
5449 function onerror(er) {
5450 cleanup();
5451 if (EE.listenerCount(this, 'error') === 0) {
5452 throw er; // Unhandled stream error in pipe.
5453 }
5454 }
5455
5456 source.on('error', onerror);
5457 dest.on('error', onerror);
5458
5459 // remove all the event listeners that were added.
5460 function cleanup() {
5461 source.removeListener('data', ondata);
5462 dest.removeListener('drain', ondrain);
5463
5464 source.removeListener('end', onend);
5465 source.removeListener('close', onclose);
5466
5467 source.removeListener('error', onerror);
5468 dest.removeListener('error', onerror);
5469
5470 source.removeListener('end', cleanup);
5471 source.removeListener('close', cleanup);
5472
5473 dest.removeListener('close', cleanup);
5474 }
5475
5476 source.on('end', cleanup);
5477 source.on('close', cleanup);
5478
5479 dest.on('close', cleanup);
5480
5481 dest.emit('pipe', source);
5482
5483 // Allow for unix-like usage: A.pipe(B).pipe(C)
5484 return dest;
5485};
5486
5487},{"events":7,"inherits":9,"readable-stream/duplex.js":14,"readable-stream/passthrough.js":23,"readable-stream/readable.js":24,"readable-stream/transform.js":25,"readable-stream/writable.js":26}],29:[function(require,module,exports){
5488// Copyright Joyent, Inc. and other Node contributors.
5489//
5490// Permission is hereby granted, free of charge, to any person obtaining a
5491// copy of this software and associated documentation files (the
5492// "Software"), to deal in the Software without restriction, including
5493// without limitation the rights to use, copy, modify, merge, publish,
5494// distribute, sublicense, and/or sell copies of the Software, and to permit
5495// persons to whom the Software is furnished to do so, subject to the
5496// following conditions:
5497//
5498// The above copyright notice and this permission notice shall be included
5499// in all copies or substantial portions of the Software.
5500//
5501// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
5502// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
5503// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
5504// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
5505// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
5506// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
5507// USE OR OTHER DEALINGS IN THE SOFTWARE.
5508
5509var Buffer = require('buffer').Buffer;
5510
5511var isBufferEncoding = Buffer.isEncoding
5512 || function(encoding) {
5513 switch (encoding && encoding.toLowerCase()) {
5514 case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true;
5515 default: return false;
5516 }
5517 }
5518
5519
5520function assertEncoding(encoding) {
5521 if (encoding && !isBufferEncoding(encoding)) {
5522 throw new Error('Unknown encoding: ' + encoding);
5523 }
5524}
5525
5526// StringDecoder provides an interface for efficiently splitting a series of
5527// buffers into a series of JS strings without breaking apart multi-byte
5528// characters. CESU-8 is handled as part of the UTF-8 encoding.
5529//
5530// @TODO Handling all encodings inside a single object makes it very difficult
5531// to reason about this code, so it should be split up in the future.
5532// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
5533// points as used by CESU-8.
5534var StringDecoder = exports.StringDecoder = function(encoding) {
5535 this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
5536 assertEncoding(encoding);
5537 switch (this.encoding) {
5538 case 'utf8':
5539 // CESU-8 represents each of Surrogate Pair by 3-bytes
5540 this.surrogateSize = 3;
5541 break;
5542 case 'ucs2':
5543 case 'utf16le':
5544 // UTF-16 represents each of Surrogate Pair by 2-bytes
5545 this.surrogateSize = 2;
5546 this.detectIncompleteChar = utf16DetectIncompleteChar;
5547 break;
5548 case 'base64':
5549 // Base-64 stores 3 bytes in 4 chars, and pads the remainder.
5550 this.surrogateSize = 3;
5551 this.detectIncompleteChar = base64DetectIncompleteChar;
5552 break;
5553 default:
5554 this.write = passThroughWrite;
5555 return;
5556 }
5557
5558 // Enough space to store all bytes of a single character. UTF-8 needs 4
5559 // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
5560 this.charBuffer = new Buffer(6);
5561 // Number of bytes received for the current incomplete multi-byte character.
5562 this.charReceived = 0;
5563 // Number of bytes expected for the current incomplete multi-byte character.
5564 this.charLength = 0;
5565};
5566
5567
5568// write decodes the given buffer and returns it as JS string that is
5569// guaranteed to not contain any partial multi-byte characters. Any partial
5570// character found at the end of the buffer is buffered up, and will be
5571// returned when calling write again with the remaining bytes.
5572//
5573// Note: Converting a Buffer containing an orphan surrogate to a String
5574// currently works, but converting a String to a Buffer (via `new Buffer`, or
5575// Buffer#write) will replace incomplete surrogates with the unicode
5576// replacement character. See https://codereview.chromium.org/121173009/ .
5577StringDecoder.prototype.write = function(buffer) {
5578 var charStr = '';
5579 // if our last write ended with an incomplete multibyte character
5580 while (this.charLength) {
5581 // determine how many remaining bytes this buffer has to offer for this char
5582 var available = (buffer.length >= this.charLength - this.charReceived) ?
5583 this.charLength - this.charReceived :
5584 buffer.length;
5585
5586 // add the new bytes to the char buffer
5587 buffer.copy(this.charBuffer, this.charReceived, 0, available);
5588 this.charReceived += available;
5589
5590 if (this.charReceived < this.charLength) {
5591 // still not enough chars in this buffer? wait for more ...
5592 return '';
5593 }
5594
5595 // remove bytes belonging to the current character from the buffer
5596 buffer = buffer.slice(available, buffer.length);
5597
5598 // get the character that was split
5599 charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
5600
5601 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
5602 var charCode = charStr.charCodeAt(charStr.length - 1);
5603 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
5604 this.charLength += this.surrogateSize;
5605 charStr = '';
5606 continue;
5607 }
5608 this.charReceived = this.charLength = 0;
5609
5610 // if there are no more bytes in this buffer, just emit our char
5611 if (buffer.length === 0) {
5612 return charStr;
5613 }
5614 break;
5615 }
5616
5617 // determine and set charLength / charReceived
5618 this.detectIncompleteChar(buffer);
5619
5620 var end = buffer.length;
5621 if (this.charLength) {
5622 // buffer the incomplete character bytes we got
5623 buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
5624 end -= this.charReceived;
5625 }
5626
5627 charStr += buffer.toString(this.encoding, 0, end);
5628
5629 var end = charStr.length - 1;
5630 var charCode = charStr.charCodeAt(end);
5631 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
5632 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
5633 var size = this.surrogateSize;
5634 this.charLength += size;
5635 this.charReceived += size;
5636 this.charBuffer.copy(this.charBuffer, size, 0, size);
5637 buffer.copy(this.charBuffer, 0, 0, size);
5638 return charStr.substring(0, end);
5639 }
5640
5641 // or just emit the charStr
5642 return charStr;
5643};
5644
5645// detectIncompleteChar determines if there is an incomplete UTF-8 character at
5646// the end of the given buffer. If so, it sets this.charLength to the byte
5647// length that character, and sets this.charReceived to the number of bytes
5648// that are available for this character.
5649StringDecoder.prototype.detectIncompleteChar = function(buffer) {
5650 // determine how many bytes we have to check at the end of this buffer
5651 var i = (buffer.length >= 3) ? 3 : buffer.length;
5652
5653 // Figure out if one of the last i bytes of our buffer announces an
5654 // incomplete char.
5655 for (; i > 0; i--) {
5656 var c = buffer[buffer.length - i];
5657
5658 // See http://en.wikipedia.org/wiki/UTF-8#Description
5659
5660 // 110XXXXX
5661 if (i == 1 && c >> 5 == 0x06) {
5662 this.charLength = 2;
5663 break;
5664 }
5665
5666 // 1110XXXX
5667 if (i <= 2 && c >> 4 == 0x0E) {
5668 this.charLength = 3;
5669 break;
5670 }
5671
5672 // 11110XXX
5673 if (i <= 3 && c >> 3 == 0x1E) {
5674 this.charLength = 4;
5675 break;
5676 }
5677 }
5678 this.charReceived = i;
5679};
5680
5681StringDecoder.prototype.end = function(buffer) {
5682 var res = '';
5683 if (buffer && buffer.length)
5684 res = this.write(buffer);
5685
5686 if (this.charReceived) {
5687 var cr = this.charReceived;
5688 var buf = this.charBuffer;
5689 var enc = this.encoding;
5690 res += buf.slice(0, cr).toString(enc);
5691 }
5692
5693 return res;
5694};
5695
5696function passThroughWrite(buffer) {
5697 return buffer.toString(this.encoding);
5698}
5699
5700function utf16DetectIncompleteChar(buffer) {
5701 this.charReceived = buffer.length % 2;
5702 this.charLength = this.charReceived ? 2 : 0;
5703}
5704
5705function base64DetectIncompleteChar(buffer) {
5706 this.charReceived = buffer.length % 3;
5707 this.charLength = this.charReceived ? 3 : 0;
5708}
5709
5710},{"buffer":5}],30:[function(require,module,exports){
5711(function (global){
5712
5713/**
5714 * Module exports.
5715 */
5716
5717module.exports = deprecate;
5718
5719/**
5720 * Mark that a method should not be used.
5721 * Returns a modified function which warns once by default.
5722 *
5723 * If `localStorage.noDeprecation = true` is set, then it is a no-op.
5724 *
5725 * If `localStorage.throwDeprecation = true` is set, then deprecated functions
5726 * will throw an Error when invoked.
5727 *
5728 * If `localStorage.traceDeprecation = true` is set, then deprecated functions
5729 * will invoke `console.trace()` instead of `console.error()`.
5730 *
5731 * @param {Function} fn - the function to deprecate
5732 * @param {String} msg - the string to print to the console when `fn` is invoked
5733 * @returns {Function} a new "deprecated" version of `fn`
5734 * @api public
5735 */
5736
5737function deprecate (fn, msg) {
5738 if (config('noDeprecation')) {
5739 return fn;
5740 }
5741
5742 var warned = false;
5743 function deprecated() {
5744 if (!warned) {
5745 if (config('throwDeprecation')) {
5746 throw new Error(msg);
5747 } else if (config('traceDeprecation')) {
5748 console.trace(msg);
5749 } else {
5750 console.warn(msg);
5751 }
5752 warned = true;
5753 }
5754 return fn.apply(this, arguments);
5755 }
5756
5757 return deprecated;
5758}
5759
5760/**
5761 * Checks `localStorage` for boolean values for the given `name`.
5762 *
5763 * @param {String} name
5764 * @returns {Boolean}
5765 * @api private
5766 */
5767
5768function config (name) {
5769 // accessing global.localStorage can trigger a DOMException in sandboxed iframes
5770 try {
5771 if (!global.localStorage) return false;
5772 } catch (_) {
5773 return false;
5774 }
5775 var val = global.localStorage[name];
5776 if (null == val) return false;
5777 return String(val).toLowerCase() === 'true';
5778}
5779
5780}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
5781},{}],31:[function(require,module,exports){
5782arguments[4][9][0].apply(exports,arguments)
5783},{"dup":9}],32:[function(require,module,exports){
5784module.exports = function isBuffer(arg) {
5785 return arg && typeof arg === 'object'
5786 && typeof arg.copy === 'function'
5787 && typeof arg.fill === 'function'
5788 && typeof arg.readUInt8 === 'function';
5789}
5790},{}],33:[function(require,module,exports){
5791(function (process,global){
5792// Copyright Joyent, Inc. and other Node contributors.
5793//
5794// Permission is hereby granted, free of charge, to any person obtaining a
5795// copy of this software and associated documentation files (the
5796// "Software"), to deal in the Software without restriction, including
5797// without limitation the rights to use, copy, modify, merge, publish,
5798// distribute, sublicense, and/or sell copies of the Software, and to permit
5799// persons to whom the Software is furnished to do so, subject to the
5800// following conditions:
5801//
5802// The above copyright notice and this permission notice shall be included
5803// in all copies or substantial portions of the Software.
5804//
5805// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
5806// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
5807// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
5808// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
5809// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
5810// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
5811// USE OR OTHER DEALINGS IN THE SOFTWARE.
5812
5813var formatRegExp = /%[sdj%]/g;
5814exports.format = function(f) {
5815 if (!isString(f)) {
5816 var objects = [];
5817 for (var i = 0; i < arguments.length; i++) {
5818 objects.push(inspect(arguments[i]));
5819 }
5820 return objects.join(' ');
5821 }
5822
5823 var i = 1;
5824 var args = arguments;
5825 var len = args.length;
5826 var str = String(f).replace(formatRegExp, function(x) {
5827 if (x === '%%') return '%';
5828 if (i >= len) return x;
5829 switch (x) {
5830 case '%s': return String(args[i++]);
5831 case '%d': return Number(args[i++]);
5832 case '%j':
5833 try {
5834 return JSON.stringify(args[i++]);
5835 } catch (_) {
5836 return '[Circular]';
5837 }
5838 default:
5839 return x;
5840 }
5841 });
5842 for (var x = args[i]; i < len; x = args[++i]) {
5843 if (isNull(x) || !isObject(x)) {
5844 str += ' ' + x;
5845 } else {
5846 str += ' ' + inspect(x);
5847 }
5848 }
5849 return str;
5850};
5851
5852
5853// Mark that a method should not be used.
5854// Returns a modified function which warns once by default.
5855// If --no-deprecation is set, then it is a no-op.
5856exports.deprecate = function(fn, msg) {
5857 // Allow for deprecating things in the process of starting up.
5858 if (isUndefined(global.process)) {
5859 return function() {
5860 return exports.deprecate(fn, msg).apply(this, arguments);
5861 };
5862 }
5863
5864 if (process.noDeprecation === true) {
5865 return fn;
5866 }
5867
5868 var warned = false;
5869 function deprecated() {
5870 if (!warned) {
5871 if (process.throwDeprecation) {
5872 throw new Error(msg);
5873 } else if (process.traceDeprecation) {
5874 console.trace(msg);
5875 } else {
5876 console.error(msg);
5877 }
5878 warned = true;
5879 }
5880 return fn.apply(this, arguments);
5881 }
5882
5883 return deprecated;
5884};
5885
5886
5887var debugs = {};
5888var debugEnviron;
5889exports.debuglog = function(set) {
5890 if (isUndefined(debugEnviron))
5891 debugEnviron = process.env.NODE_DEBUG || '';
5892 set = set.toUpperCase();
5893 if (!debugs[set]) {
5894 if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
5895 var pid = process.pid;
5896 debugs[set] = function() {
5897 var msg = exports.format.apply(exports, arguments);
5898 console.error('%s %d: %s', set, pid, msg);
5899 };
5900 } else {
5901 debugs[set] = function() {};
5902 }
5903 }
5904 return debugs[set];
5905};
5906
5907
5908/**
5909 * Echos the value of a value. Trys to print the value out
5910 * in the best way possible given the different types.
5911 *
5912 * @param {Object} obj The object to print out.
5913 * @param {Object} opts Optional options object that alters the output.
5914 */
5915/* legacy: obj, showHidden, depth, colors*/
5916function inspect(obj, opts) {
5917 // default options
5918 var ctx = {
5919 seen: [],
5920 stylize: stylizeNoColor
5921 };
5922 // legacy...
5923 if (arguments.length >= 3) ctx.depth = arguments[2];
5924 if (arguments.length >= 4) ctx.colors = arguments[3];
5925 if (isBoolean(opts)) {
5926 // legacy...
5927 ctx.showHidden = opts;
5928 } else if (opts) {
5929 // got an "options" object
5930 exports._extend(ctx, opts);
5931 }
5932 // set default options
5933 if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
5934 if (isUndefined(ctx.depth)) ctx.depth = 2;
5935 if (isUndefined(ctx.colors)) ctx.colors = false;
5936 if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
5937 if (ctx.colors) ctx.stylize = stylizeWithColor;
5938 return formatValue(ctx, obj, ctx.depth);
5939}
5940exports.inspect = inspect;
5941
5942
5943// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
5944inspect.colors = {
5945 'bold' : [1, 22],
5946 'italic' : [3, 23],
5947 'underline' : [4, 24],
5948 'inverse' : [7, 27],
5949 'white' : [37, 39],
5950 'grey' : [90, 39],
5951 'black' : [30, 39],
5952 'blue' : [34, 39],
5953 'cyan' : [36, 39],
5954 'green' : [32, 39],
5955 'magenta' : [35, 39],
5956 'red' : [31, 39],
5957 'yellow' : [33, 39]
5958};
5959
5960// Don't use 'blue' not visible on cmd.exe
5961inspect.styles = {
5962 'special': 'cyan',
5963 'number': 'yellow',
5964 'boolean': 'yellow',
5965 'undefined': 'grey',
5966 'null': 'bold',
5967 'string': 'green',
5968 'date': 'magenta',
5969 // "name": intentionally not styling
5970 'regexp': 'red'
5971};
5972
5973
5974function stylizeWithColor(str, styleType) {
5975 var style = inspect.styles[styleType];
5976
5977 if (style) {
5978 return '\u001b[' + inspect.colors[style][0] + 'm' + str +
5979 '\u001b[' + inspect.colors[style][1] + 'm';
5980 } else {
5981 return str;
5982 }
5983}
5984
5985
5986function stylizeNoColor(str, styleType) {
5987 return str;
5988}
5989
5990
5991function arrayToHash(array) {
5992 var hash = {};
5993
5994 array.forEach(function(val, idx) {
5995 hash[val] = true;
5996 });
5997
5998 return hash;
5999}
6000
6001
6002function formatValue(ctx, value, recurseTimes) {
6003 // Provide a hook for user-specified inspect functions.
6004 // Check that value is an object with an inspect function on it
6005 if (ctx.customInspect &&
6006 value &&
6007 isFunction(value.inspect) &&
6008 // Filter out the util module, it's inspect function is special
6009 value.inspect !== exports.inspect &&
6010 // Also filter out any prototype objects using the circular check.
6011 !(value.constructor && value.constructor.prototype === value)) {
6012 var ret = value.inspect(recurseTimes, ctx);
6013 if (!isString(ret)) {
6014 ret = formatValue(ctx, ret, recurseTimes);
6015 }
6016 return ret;
6017 }
6018
6019 // Primitive types cannot have properties
6020 var primitive = formatPrimitive(ctx, value);
6021 if (primitive) {
6022 return primitive;
6023 }
6024
6025 // Look up the keys of the object.
6026 var keys = Object.keys(value);
6027 var visibleKeys = arrayToHash(keys);
6028
6029 if (ctx.showHidden) {
6030 keys = Object.getOwnPropertyNames(value);
6031 }
6032
6033 // IE doesn't make error fields non-enumerable
6034 // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
6035 if (isError(value)
6036 && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
6037 return formatError(value);
6038 }
6039
6040 // Some type of object without properties can be shortcutted.
6041 if (keys.length === 0) {
6042 if (isFunction(value)) {
6043 var name = value.name ? ': ' + value.name : '';
6044 return ctx.stylize('[Function' + name + ']', 'special');
6045 }
6046 if (isRegExp(value)) {
6047 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
6048 }
6049 if (isDate(value)) {
6050 return ctx.stylize(Date.prototype.toString.call(value), 'date');
6051 }
6052 if (isError(value)) {
6053 return formatError(value);
6054 }
6055 }
6056
6057 var base = '', array = false, braces = ['{', '}'];
6058
6059 // Make Array say that they are Array
6060 if (isArray(value)) {
6061 array = true;
6062 braces = ['[', ']'];
6063 }
6064
6065 // Make functions say that they are functions
6066 if (isFunction(value)) {
6067 var n = value.name ? ': ' + value.name : '';
6068 base = ' [Function' + n + ']';
6069 }
6070
6071 // Make RegExps say that they are RegExps
6072 if (isRegExp(value)) {
6073 base = ' ' + RegExp.prototype.toString.call(value);
6074 }
6075
6076 // Make dates with properties first say the date
6077 if (isDate(value)) {
6078 base = ' ' + Date.prototype.toUTCString.call(value);
6079 }
6080
6081 // Make error with message first say the error
6082 if (isError(value)) {
6083 base = ' ' + formatError(value);
6084 }
6085
6086 if (keys.length === 0 && (!array || value.length == 0)) {
6087 return braces[0] + base + braces[1];
6088 }
6089
6090 if (recurseTimes < 0) {
6091 if (isRegExp(value)) {
6092 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
6093 } else {
6094 return ctx.stylize('[Object]', 'special');
6095 }
6096 }
6097
6098 ctx.seen.push(value);
6099
6100 var output;
6101 if (array) {
6102 output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
6103 } else {
6104 output = keys.map(function(key) {
6105 return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
6106 });
6107 }
6108
6109 ctx.seen.pop();
6110
6111 return reduceToSingleString(output, base, braces);
6112}
6113
6114
6115function formatPrimitive(ctx, value) {
6116 if (isUndefined(value))
6117 return ctx.stylize('undefined', 'undefined');
6118 if (isString(value)) {
6119 var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
6120 .replace(/'/g, "\\'")
6121 .replace(/\\"/g, '"') + '\'';
6122 return ctx.stylize(simple, 'string');
6123 }
6124 if (isNumber(value))
6125 return ctx.stylize('' + value, 'number');
6126 if (isBoolean(value))
6127 return ctx.stylize('' + value, 'boolean');
6128 // For some reason typeof null is "object", so special case here.
6129 if (isNull(value))
6130 return ctx.stylize('null', 'null');
6131}
6132
6133
6134function formatError(value) {
6135 return '[' + Error.prototype.toString.call(value) + ']';
6136}
6137
6138
6139function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
6140 var output = [];
6141 for (var i = 0, l = value.length; i < l; ++i) {
6142 if (hasOwnProperty(value, String(i))) {
6143 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
6144 String(i), true));
6145 } else {
6146 output.push('');
6147 }
6148 }
6149 keys.forEach(function(key) {
6150 if (!key.match(/^\d+$/)) {
6151 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
6152 key, true));
6153 }
6154 });
6155 return output;
6156}
6157
6158
6159function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
6160 var name, str, desc;
6161 desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
6162 if (desc.get) {
6163 if (desc.set) {
6164 str = ctx.stylize('[Getter/Setter]', 'special');
6165 } else {
6166 str = ctx.stylize('[Getter]', 'special');
6167 }
6168 } else {
6169 if (desc.set) {
6170 str = ctx.stylize('[Setter]', 'special');
6171 }
6172 }
6173 if (!hasOwnProperty(visibleKeys, key)) {
6174 name = '[' + key + ']';
6175 }
6176 if (!str) {
6177 if (ctx.seen.indexOf(desc.value) < 0) {
6178 if (isNull(recurseTimes)) {
6179 str = formatValue(ctx, desc.value, null);
6180 } else {
6181 str = formatValue(ctx, desc.value, recurseTimes - 1);
6182 }
6183 if (str.indexOf('\n') > -1) {
6184 if (array) {
6185 str = str.split('\n').map(function(line) {
6186 return ' ' + line;
6187 }).join('\n').substr(2);
6188 } else {
6189 str = '\n' + str.split('\n').map(function(line) {
6190 return ' ' + line;
6191 }).join('\n');
6192 }
6193 }
6194 } else {
6195 str = ctx.stylize('[Circular]', 'special');
6196 }
6197 }
6198 if (isUndefined(name)) {
6199 if (array && key.match(/^\d+$/)) {
6200 return str;
6201 }
6202 name = JSON.stringify('' + key);
6203 if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
6204 name = name.substr(1, name.length - 2);
6205 name = ctx.stylize(name, 'name');
6206 } else {
6207 name = name.replace(/'/g, "\\'")
6208 .replace(/\\"/g, '"')
6209 .replace(/(^"|"$)/g, "'");
6210 name = ctx.stylize(name, 'string');
6211 }
6212 }
6213
6214 return name + ': ' + str;
6215}
6216
6217
6218function reduceToSingleString(output, base, braces) {
6219 var numLinesEst = 0;
6220 var length = output.reduce(function(prev, cur) {
6221 numLinesEst++;
6222 if (cur.indexOf('\n') >= 0) numLinesEst++;
6223 return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
6224 }, 0);
6225
6226 if (length > 60) {
6227 return braces[0] +
6228 (base === '' ? '' : base + '\n ') +
6229 ' ' +
6230 output.join(',\n ') +
6231 ' ' +
6232 braces[1];
6233 }
6234
6235 return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
6236}
6237
6238
6239// NOTE: These type checking functions intentionally don't use `instanceof`
6240// because it is fragile and can be easily faked with `Object.create()`.
6241function isArray(ar) {
6242 return Array.isArray(ar);
6243}
6244exports.isArray = isArray;
6245
6246function isBoolean(arg) {
6247 return typeof arg === 'boolean';
6248}
6249exports.isBoolean = isBoolean;
6250
6251function isNull(arg) {
6252 return arg === null;
6253}
6254exports.isNull = isNull;
6255
6256function isNullOrUndefined(arg) {
6257 return arg == null;
6258}
6259exports.isNullOrUndefined = isNullOrUndefined;
6260
6261function isNumber(arg) {
6262 return typeof arg === 'number';
6263}
6264exports.isNumber = isNumber;
6265
6266function isString(arg) {
6267 return typeof arg === 'string';
6268}
6269exports.isString = isString;
6270
6271function isSymbol(arg) {
6272 return typeof arg === 'symbol';
6273}
6274exports.isSymbol = isSymbol;
6275
6276function isUndefined(arg) {
6277 return arg === void 0;
6278}
6279exports.isUndefined = isUndefined;
6280
6281function isRegExp(re) {
6282 return isObject(re) && objectToString(re) === '[object RegExp]';
6283}
6284exports.isRegExp = isRegExp;
6285
6286function isObject(arg) {
6287 return typeof arg === 'object' && arg !== null;
6288}
6289exports.isObject = isObject;
6290
6291function isDate(d) {
6292 return isObject(d) && objectToString(d) === '[object Date]';
6293}
6294exports.isDate = isDate;
6295
6296function isError(e) {
6297 return isObject(e) &&
6298 (objectToString(e) === '[object Error]' || e instanceof Error);
6299}
6300exports.isError = isError;
6301
6302function isFunction(arg) {
6303 return typeof arg === 'function';
6304}
6305exports.isFunction = isFunction;
6306
6307function isPrimitive(arg) {
6308 return arg === null ||
6309 typeof arg === 'boolean' ||
6310 typeof arg === 'number' ||
6311 typeof arg === 'string' ||
6312 typeof arg === 'symbol' || // ES6 symbol
6313 typeof arg === 'undefined';
6314}
6315exports.isPrimitive = isPrimitive;
6316
6317exports.isBuffer = require('./support/isBuffer');
6318
6319function objectToString(o) {
6320 return Object.prototype.toString.call(o);
6321}
6322
6323
6324function pad(n) {
6325 return n < 10 ? '0' + n.toString(10) : n.toString(10);
6326}
6327
6328
6329var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
6330 'Oct', 'Nov', 'Dec'];
6331
6332// 26 Feb 16:19:34
6333function timestamp() {
6334 var d = new Date();
6335 var time = [pad(d.getHours()),
6336 pad(d.getMinutes()),
6337 pad(d.getSeconds())].join(':');
6338 return [d.getDate(), months[d.getMonth()], time].join(' ');
6339}
6340
6341
6342// log is just a thin wrapper to console.log that prepends a timestamp
6343exports.log = function() {
6344 console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
6345};
6346
6347
6348/**
6349 * Inherit the prototype methods from one constructor into another.
6350 *
6351 * The Function.prototype.inherits from lang.js rewritten as a standalone
6352 * function (not on Function.prototype). NOTE: If this file is to be loaded
6353 * during bootstrapping this function needs to be rewritten using some native
6354 * functions as prototype setup using normal JavaScript does not work as
6355 * expected during bootstrapping (see mirror.js in r114903).
6356 *
6357 * @param {function} ctor Constructor function which needs to inherit the
6358 * prototype.
6359 * @param {function} superCtor Constructor function to inherit prototype from.
6360 */
6361exports.inherits = require('inherits');
6362
6363exports._extend = function(origin, add) {
6364 // Don't do anything if add isn't an object
6365 if (!add || !isObject(add)) return origin;
6366
6367 var keys = Object.keys(add);
6368 var i = keys.length;
6369 while (i--) {
6370 origin[keys[i]] = add[keys[i]];
6371 }
6372 return origin;
6373};
6374
6375function hasOwnProperty(obj, prop) {
6376 return Object.prototype.hasOwnProperty.call(obj, prop);
6377}
6378
6379}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
6380},{"./support/isBuffer":32,"_process":13,"inherits":31}],34:[function(require,module,exports){
6381
6382module.exports = {
6383 Aes: require("./src/aes"),
6384 PrivateKey: require("./src/key_private"),
6385 PublicKey: require("./src/key_public"),
6386 Signature: require("./src/signature"),
6387 config: require('./src/config')
6388}
6389
6390},{"./src/aes":84,"./src/config":85,"./src/key_private":90,"./src/key_public":91,"./src/signature":93}],35:[function(require,module,exports){
6391// base-x encoding
6392// Forked from https://github.com/cryptocoinjs/bs58
6393// Originally written by Mike Hearn for BitcoinJ
6394// Copyright (c) 2011 Google Inc
6395// Ported to JavaScript by Stefan Thomas
6396// Merged Buffer refactorings from base58-native by Stephen Pair
6397// Copyright (c) 2013 BitPay Inc
6398
6399var Buffer = require('safe-buffer').Buffer
6400
6401module.exports = function base (ALPHABET) {
6402 var ALPHABET_MAP = {}
6403 var BASE = ALPHABET.length
6404 var LEADER = ALPHABET.charAt(0)
6405
6406 // pre-compute lookup table
6407 for (var z = 0; z < ALPHABET.length; z++) {
6408 var x = ALPHABET.charAt(z)
6409
6410 if (ALPHABET_MAP[x] !== undefined) throw new TypeError(x + ' is ambiguous')
6411 ALPHABET_MAP[x] = z
6412 }
6413
6414 function encode (source) {
6415 if (source.length === 0) return ''
6416
6417 var digits = [0]
6418 for (var i = 0; i < source.length; ++i) {
6419 for (var j = 0, carry = source[i]; j < digits.length; ++j) {
6420 carry += digits[j] << 8
6421 digits[j] = carry % BASE
6422 carry = (carry / BASE) | 0
6423 }
6424
6425 while (carry > 0) {
6426 digits.push(carry % BASE)
6427 carry = (carry / BASE) | 0
6428 }
6429 }
6430
6431 var string = ''
6432
6433 // deal with leading zeros
6434 for (var k = 0; source[k] === 0 && k < source.length - 1; ++k) string += ALPHABET[0]
6435 // convert digits to a string
6436 for (var q = digits.length - 1; q >= 0; --q) string += ALPHABET[digits[q]]
6437
6438 return string
6439 }
6440
6441 function decodeUnsafe (string) {
6442 if (string.length === 0) return Buffer.allocUnsafe(0)
6443
6444 var bytes = [0]
6445 for (var i = 0; i < string.length; i++) {
6446 var value = ALPHABET_MAP[string[i]]
6447 if (value === undefined) return
6448
6449 for (var j = 0, carry = value; j < bytes.length; ++j) {
6450 carry += bytes[j] * BASE
6451 bytes[j] = carry & 0xff
6452 carry >>= 8
6453 }
6454
6455 while (carry > 0) {
6456 bytes.push(carry & 0xff)
6457 carry >>= 8
6458 }
6459 }
6460
6461 // deal with leading zeros
6462 for (var k = 0; string[k] === LEADER && k < string.length - 1; ++k) {
6463 bytes.push(0)
6464 }
6465
6466 return Buffer.from(bytes.reverse())
6467 }
6468
6469 function decode (string) {
6470 var buffer = decodeUnsafe(string)
6471 if (buffer) return buffer
6472
6473 throw new Error('Non-base' + BASE + ' character')
6474 }
6475
6476 return {
6477 encode: encode,
6478 decodeUnsafe: decodeUnsafe,
6479 decode: decode
6480 }
6481}
6482
6483},{"safe-buffer":74}],36:[function(require,module,exports){
6484// (public) Constructor
6485function BigInteger(a, b, c) {
6486 if (!(this instanceof BigInteger))
6487 return new BigInteger(a, b, c)
6488
6489 if (a != null) {
6490 if ("number" == typeof a) this.fromNumber(a, b, c)
6491 else if (b == null && "string" != typeof a) this.fromString(a, 256)
6492 else this.fromString(a, b)
6493 }
6494}
6495
6496var proto = BigInteger.prototype
6497
6498// duck-typed isBigInteger
6499proto.__bigi = require('../package.json').version
6500BigInteger.isBigInteger = function (obj, check_ver) {
6501 return obj && obj.__bigi && (!check_ver || obj.__bigi === proto.__bigi)
6502}
6503
6504// Bits per digit
6505var dbits
6506
6507// am: Compute w_j += (x*this_i), propagate carries,
6508// c is initial carry, returns final carry.
6509// c < 3*dvalue, x < 2*dvalue, this_i < dvalue
6510// We need to select the fastest one that works in this environment.
6511
6512// am1: use a single mult and divide to get the high bits,
6513// max digit bits should be 26 because
6514// max internal value = 2*dvalue^2-2*dvalue (< 2^53)
6515function am1(i, x, w, j, c, n) {
6516 while (--n >= 0) {
6517 var v = x * this[i++] + w[j] + c
6518 c = Math.floor(v / 0x4000000)
6519 w[j++] = v & 0x3ffffff
6520 }
6521 return c
6522}
6523// am2 avoids a big mult-and-extract completely.
6524// Max digit bits should be <= 30 because we do bitwise ops
6525// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)
6526function am2(i, x, w, j, c, n) {
6527 var xl = x & 0x7fff,
6528 xh = x >> 15
6529 while (--n >= 0) {
6530 var l = this[i] & 0x7fff
6531 var h = this[i++] >> 15
6532 var m = xh * l + h * xl
6533 l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff)
6534 c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30)
6535 w[j++] = l & 0x3fffffff
6536 }
6537 return c
6538}
6539// Alternately, set max digit bits to 28 since some
6540// browsers slow down when dealing with 32-bit numbers.
6541function am3(i, x, w, j, c, n) {
6542 var xl = x & 0x3fff,
6543 xh = x >> 14
6544 while (--n >= 0) {
6545 var l = this[i] & 0x3fff
6546 var h = this[i++] >> 14
6547 var m = xh * l + h * xl
6548 l = xl * l + ((m & 0x3fff) << 14) + w[j] + c
6549 c = (l >> 28) + (m >> 14) + xh * h
6550 w[j++] = l & 0xfffffff
6551 }
6552 return c
6553}
6554
6555// wtf?
6556BigInteger.prototype.am = am1
6557dbits = 26
6558
6559BigInteger.prototype.DB = dbits
6560BigInteger.prototype.DM = ((1 << dbits) - 1)
6561var DV = BigInteger.prototype.DV = (1 << dbits)
6562
6563var BI_FP = 52
6564BigInteger.prototype.FV = Math.pow(2, BI_FP)
6565BigInteger.prototype.F1 = BI_FP - dbits
6566BigInteger.prototype.F2 = 2 * dbits - BI_FP
6567
6568// Digit conversions
6569var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"
6570var BI_RC = new Array()
6571var rr, vv
6572rr = "0".charCodeAt(0)
6573for (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv
6574rr = "a".charCodeAt(0)
6575for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv
6576rr = "A".charCodeAt(0)
6577for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv
6578
6579function int2char(n) {
6580 return BI_RM.charAt(n)
6581}
6582
6583function intAt(s, i) {
6584 var c = BI_RC[s.charCodeAt(i)]
6585 return (c == null) ? -1 : c
6586}
6587
6588// (protected) copy this to r
6589function bnpCopyTo(r) {
6590 for (var i = this.t - 1; i >= 0; --i) r[i] = this[i]
6591 r.t = this.t
6592 r.s = this.s
6593}
6594
6595// (protected) set from integer value x, -DV <= x < DV
6596function bnpFromInt(x) {
6597 this.t = 1
6598 this.s = (x < 0) ? -1 : 0
6599 if (x > 0) this[0] = x
6600 else if (x < -1) this[0] = x + DV
6601 else this.t = 0
6602}
6603
6604// return bigint initialized to value
6605function nbv(i) {
6606 var r = new BigInteger()
6607 r.fromInt(i)
6608 return r
6609}
6610
6611// (protected) set from string and radix
6612function bnpFromString(s, b) {
6613 var self = this
6614
6615 var k
6616 if (b == 16) k = 4
6617 else if (b == 8) k = 3
6618 else if (b == 256) k = 8; // byte array
6619 else if (b == 2) k = 1
6620 else if (b == 32) k = 5
6621 else if (b == 4) k = 2
6622 else {
6623 self.fromRadix(s, b)
6624 return
6625 }
6626 self.t = 0
6627 self.s = 0
6628 var i = s.length,
6629 mi = false,
6630 sh = 0
6631 while (--i >= 0) {
6632 var x = (k == 8) ? s[i] & 0xff : intAt(s, i)
6633 if (x < 0) {
6634 if (s.charAt(i) == "-") mi = true
6635 continue
6636 }
6637 mi = false
6638 if (sh == 0)
6639 self[self.t++] = x
6640 else if (sh + k > self.DB) {
6641 self[self.t - 1] |= (x & ((1 << (self.DB - sh)) - 1)) << sh
6642 self[self.t++] = (x >> (self.DB - sh))
6643 } else
6644 self[self.t - 1] |= x << sh
6645 sh += k
6646 if (sh >= self.DB) sh -= self.DB
6647 }
6648 if (k == 8 && (s[0] & 0x80) != 0) {
6649 self.s = -1
6650 if (sh > 0) self[self.t - 1] |= ((1 << (self.DB - sh)) - 1) << sh
6651 }
6652 self.clamp()
6653 if (mi) BigInteger.ZERO.subTo(self, self)
6654}
6655
6656// (protected) clamp off excess high words
6657function bnpClamp() {
6658 var c = this.s & this.DM
6659 while (this.t > 0 && this[this.t - 1] == c)--this.t
6660}
6661
6662// (public) return string representation in given radix
6663function bnToString(b) {
6664 var self = this
6665 if (self.s < 0) return "-" + self.negate()
6666 .toString(b)
6667 var k
6668 if (b == 16) k = 4
6669 else if (b == 8) k = 3
6670 else if (b == 2) k = 1
6671 else if (b == 32) k = 5
6672 else if (b == 4) k = 2
6673 else return self.toRadix(b)
6674 var km = (1 << k) - 1,
6675 d, m = false,
6676 r = "",
6677 i = self.t
6678 var p = self.DB - (i * self.DB) % k
6679 if (i-- > 0) {
6680 if (p < self.DB && (d = self[i] >> p) > 0) {
6681 m = true
6682 r = int2char(d)
6683 }
6684 while (i >= 0) {
6685 if (p < k) {
6686 d = (self[i] & ((1 << p) - 1)) << (k - p)
6687 d |= self[--i] >> (p += self.DB - k)
6688 } else {
6689 d = (self[i] >> (p -= k)) & km
6690 if (p <= 0) {
6691 p += self.DB
6692 --i
6693 }
6694 }
6695 if (d > 0) m = true
6696 if (m) r += int2char(d)
6697 }
6698 }
6699 return m ? r : "0"
6700}
6701
6702// (public) -this
6703function bnNegate() {
6704 var r = new BigInteger()
6705 BigInteger.ZERO.subTo(this, r)
6706 return r
6707}
6708
6709// (public) |this|
6710function bnAbs() {
6711 return (this.s < 0) ? this.negate() : this
6712}
6713
6714// (public) return + if this > a, - if this < a, 0 if equal
6715function bnCompareTo(a) {
6716 var r = this.s - a.s
6717 if (r != 0) return r
6718 var i = this.t
6719 r = i - a.t
6720 if (r != 0) return (this.s < 0) ? -r : r
6721 while (--i >= 0)
6722 if ((r = this[i] - a[i]) != 0) return r
6723 return 0
6724}
6725
6726// returns bit length of the integer x
6727function nbits(x) {
6728 var r = 1,
6729 t
6730 if ((t = x >>> 16) != 0) {
6731 x = t
6732 r += 16
6733 }
6734 if ((t = x >> 8) != 0) {
6735 x = t
6736 r += 8
6737 }
6738 if ((t = x >> 4) != 0) {
6739 x = t
6740 r += 4
6741 }
6742 if ((t = x >> 2) != 0) {
6743 x = t
6744 r += 2
6745 }
6746 if ((t = x >> 1) != 0) {
6747 x = t
6748 r += 1
6749 }
6750 return r
6751}
6752
6753// (public) return the number of bits in "this"
6754function bnBitLength() {
6755 if (this.t <= 0) return 0
6756 return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM))
6757}
6758
6759// (public) return the number of bytes in "this"
6760function bnByteLength() {
6761 return this.bitLength() >> 3
6762}
6763
6764// (protected) r = this << n*DB
6765function bnpDLShiftTo(n, r) {
6766 var i
6767 for (i = this.t - 1; i >= 0; --i) r[i + n] = this[i]
6768 for (i = n - 1; i >= 0; --i) r[i] = 0
6769 r.t = this.t + n
6770 r.s = this.s
6771}
6772
6773// (protected) r = this >> n*DB
6774function bnpDRShiftTo(n, r) {
6775 for (var i = n; i < this.t; ++i) r[i - n] = this[i]
6776 r.t = Math.max(this.t - n, 0)
6777 r.s = this.s
6778}
6779
6780// (protected) r = this << n
6781function bnpLShiftTo(n, r) {
6782 var self = this
6783 var bs = n % self.DB
6784 var cbs = self.DB - bs
6785 var bm = (1 << cbs) - 1
6786 var ds = Math.floor(n / self.DB),
6787 c = (self.s << bs) & self.DM,
6788 i
6789 for (i = self.t - 1; i >= 0; --i) {
6790 r[i + ds + 1] = (self[i] >> cbs) | c
6791 c = (self[i] & bm) << bs
6792 }
6793 for (i = ds - 1; i >= 0; --i) r[i] = 0
6794 r[ds] = c
6795 r.t = self.t + ds + 1
6796 r.s = self.s
6797 r.clamp()
6798}
6799
6800// (protected) r = this >> n
6801function bnpRShiftTo(n, r) {
6802 var self = this
6803 r.s = self.s
6804 var ds = Math.floor(n / self.DB)
6805 if (ds >= self.t) {
6806 r.t = 0
6807 return
6808 }
6809 var bs = n % self.DB
6810 var cbs = self.DB - bs
6811 var bm = (1 << bs) - 1
6812 r[0] = self[ds] >> bs
6813 for (var i = ds + 1; i < self.t; ++i) {
6814 r[i - ds - 1] |= (self[i] & bm) << cbs
6815 r[i - ds] = self[i] >> bs
6816 }
6817 if (bs > 0) r[self.t - ds - 1] |= (self.s & bm) << cbs
6818 r.t = self.t - ds
6819 r.clamp()
6820}
6821
6822// (protected) r = this - a
6823function bnpSubTo(a, r) {
6824 var self = this
6825 var i = 0,
6826 c = 0,
6827 m = Math.min(a.t, self.t)
6828 while (i < m) {
6829 c += self[i] - a[i]
6830 r[i++] = c & self.DM
6831 c >>= self.DB
6832 }
6833 if (a.t < self.t) {
6834 c -= a.s
6835 while (i < self.t) {
6836 c += self[i]
6837 r[i++] = c & self.DM
6838 c >>= self.DB
6839 }
6840 c += self.s
6841 } else {
6842 c += self.s
6843 while (i < a.t) {
6844 c -= a[i]
6845 r[i++] = c & self.DM
6846 c >>= self.DB
6847 }
6848 c -= a.s
6849 }
6850 r.s = (c < 0) ? -1 : 0
6851 if (c < -1) r[i++] = self.DV + c
6852 else if (c > 0) r[i++] = c
6853 r.t = i
6854 r.clamp()
6855}
6856
6857// (protected) r = this * a, r != this,a (HAC 14.12)
6858// "this" should be the larger one if appropriate.
6859function bnpMultiplyTo(a, r) {
6860 var x = this.abs(),
6861 y = a.abs()
6862 var i = x.t
6863 r.t = i + y.t
6864 while (--i >= 0) r[i] = 0
6865 for (i = 0; i < y.t; ++i) r[i + x.t] = x.am(0, y[i], r, i, 0, x.t)
6866 r.s = 0
6867 r.clamp()
6868 if (this.s != a.s) BigInteger.ZERO.subTo(r, r)
6869}
6870
6871// (protected) r = this^2, r != this (HAC 14.16)
6872function bnpSquareTo(r) {
6873 var x = this.abs()
6874 var i = r.t = 2 * x.t
6875 while (--i >= 0) r[i] = 0
6876 for (i = 0; i < x.t - 1; ++i) {
6877 var c = x.am(i, x[i], r, 2 * i, 0, 1)
6878 if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) {
6879 r[i + x.t] -= x.DV
6880 r[i + x.t + 1] = 1
6881 }
6882 }
6883 if (r.t > 0) r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1)
6884 r.s = 0
6885 r.clamp()
6886}
6887
6888// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)
6889// r != q, this != m. q or r may be null.
6890function bnpDivRemTo(m, q, r) {
6891 var self = this
6892 var pm = m.abs()
6893 if (pm.t <= 0) return
6894 var pt = self.abs()
6895 if (pt.t < pm.t) {
6896 if (q != null) q.fromInt(0)
6897 if (r != null) self.copyTo(r)
6898 return
6899 }
6900 if (r == null) r = new BigInteger()
6901 var y = new BigInteger(),
6902 ts = self.s,
6903 ms = m.s
6904 var nsh = self.DB - nbits(pm[pm.t - 1]); // normalize modulus
6905 if (nsh > 0) {
6906 pm.lShiftTo(nsh, y)
6907 pt.lShiftTo(nsh, r)
6908 } else {
6909 pm.copyTo(y)
6910 pt.copyTo(r)
6911 }
6912 var ys = y.t
6913 var y0 = y[ys - 1]
6914 if (y0 == 0) return
6915 var yt = y0 * (1 << self.F1) + ((ys > 1) ? y[ys - 2] >> self.F2 : 0)
6916 var d1 = self.FV / yt,
6917 d2 = (1 << self.F1) / yt,
6918 e = 1 << self.F2
6919 var i = r.t,
6920 j = i - ys,
6921 t = (q == null) ? new BigInteger() : q
6922 y.dlShiftTo(j, t)
6923 if (r.compareTo(t) >= 0) {
6924 r[r.t++] = 1
6925 r.subTo(t, r)
6926 }
6927 BigInteger.ONE.dlShiftTo(ys, t)
6928 t.subTo(y, y); // "negative" y so we can replace sub with am later
6929 while (y.t < ys) y[y.t++] = 0
6930 while (--j >= 0) {
6931 // Estimate quotient digit
6932 var qd = (r[--i] == y0) ? self.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2)
6933 if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { // Try it out
6934 y.dlShiftTo(j, t)
6935 r.subTo(t, r)
6936 while (r[i] < --qd) r.subTo(t, r)
6937 }
6938 }
6939 if (q != null) {
6940 r.drShiftTo(ys, q)
6941 if (ts != ms) BigInteger.ZERO.subTo(q, q)
6942 }
6943 r.t = ys
6944 r.clamp()
6945 if (nsh > 0) r.rShiftTo(nsh, r); // Denormalize remainder
6946 if (ts < 0) BigInteger.ZERO.subTo(r, r)
6947}
6948
6949// (public) this mod a
6950function bnMod(a) {
6951 var r = new BigInteger()
6952 this.abs()
6953 .divRemTo(a, null, r)
6954 if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r)
6955 return r
6956}
6957
6958// Modular reduction using "classic" algorithm
6959function Classic(m) {
6960 this.m = m
6961}
6962
6963function cConvert(x) {
6964 if (x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m)
6965 else return x
6966}
6967
6968function cRevert(x) {
6969 return x
6970}
6971
6972function cReduce(x) {
6973 x.divRemTo(this.m, null, x)
6974}
6975
6976function cMulTo(x, y, r) {
6977 x.multiplyTo(y, r)
6978 this.reduce(r)
6979}
6980
6981function cSqrTo(x, r) {
6982 x.squareTo(r)
6983 this.reduce(r)
6984}
6985
6986Classic.prototype.convert = cConvert
6987Classic.prototype.revert = cRevert
6988Classic.prototype.reduce = cReduce
6989Classic.prototype.mulTo = cMulTo
6990Classic.prototype.sqrTo = cSqrTo
6991
6992// (protected) return "-1/this % 2^DB"; useful for Mont. reduction
6993// justification:
6994// xy == 1 (mod m)
6995// xy = 1+km
6996// xy(2-xy) = (1+km)(1-km)
6997// x[y(2-xy)] = 1-k^2m^2
6998// x[y(2-xy)] == 1 (mod m^2)
6999// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2
7000// should reduce x and y(2-xy) by m^2 at each step to keep size bounded.
7001// JS multiply "overflows" differently from C/C++, so care is needed here.
7002function bnpInvDigit() {
7003 if (this.t < 1) return 0
7004 var x = this[0]
7005 if ((x & 1) == 0) return 0
7006 var y = x & 3; // y == 1/x mod 2^2
7007 y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4
7008 y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8
7009 y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16
7010 // last step - calculate inverse mod DV directly
7011 // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints
7012 y = (y * (2 - x * y % this.DV)) % this.DV; // y == 1/x mod 2^dbits
7013 // we really want the negative inverse, and -DV < y < DV
7014 return (y > 0) ? this.DV - y : -y
7015}
7016
7017// Montgomery reduction
7018function Montgomery(m) {
7019 this.m = m
7020 this.mp = m.invDigit()
7021 this.mpl = this.mp & 0x7fff
7022 this.mph = this.mp >> 15
7023 this.um = (1 << (m.DB - 15)) - 1
7024 this.mt2 = 2 * m.t
7025}
7026
7027// xR mod m
7028function montConvert(x) {
7029 var r = new BigInteger()
7030 x.abs()
7031 .dlShiftTo(this.m.t, r)
7032 r.divRemTo(this.m, null, r)
7033 if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r)
7034 return r
7035}
7036
7037// x/R mod m
7038function montRevert(x) {
7039 var r = new BigInteger()
7040 x.copyTo(r)
7041 this.reduce(r)
7042 return r
7043}
7044
7045// x = x/R mod m (HAC 14.32)
7046function montReduce(x) {
7047 while (x.t <= this.mt2) // pad x so am has enough room later
7048 x[x.t++] = 0
7049 for (var i = 0; i < this.m.t; ++i) {
7050 // faster way of calculating u0 = x[i]*mp mod DV
7051 var j = x[i] & 0x7fff
7052 var u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & x.DM
7053 // use am to combine the multiply-shift-add into one call
7054 j = i + this.m.t
7055 x[j] += this.m.am(0, u0, x, i, 0, this.m.t)
7056 // propagate carry
7057 while (x[j] >= x.DV) {
7058 x[j] -= x.DV
7059 x[++j]++
7060 }
7061 }
7062 x.clamp()
7063 x.drShiftTo(this.m.t, x)
7064 if (x.compareTo(this.m) >= 0) x.subTo(this.m, x)
7065}
7066
7067// r = "x^2/R mod m"; x != r
7068function montSqrTo(x, r) {
7069 x.squareTo(r)
7070 this.reduce(r)
7071}
7072
7073// r = "xy/R mod m"; x,y != r
7074function montMulTo(x, y, r) {
7075 x.multiplyTo(y, r)
7076 this.reduce(r)
7077}
7078
7079Montgomery.prototype.convert = montConvert
7080Montgomery.prototype.revert = montRevert
7081Montgomery.prototype.reduce = montReduce
7082Montgomery.prototype.mulTo = montMulTo
7083Montgomery.prototype.sqrTo = montSqrTo
7084
7085// (protected) true iff this is even
7086function bnpIsEven() {
7087 return ((this.t > 0) ? (this[0] & 1) : this.s) == 0
7088}
7089
7090// (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79)
7091function bnpExp(e, z) {
7092 if (e > 0xffffffff || e < 1) return BigInteger.ONE
7093 var r = new BigInteger(),
7094 r2 = new BigInteger(),
7095 g = z.convert(this),
7096 i = nbits(e) - 1
7097 g.copyTo(r)
7098 while (--i >= 0) {
7099 z.sqrTo(r, r2)
7100 if ((e & (1 << i)) > 0) z.mulTo(r2, g, r)
7101 else {
7102 var t = r
7103 r = r2
7104 r2 = t
7105 }
7106 }
7107 return z.revert(r)
7108}
7109
7110// (public) this^e % m, 0 <= e < 2^32
7111function bnModPowInt(e, m) {
7112 var z
7113 if (e < 256 || m.isEven()) z = new Classic(m)
7114 else z = new Montgomery(m)
7115 return this.exp(e, z)
7116}
7117
7118// protected
7119proto.copyTo = bnpCopyTo
7120proto.fromInt = bnpFromInt
7121proto.fromString = bnpFromString
7122proto.clamp = bnpClamp
7123proto.dlShiftTo = bnpDLShiftTo
7124proto.drShiftTo = bnpDRShiftTo
7125proto.lShiftTo = bnpLShiftTo
7126proto.rShiftTo = bnpRShiftTo
7127proto.subTo = bnpSubTo
7128proto.multiplyTo = bnpMultiplyTo
7129proto.squareTo = bnpSquareTo
7130proto.divRemTo = bnpDivRemTo
7131proto.invDigit = bnpInvDigit
7132proto.isEven = bnpIsEven
7133proto.exp = bnpExp
7134
7135// public
7136proto.toString = bnToString
7137proto.negate = bnNegate
7138proto.abs = bnAbs
7139proto.compareTo = bnCompareTo
7140proto.bitLength = bnBitLength
7141proto.byteLength = bnByteLength
7142proto.mod = bnMod
7143proto.modPowInt = bnModPowInt
7144
7145// (public)
7146function bnClone() {
7147 var r = new BigInteger()
7148 this.copyTo(r)
7149 return r
7150}
7151
7152// (public) return value as integer
7153function bnIntValue() {
7154 if (this.s < 0) {
7155 if (this.t == 1) return this[0] - this.DV
7156 else if (this.t == 0) return -1
7157 } else if (this.t == 1) return this[0]
7158 else if (this.t == 0) return 0
7159 // assumes 16 < DB < 32
7160 return ((this[1] & ((1 << (32 - this.DB)) - 1)) << this.DB) | this[0]
7161}
7162
7163// (public) return value as byte
7164function bnByteValue() {
7165 return (this.t == 0) ? this.s : (this[0] << 24) >> 24
7166}
7167
7168// (public) return value as short (assumes DB>=16)
7169function bnShortValue() {
7170 return (this.t == 0) ? this.s : (this[0] << 16) >> 16
7171}
7172
7173// (protected) return x s.t. r^x < DV
7174function bnpChunkSize(r) {
7175 return Math.floor(Math.LN2 * this.DB / Math.log(r))
7176}
7177
7178// (public) 0 if this == 0, 1 if this > 0
7179function bnSigNum() {
7180 if (this.s < 0) return -1
7181 else if (this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0
7182 else return 1
7183}
7184
7185// (protected) convert to radix string
7186function bnpToRadix(b) {
7187 if (b == null) b = 10
7188 if (this.signum() == 0 || b < 2 || b > 36) return "0"
7189 var cs = this.chunkSize(b)
7190 var a = Math.pow(b, cs)
7191 var d = nbv(a),
7192 y = new BigInteger(),
7193 z = new BigInteger(),
7194 r = ""
7195 this.divRemTo(d, y, z)
7196 while (y.signum() > 0) {
7197 r = (a + z.intValue())
7198 .toString(b)
7199 .substr(1) + r
7200 y.divRemTo(d, y, z)
7201 }
7202 return z.intValue()
7203 .toString(b) + r
7204}
7205
7206// (protected) convert from radix string
7207function bnpFromRadix(s, b) {
7208 var self = this
7209 self.fromInt(0)
7210 if (b == null) b = 10
7211 var cs = self.chunkSize(b)
7212 var d = Math.pow(b, cs),
7213 mi = false,
7214 j = 0,
7215 w = 0
7216 for (var i = 0; i < s.length; ++i) {
7217 var x = intAt(s, i)
7218 if (x < 0) {
7219 if (s.charAt(i) == "-" && self.signum() == 0) mi = true
7220 continue
7221 }
7222 w = b * w + x
7223 if (++j >= cs) {
7224 self.dMultiply(d)
7225 self.dAddOffset(w, 0)
7226 j = 0
7227 w = 0
7228 }
7229 }
7230 if (j > 0) {
7231 self.dMultiply(Math.pow(b, j))
7232 self.dAddOffset(w, 0)
7233 }
7234 if (mi) BigInteger.ZERO.subTo(self, self)
7235}
7236
7237// (protected) alternate constructor
7238function bnpFromNumber(a, b, c) {
7239 var self = this
7240 if ("number" == typeof b) {
7241 // new BigInteger(int,int,RNG)
7242 if (a < 2) self.fromInt(1)
7243 else {
7244 self.fromNumber(a, c)
7245 if (!self.testBit(a - 1)) // force MSB set
7246 self.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, self)
7247 if (self.isEven()) self.dAddOffset(1, 0); // force odd
7248 while (!self.isProbablePrime(b)) {
7249 self.dAddOffset(2, 0)
7250 if (self.bitLength() > a) self.subTo(BigInteger.ONE.shiftLeft(a - 1), self)
7251 }
7252 }
7253 } else {
7254 // new BigInteger(int,RNG)
7255 var x = new Array(),
7256 t = a & 7
7257 x.length = (a >> 3) + 1
7258 b.nextBytes(x)
7259 if (t > 0) x[0] &= ((1 << t) - 1)
7260 else x[0] = 0
7261 self.fromString(x, 256)
7262 }
7263}
7264
7265// (public) convert to bigendian byte array
7266function bnToByteArray() {
7267 var self = this
7268 var i = self.t,
7269 r = new Array()
7270 r[0] = self.s
7271 var p = self.DB - (i * self.DB) % 8,
7272 d, k = 0
7273 if (i-- > 0) {
7274 if (p < self.DB && (d = self[i] >> p) != (self.s & self.DM) >> p)
7275 r[k++] = d | (self.s << (self.DB - p))
7276 while (i >= 0) {
7277 if (p < 8) {
7278 d = (self[i] & ((1 << p) - 1)) << (8 - p)
7279 d |= self[--i] >> (p += self.DB - 8)
7280 } else {
7281 d = (self[i] >> (p -= 8)) & 0xff
7282 if (p <= 0) {
7283 p += self.DB
7284 --i
7285 }
7286 }
7287 if ((d & 0x80) != 0) d |= -256
7288 if (k === 0 && (self.s & 0x80) != (d & 0x80))++k
7289 if (k > 0 || d != self.s) r[k++] = d
7290 }
7291 }
7292 return r
7293}
7294
7295function bnEquals(a) {
7296 return (this.compareTo(a) == 0)
7297}
7298
7299function bnMin(a) {
7300 return (this.compareTo(a) < 0) ? this : a
7301}
7302
7303function bnMax(a) {
7304 return (this.compareTo(a) > 0) ? this : a
7305}
7306
7307// (protected) r = this op a (bitwise)
7308function bnpBitwiseTo(a, op, r) {
7309 var self = this
7310 var i, f, m = Math.min(a.t, self.t)
7311 for (i = 0; i < m; ++i) r[i] = op(self[i], a[i])
7312 if (a.t < self.t) {
7313 f = a.s & self.DM
7314 for (i = m; i < self.t; ++i) r[i] = op(self[i], f)
7315 r.t = self.t
7316 } else {
7317 f = self.s & self.DM
7318 for (i = m; i < a.t; ++i) r[i] = op(f, a[i])
7319 r.t = a.t
7320 }
7321 r.s = op(self.s, a.s)
7322 r.clamp()
7323}
7324
7325// (public) this & a
7326function op_and(x, y) {
7327 return x & y
7328}
7329
7330function bnAnd(a) {
7331 var r = new BigInteger()
7332 this.bitwiseTo(a, op_and, r)
7333 return r
7334}
7335
7336// (public) this | a
7337function op_or(x, y) {
7338 return x | y
7339}
7340
7341function bnOr(a) {
7342 var r = new BigInteger()
7343 this.bitwiseTo(a, op_or, r)
7344 return r
7345}
7346
7347// (public) this ^ a
7348function op_xor(x, y) {
7349 return x ^ y
7350}
7351
7352function bnXor(a) {
7353 var r = new BigInteger()
7354 this.bitwiseTo(a, op_xor, r)
7355 return r
7356}
7357
7358// (public) this & ~a
7359function op_andnot(x, y) {
7360 return x & ~y
7361}
7362
7363function bnAndNot(a) {
7364 var r = new BigInteger()
7365 this.bitwiseTo(a, op_andnot, r)
7366 return r
7367}
7368
7369// (public) ~this
7370function bnNot() {
7371 var r = new BigInteger()
7372 for (var i = 0; i < this.t; ++i) r[i] = this.DM & ~this[i]
7373 r.t = this.t
7374 r.s = ~this.s
7375 return r
7376}
7377
7378// (public) this << n
7379function bnShiftLeft(n) {
7380 var r = new BigInteger()
7381 if (n < 0) this.rShiftTo(-n, r)
7382 else this.lShiftTo(n, r)
7383 return r
7384}
7385
7386// (public) this >> n
7387function bnShiftRight(n) {
7388 var r = new BigInteger()
7389 if (n < 0) this.lShiftTo(-n, r)
7390 else this.rShiftTo(n, r)
7391 return r
7392}
7393
7394// return index of lowest 1-bit in x, x < 2^31
7395function lbit(x) {
7396 if (x == 0) return -1
7397 var r = 0
7398 if ((x & 0xffff) == 0) {
7399 x >>= 16
7400 r += 16
7401 }
7402 if ((x & 0xff) == 0) {
7403 x >>= 8
7404 r += 8
7405 }
7406 if ((x & 0xf) == 0) {
7407 x >>= 4
7408 r += 4
7409 }
7410 if ((x & 3) == 0) {
7411 x >>= 2
7412 r += 2
7413 }
7414 if ((x & 1) == 0)++r
7415 return r
7416}
7417
7418// (public) returns index of lowest 1-bit (or -1 if none)
7419function bnGetLowestSetBit() {
7420 for (var i = 0; i < this.t; ++i)
7421 if (this[i] != 0) return i * this.DB + lbit(this[i])
7422 if (this.s < 0) return this.t * this.DB
7423 return -1
7424}
7425
7426// return number of 1 bits in x
7427function cbit(x) {
7428 var r = 0
7429 while (x != 0) {
7430 x &= x - 1
7431 ++r
7432 }
7433 return r
7434}
7435
7436// (public) return number of set bits
7437function bnBitCount() {
7438 var r = 0,
7439 x = this.s & this.DM
7440 for (var i = 0; i < this.t; ++i) r += cbit(this[i] ^ x)
7441 return r
7442}
7443
7444// (public) true iff nth bit is set
7445function bnTestBit(n) {
7446 var j = Math.floor(n / this.DB)
7447 if (j >= this.t) return (this.s != 0)
7448 return ((this[j] & (1 << (n % this.DB))) != 0)
7449}
7450
7451// (protected) this op (1<<n)
7452function bnpChangeBit(n, op) {
7453 var r = BigInteger.ONE.shiftLeft(n)
7454 this.bitwiseTo(r, op, r)
7455 return r
7456}
7457
7458// (public) this | (1<<n)
7459function bnSetBit(n) {
7460 return this.changeBit(n, op_or)
7461}
7462
7463// (public) this & ~(1<<n)
7464function bnClearBit(n) {
7465 return this.changeBit(n, op_andnot)
7466}
7467
7468// (public) this ^ (1<<n)
7469function bnFlipBit(n) {
7470 return this.changeBit(n, op_xor)
7471}
7472
7473// (protected) r = this + a
7474function bnpAddTo(a, r) {
7475 var self = this
7476
7477 var i = 0,
7478 c = 0,
7479 m = Math.min(a.t, self.t)
7480 while (i < m) {
7481 c += self[i] + a[i]
7482 r[i++] = c & self.DM
7483 c >>= self.DB
7484 }
7485 if (a.t < self.t) {
7486 c += a.s
7487 while (i < self.t) {
7488 c += self[i]
7489 r[i++] = c & self.DM
7490 c >>= self.DB
7491 }
7492 c += self.s
7493 } else {
7494 c += self.s
7495 while (i < a.t) {
7496 c += a[i]
7497 r[i++] = c & self.DM
7498 c >>= self.DB
7499 }
7500 c += a.s
7501 }
7502 r.s = (c < 0) ? -1 : 0
7503 if (c > 0) r[i++] = c
7504 else if (c < -1) r[i++] = self.DV + c
7505 r.t = i
7506 r.clamp()
7507}
7508
7509// (public) this + a
7510function bnAdd(a) {
7511 var r = new BigInteger()
7512 this.addTo(a, r)
7513 return r
7514}
7515
7516// (public) this - a
7517function bnSubtract(a) {
7518 var r = new BigInteger()
7519 this.subTo(a, r)
7520 return r
7521}
7522
7523// (public) this * a
7524function bnMultiply(a) {
7525 var r = new BigInteger()
7526 this.multiplyTo(a, r)
7527 return r
7528}
7529
7530// (public) this^2
7531function bnSquare() {
7532 var r = new BigInteger()
7533 this.squareTo(r)
7534 return r
7535}
7536
7537// (public) this / a
7538function bnDivide(a) {
7539 var r = new BigInteger()
7540 this.divRemTo(a, r, null)
7541 return r
7542}
7543
7544// (public) this % a
7545function bnRemainder(a) {
7546 var r = new BigInteger()
7547 this.divRemTo(a, null, r)
7548 return r
7549}
7550
7551// (public) [this/a,this%a]
7552function bnDivideAndRemainder(a) {
7553 var q = new BigInteger(),
7554 r = new BigInteger()
7555 this.divRemTo(a, q, r)
7556 return new Array(q, r)
7557}
7558
7559// (protected) this *= n, this >= 0, 1 < n < DV
7560function bnpDMultiply(n) {
7561 this[this.t] = this.am(0, n - 1, this, 0, 0, this.t)
7562 ++this.t
7563 this.clamp()
7564}
7565
7566// (protected) this += n << w words, this >= 0
7567function bnpDAddOffset(n, w) {
7568 if (n == 0) return
7569 while (this.t <= w) this[this.t++] = 0
7570 this[w] += n
7571 while (this[w] >= this.DV) {
7572 this[w] -= this.DV
7573 if (++w >= this.t) this[this.t++] = 0
7574 ++this[w]
7575 }
7576}
7577
7578// A "null" reducer
7579function NullExp() {}
7580
7581function nNop(x) {
7582 return x
7583}
7584
7585function nMulTo(x, y, r) {
7586 x.multiplyTo(y, r)
7587}
7588
7589function nSqrTo(x, r) {
7590 x.squareTo(r)
7591}
7592
7593NullExp.prototype.convert = nNop
7594NullExp.prototype.revert = nNop
7595NullExp.prototype.mulTo = nMulTo
7596NullExp.prototype.sqrTo = nSqrTo
7597
7598// (public) this^e
7599function bnPow(e) {
7600 return this.exp(e, new NullExp())
7601}
7602
7603// (protected) r = lower n words of "this * a", a.t <= n
7604// "this" should be the larger one if appropriate.
7605function bnpMultiplyLowerTo(a, n, r) {
7606 var i = Math.min(this.t + a.t, n)
7607 r.s = 0; // assumes a,this >= 0
7608 r.t = i
7609 while (i > 0) r[--i] = 0
7610 var j
7611 for (j = r.t - this.t; i < j; ++i) r[i + this.t] = this.am(0, a[i], r, i, 0, this.t)
7612 for (j = Math.min(a.t, n); i < j; ++i) this.am(0, a[i], r, i, 0, n - i)
7613 r.clamp()
7614}
7615
7616// (protected) r = "this * a" without lower n words, n > 0
7617// "this" should be the larger one if appropriate.
7618function bnpMultiplyUpperTo(a, n, r) {
7619 --n
7620 var i = r.t = this.t + a.t - n
7621 r.s = 0; // assumes a,this >= 0
7622 while (--i >= 0) r[i] = 0
7623 for (i = Math.max(n - this.t, 0); i < a.t; ++i)
7624 r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n)
7625 r.clamp()
7626 r.drShiftTo(1, r)
7627}
7628
7629// Barrett modular reduction
7630function Barrett(m) {
7631 // setup Barrett
7632 this.r2 = new BigInteger()
7633 this.q3 = new BigInteger()
7634 BigInteger.ONE.dlShiftTo(2 * m.t, this.r2)
7635 this.mu = this.r2.divide(m)
7636 this.m = m
7637}
7638
7639function barrettConvert(x) {
7640 if (x.s < 0 || x.t > 2 * this.m.t) return x.mod(this.m)
7641 else if (x.compareTo(this.m) < 0) return x
7642 else {
7643 var r = new BigInteger()
7644 x.copyTo(r)
7645 this.reduce(r)
7646 return r
7647 }
7648}
7649
7650function barrettRevert(x) {
7651 return x
7652}
7653
7654// x = x mod m (HAC 14.42)
7655function barrettReduce(x) {
7656 var self = this
7657 x.drShiftTo(self.m.t - 1, self.r2)
7658 if (x.t > self.m.t + 1) {
7659 x.t = self.m.t + 1
7660 x.clamp()
7661 }
7662 self.mu.multiplyUpperTo(self.r2, self.m.t + 1, self.q3)
7663 self.m.multiplyLowerTo(self.q3, self.m.t + 1, self.r2)
7664 while (x.compareTo(self.r2) < 0) x.dAddOffset(1, self.m.t + 1)
7665 x.subTo(self.r2, x)
7666 while (x.compareTo(self.m) >= 0) x.subTo(self.m, x)
7667}
7668
7669// r = x^2 mod m; x != r
7670function barrettSqrTo(x, r) {
7671 x.squareTo(r)
7672 this.reduce(r)
7673}
7674
7675// r = x*y mod m; x,y != r
7676function barrettMulTo(x, y, r) {
7677 x.multiplyTo(y, r)
7678 this.reduce(r)
7679}
7680
7681Barrett.prototype.convert = barrettConvert
7682Barrett.prototype.revert = barrettRevert
7683Barrett.prototype.reduce = barrettReduce
7684Barrett.prototype.mulTo = barrettMulTo
7685Barrett.prototype.sqrTo = barrettSqrTo
7686
7687// (public) this^e % m (HAC 14.85)
7688function bnModPow(e, m) {
7689 var i = e.bitLength(),
7690 k, r = nbv(1),
7691 z
7692 if (i <= 0) return r
7693 else if (i < 18) k = 1
7694 else if (i < 48) k = 3
7695 else if (i < 144) k = 4
7696 else if (i < 768) k = 5
7697 else k = 6
7698 if (i < 8)
7699 z = new Classic(m)
7700 else if (m.isEven())
7701 z = new Barrett(m)
7702 else
7703 z = new Montgomery(m)
7704
7705 // precomputation
7706 var g = new Array(),
7707 n = 3,
7708 k1 = k - 1,
7709 km = (1 << k) - 1
7710 g[1] = z.convert(this)
7711 if (k > 1) {
7712 var g2 = new BigInteger()
7713 z.sqrTo(g[1], g2)
7714 while (n <= km) {
7715 g[n] = new BigInteger()
7716 z.mulTo(g2, g[n - 2], g[n])
7717 n += 2
7718 }
7719 }
7720
7721 var j = e.t - 1,
7722 w, is1 = true,
7723 r2 = new BigInteger(),
7724 t
7725 i = nbits(e[j]) - 1
7726 while (j >= 0) {
7727 if (i >= k1) w = (e[j] >> (i - k1)) & km
7728 else {
7729 w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i)
7730 if (j > 0) w |= e[j - 1] >> (this.DB + i - k1)
7731 }
7732
7733 n = k
7734 while ((w & 1) == 0) {
7735 w >>= 1
7736 --n
7737 }
7738 if ((i -= n) < 0) {
7739 i += this.DB
7740 --j
7741 }
7742 if (is1) { // ret == 1, don't bother squaring or multiplying it
7743 g[w].copyTo(r)
7744 is1 = false
7745 } else {
7746 while (n > 1) {
7747 z.sqrTo(r, r2)
7748 z.sqrTo(r2, r)
7749 n -= 2
7750 }
7751 if (n > 0) z.sqrTo(r, r2)
7752 else {
7753 t = r
7754 r = r2
7755 r2 = t
7756 }
7757 z.mulTo(r2, g[w], r)
7758 }
7759
7760 while (j >= 0 && (e[j] & (1 << i)) == 0) {
7761 z.sqrTo(r, r2)
7762 t = r
7763 r = r2
7764 r2 = t
7765 if (--i < 0) {
7766 i = this.DB - 1
7767 --j
7768 }
7769 }
7770 }
7771 return z.revert(r)
7772}
7773
7774// (public) gcd(this,a) (HAC 14.54)
7775function bnGCD(a) {
7776 var x = (this.s < 0) ? this.negate() : this.clone()
7777 var y = (a.s < 0) ? a.negate() : a.clone()
7778 if (x.compareTo(y) < 0) {
7779 var t = x
7780 x = y
7781 y = t
7782 }
7783 var i = x.getLowestSetBit(),
7784 g = y.getLowestSetBit()
7785 if (g < 0) return x
7786 if (i < g) g = i
7787 if (g > 0) {
7788 x.rShiftTo(g, x)
7789 y.rShiftTo(g, y)
7790 }
7791 while (x.signum() > 0) {
7792 if ((i = x.getLowestSetBit()) > 0) x.rShiftTo(i, x)
7793 if ((i = y.getLowestSetBit()) > 0) y.rShiftTo(i, y)
7794 if (x.compareTo(y) >= 0) {
7795 x.subTo(y, x)
7796 x.rShiftTo(1, x)
7797 } else {
7798 y.subTo(x, y)
7799 y.rShiftTo(1, y)
7800 }
7801 }
7802 if (g > 0) y.lShiftTo(g, y)
7803 return y
7804}
7805
7806// (protected) this % n, n < 2^26
7807function bnpModInt(n) {
7808 if (n <= 0) return 0
7809 var d = this.DV % n,
7810 r = (this.s < 0) ? n - 1 : 0
7811 if (this.t > 0)
7812 if (d == 0) r = this[0] % n
7813 else
7814 for (var i = this.t - 1; i >= 0; --i) r = (d * r + this[i]) % n
7815 return r
7816}
7817
7818// (public) 1/this % m (HAC 14.61)
7819function bnModInverse(m) {
7820 var ac = m.isEven()
7821 if (this.signum() === 0) throw new Error('division by zero')
7822 if ((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO
7823 var u = m.clone(),
7824 v = this.clone()
7825 var a = nbv(1),
7826 b = nbv(0),
7827 c = nbv(0),
7828 d = nbv(1)
7829 while (u.signum() != 0) {
7830 while (u.isEven()) {
7831 u.rShiftTo(1, u)
7832 if (ac) {
7833 if (!a.isEven() || !b.isEven()) {
7834 a.addTo(this, a)
7835 b.subTo(m, b)
7836 }
7837 a.rShiftTo(1, a)
7838 } else if (!b.isEven()) b.subTo(m, b)
7839 b.rShiftTo(1, b)
7840 }
7841 while (v.isEven()) {
7842 v.rShiftTo(1, v)
7843 if (ac) {
7844 if (!c.isEven() || !d.isEven()) {
7845 c.addTo(this, c)
7846 d.subTo(m, d)
7847 }
7848 c.rShiftTo(1, c)
7849 } else if (!d.isEven()) d.subTo(m, d)
7850 d.rShiftTo(1, d)
7851 }
7852 if (u.compareTo(v) >= 0) {
7853 u.subTo(v, u)
7854 if (ac) a.subTo(c, a)
7855 b.subTo(d, b)
7856 } else {
7857 v.subTo(u, v)
7858 if (ac) c.subTo(a, c)
7859 d.subTo(b, d)
7860 }
7861 }
7862 if (v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO
7863 while (d.compareTo(m) >= 0) d.subTo(m, d)
7864 while (d.signum() < 0) d.addTo(m, d)
7865 return d
7866}
7867
7868var lowprimes = [
7869 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
7870 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,
7871 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233,
7872 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317,
7873 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419,
7874 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503,
7875 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607,
7876 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701,
7877 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811,
7878 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911,
7879 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997
7880]
7881
7882var lplim = (1 << 26) / lowprimes[lowprimes.length - 1]
7883
7884// (public) test primality with certainty >= 1-.5^t
7885function bnIsProbablePrime(t) {
7886 var i, x = this.abs()
7887 if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) {
7888 for (i = 0; i < lowprimes.length; ++i)
7889 if (x[0] == lowprimes[i]) return true
7890 return false
7891 }
7892 if (x.isEven()) return false
7893 i = 1
7894 while (i < lowprimes.length) {
7895 var m = lowprimes[i],
7896 j = i + 1
7897 while (j < lowprimes.length && m < lplim) m *= lowprimes[j++]
7898 m = x.modInt(m)
7899 while (i < j) if (m % lowprimes[i++] == 0) return false
7900 }
7901 return x.millerRabin(t)
7902}
7903
7904// (protected) true if probably prime (HAC 4.24, Miller-Rabin)
7905function bnpMillerRabin(t) {
7906 var n1 = this.subtract(BigInteger.ONE)
7907 var k = n1.getLowestSetBit()
7908 if (k <= 0) return false
7909 var r = n1.shiftRight(k)
7910 t = (t + 1) >> 1
7911 if (t > lowprimes.length) t = lowprimes.length
7912 var a = new BigInteger(null)
7913 var j, bases = []
7914 for (var i = 0; i < t; ++i) {
7915 for (;;) {
7916 j = lowprimes[Math.floor(Math.random() * lowprimes.length)]
7917 if (bases.indexOf(j) == -1) break
7918 }
7919 bases.push(j)
7920 a.fromInt(j)
7921 var y = a.modPow(r, this)
7922 if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) {
7923 var j = 1
7924 while (j++ < k && y.compareTo(n1) != 0) {
7925 y = y.modPowInt(2, this)
7926 if (y.compareTo(BigInteger.ONE) == 0) return false
7927 }
7928 if (y.compareTo(n1) != 0) return false
7929 }
7930 }
7931 return true
7932}
7933
7934// protected
7935proto.chunkSize = bnpChunkSize
7936proto.toRadix = bnpToRadix
7937proto.fromRadix = bnpFromRadix
7938proto.fromNumber = bnpFromNumber
7939proto.bitwiseTo = bnpBitwiseTo
7940proto.changeBit = bnpChangeBit
7941proto.addTo = bnpAddTo
7942proto.dMultiply = bnpDMultiply
7943proto.dAddOffset = bnpDAddOffset
7944proto.multiplyLowerTo = bnpMultiplyLowerTo
7945proto.multiplyUpperTo = bnpMultiplyUpperTo
7946proto.modInt = bnpModInt
7947proto.millerRabin = bnpMillerRabin
7948
7949// public
7950proto.clone = bnClone
7951proto.intValue = bnIntValue
7952proto.byteValue = bnByteValue
7953proto.shortValue = bnShortValue
7954proto.signum = bnSigNum
7955proto.toByteArray = bnToByteArray
7956proto.equals = bnEquals
7957proto.min = bnMin
7958proto.max = bnMax
7959proto.and = bnAnd
7960proto.or = bnOr
7961proto.xor = bnXor
7962proto.andNot = bnAndNot
7963proto.not = bnNot
7964proto.shiftLeft = bnShiftLeft
7965proto.shiftRight = bnShiftRight
7966proto.getLowestSetBit = bnGetLowestSetBit
7967proto.bitCount = bnBitCount
7968proto.testBit = bnTestBit
7969proto.setBit = bnSetBit
7970proto.clearBit = bnClearBit
7971proto.flipBit = bnFlipBit
7972proto.add = bnAdd
7973proto.subtract = bnSubtract
7974proto.multiply = bnMultiply
7975proto.divide = bnDivide
7976proto.remainder = bnRemainder
7977proto.divideAndRemainder = bnDivideAndRemainder
7978proto.modPow = bnModPow
7979proto.modInverse = bnModInverse
7980proto.pow = bnPow
7981proto.gcd = bnGCD
7982proto.isProbablePrime = bnIsProbablePrime
7983
7984// JSBN-specific extension
7985proto.square = bnSquare
7986
7987// constants
7988BigInteger.ZERO = nbv(0)
7989BigInteger.ONE = nbv(1)
7990BigInteger.valueOf = nbv
7991
7992module.exports = BigInteger
7993
7994},{"../package.json":39}],37:[function(require,module,exports){
7995(function (Buffer){
7996// FIXME: Kind of a weird way to throw exceptions, consider removing
7997var assert = require('assert')
7998var BigInteger = require('./bigi')
7999
8000/**
8001 * Turns a byte array into a big integer.
8002 *
8003 * This function will interpret a byte array as a big integer in big
8004 * endian notation.
8005 */
8006BigInteger.fromByteArrayUnsigned = function(byteArray) {
8007 // BigInteger expects a DER integer conformant byte array
8008 if (byteArray[0] & 0x80) {
8009 return new BigInteger([0].concat(byteArray))
8010 }
8011
8012 return new BigInteger(byteArray)
8013}
8014
8015/**
8016 * Returns a byte array representation of the big integer.
8017 *
8018 * This returns the absolute of the contained value in big endian
8019 * form. A value of zero results in an empty array.
8020 */
8021BigInteger.prototype.toByteArrayUnsigned = function() {
8022 var byteArray = this.toByteArray()
8023 return byteArray[0] === 0 ? byteArray.slice(1) : byteArray
8024}
8025
8026BigInteger.fromDERInteger = function(byteArray) {
8027 return new BigInteger(byteArray)
8028}
8029
8030/*
8031 * Converts BigInteger to a DER integer representation.
8032 *
8033 * The format for this value uses the most significant bit as a sign
8034 * bit. If the most significant bit is already set and the integer is
8035 * positive, a 0x00 is prepended.
8036 *
8037 * Examples:
8038 *
8039 * 0 => 0x00
8040 * 1 => 0x01
8041 * -1 => 0xff
8042 * 127 => 0x7f
8043 * -127 => 0x81
8044 * 128 => 0x0080
8045 * -128 => 0x80
8046 * 255 => 0x00ff
8047 * -255 => 0xff01
8048 * 16300 => 0x3fac
8049 * -16300 => 0xc054
8050 * 62300 => 0x00f35c
8051 * -62300 => 0xff0ca4
8052*/
8053BigInteger.prototype.toDERInteger = BigInteger.prototype.toByteArray
8054
8055BigInteger.fromBuffer = function(buffer) {
8056 // BigInteger expects a DER integer conformant byte array
8057 if (buffer[0] & 0x80) {
8058 var byteArray = Array.prototype.slice.call(buffer)
8059
8060 return new BigInteger([0].concat(byteArray))
8061 }
8062
8063 return new BigInteger(buffer)
8064}
8065
8066BigInteger.fromHex = function(hex) {
8067 if (hex === '') return BigInteger.ZERO
8068
8069 assert.equal(hex, hex.match(/^[A-Fa-f0-9]+/), 'Invalid hex string')
8070 assert.equal(hex.length % 2, 0, 'Incomplete hex')
8071 return new BigInteger(hex, 16)
8072}
8073
8074BigInteger.prototype.toBuffer = function(size) {
8075 var byteArray = this.toByteArrayUnsigned()
8076 var zeros = []
8077
8078 var padding = size - byteArray.length
8079 while (zeros.length < padding) zeros.push(0)
8080
8081 return new Buffer(zeros.concat(byteArray))
8082}
8083
8084BigInteger.prototype.toHex = function(size) {
8085 return this.toBuffer(size).toString('hex')
8086}
8087
8088}).call(this,require("buffer").Buffer)
8089},{"./bigi":36,"assert":1,"buffer":5}],38:[function(require,module,exports){
8090var BigInteger = require('./bigi')
8091
8092//addons
8093require('./convert')
8094
8095module.exports = BigInteger
8096},{"./bigi":36,"./convert":37}],39:[function(require,module,exports){
8097module.exports={
8098 "name": "bigi",
8099 "version": "1.4.2",
8100 "description": "Big integers.",
8101 "keywords": [
8102 "cryptography",
8103 "math",
8104 "bitcoin",
8105 "arbitrary",
8106 "precision",
8107 "arithmetic",
8108 "big",
8109 "integer",
8110 "int",
8111 "number",
8112 "biginteger",
8113 "bigint",
8114 "bignumber",
8115 "decimal",
8116 "float"
8117 ],
8118 "devDependencies": {
8119 "coveralls": "^2.11.2",
8120 "istanbul": "^0.3.5",
8121 "jshint": "^2.5.1",
8122 "mocha": "^2.1.0",
8123 "mochify": "^2.1.0"
8124 },
8125 "repository": {
8126 "url": "https://github.com/cryptocoinjs/bigi",
8127 "type": "git"
8128 },
8129 "main": "./lib/index.js",
8130 "scripts": {
8131 "browser-test": "./node_modules/.bin/mochify --wd -R spec",
8132 "test": "./node_modules/.bin/_mocha -- test/*.js",
8133 "jshint": "./node_modules/.bin/jshint --config jshint.json lib/*.js ; true",
8134 "unit": "./node_modules/.bin/mocha",
8135 "coverage": "./node_modules/.bin/istanbul cover ./node_modules/.bin/_mocha -- --reporter list test/*.js",
8136 "coveralls": "npm run-script coverage && node ./node_modules/.bin/coveralls < coverage/lcov.info"
8137 },
8138 "dependencies": {},
8139 "testling": {
8140 "files": "test/*.js",
8141 "harness": "mocha",
8142 "browsers": [
8143 "ie/9..latest",
8144 "firefox/latest",
8145 "chrome/latest",
8146 "safari/6.0..latest",
8147 "iphone/6.0..latest",
8148 "android-browser/4.2..latest"
8149 ]
8150 }
8151}
8152
8153},{}],40:[function(require,module,exports){
8154(function (Buffer){
8155// based on the aes implimentation in triple sec
8156// https://github.com/keybase/triplesec
8157
8158// which is in turn based on the one from crypto-js
8159// https://code.google.com/p/crypto-js/
8160
8161var uint_max = Math.pow(2, 32)
8162function fixup_uint32 (x) {
8163 var ret, x_pos
8164 ret = x > uint_max || x < 0 ? (x_pos = Math.abs(x) % uint_max, x < 0 ? uint_max - x_pos : x_pos) : x
8165 return ret
8166}
8167function scrub_vec (v) {
8168 for (var i = 0; i < v.length; v++) {
8169 v[i] = 0
8170 }
8171 return false
8172}
8173
8174function Global () {
8175 this.SBOX = []
8176 this.INV_SBOX = []
8177 this.SUB_MIX = [[], [], [], []]
8178 this.INV_SUB_MIX = [[], [], [], []]
8179 this.init()
8180 this.RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]
8181}
8182
8183Global.prototype.init = function () {
8184 var d, i, sx, t, x, x2, x4, x8, xi, _i
8185 d = (function () {
8186 var _i, _results
8187 _results = []
8188 for (i = _i = 0; _i < 256; i = ++_i) {
8189 if (i < 128) {
8190 _results.push(i << 1)
8191 } else {
8192 _results.push((i << 1) ^ 0x11b)
8193 }
8194 }
8195 return _results
8196 })()
8197 x = 0
8198 xi = 0
8199 for (i = _i = 0; _i < 256; i = ++_i) {
8200 sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4)
8201 sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63
8202 this.SBOX[x] = sx
8203 this.INV_SBOX[sx] = x
8204 x2 = d[x]
8205 x4 = d[x2]
8206 x8 = d[x4]
8207 t = (d[sx] * 0x101) ^ (sx * 0x1010100)
8208 this.SUB_MIX[0][x] = (t << 24) | (t >>> 8)
8209 this.SUB_MIX[1][x] = (t << 16) | (t >>> 16)
8210 this.SUB_MIX[2][x] = (t << 8) | (t >>> 24)
8211 this.SUB_MIX[3][x] = t
8212 t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100)
8213 this.INV_SUB_MIX[0][sx] = (t << 24) | (t >>> 8)
8214 this.INV_SUB_MIX[1][sx] = (t << 16) | (t >>> 16)
8215 this.INV_SUB_MIX[2][sx] = (t << 8) | (t >>> 24)
8216 this.INV_SUB_MIX[3][sx] = t
8217 if (x === 0) {
8218 x = xi = 1
8219 } else {
8220 x = x2 ^ d[d[d[x8 ^ x2]]]
8221 xi ^= d[d[xi]]
8222 }
8223 }
8224 return true
8225}
8226
8227var G = new Global()
8228
8229AES.blockSize = 4 * 4
8230
8231AES.prototype.blockSize = AES.blockSize
8232
8233AES.keySize = 256 / 8
8234
8235AES.prototype.keySize = AES.keySize
8236
8237function bufferToArray (buf) {
8238 var len = buf.length / 4
8239 var out = new Array(len)
8240 var i = -1
8241 while (++i < len) {
8242 out[i] = buf.readUInt32BE(i * 4)
8243 }
8244 return out
8245}
8246function AES (key) {
8247 this._key = bufferToArray(key)
8248 this._doReset()
8249}
8250
8251AES.prototype._doReset = function () {
8252 var invKsRow, keySize, keyWords, ksRow, ksRows, t
8253 keyWords = this._key
8254 keySize = keyWords.length
8255 this._nRounds = keySize + 6
8256 ksRows = (this._nRounds + 1) * 4
8257 this._keySchedule = []
8258 for (ksRow = 0; ksRow < ksRows; ksRow++) {
8259 this._keySchedule[ksRow] = ksRow < keySize ? keyWords[ksRow] : (t = this._keySchedule[ksRow - 1], (ksRow % keySize) === 0 ? (t = (t << 8) | (t >>> 24), t = (G.SBOX[t >>> 24] << 24) | (G.SBOX[(t >>> 16) & 0xff] << 16) | (G.SBOX[(t >>> 8) & 0xff] << 8) | G.SBOX[t & 0xff], t ^= G.RCON[(ksRow / keySize) | 0] << 24) : keySize > 6 && ksRow % keySize === 4 ? t = (G.SBOX[t >>> 24] << 24) | (G.SBOX[(t >>> 16) & 0xff] << 16) | (G.SBOX[(t >>> 8) & 0xff] << 8) | G.SBOX[t & 0xff] : void 0, this._keySchedule[ksRow - keySize] ^ t)
8260 }
8261 this._invKeySchedule = []
8262 for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {
8263 ksRow = ksRows - invKsRow
8264 t = this._keySchedule[ksRow - (invKsRow % 4 ? 0 : 4)]
8265 this._invKeySchedule[invKsRow] = invKsRow < 4 || ksRow <= 4 ? t : G.INV_SUB_MIX[0][G.SBOX[t >>> 24]] ^ G.INV_SUB_MIX[1][G.SBOX[(t >>> 16) & 0xff]] ^ G.INV_SUB_MIX[2][G.SBOX[(t >>> 8) & 0xff]] ^ G.INV_SUB_MIX[3][G.SBOX[t & 0xff]]
8266 }
8267 return true
8268}
8269
8270AES.prototype.encryptBlock = function (M) {
8271 M = bufferToArray(new Buffer(M))
8272 var out = this._doCryptBlock(M, this._keySchedule, G.SUB_MIX, G.SBOX)
8273 var buf = new Buffer(16)
8274 buf.writeUInt32BE(out[0], 0)
8275 buf.writeUInt32BE(out[1], 4)
8276 buf.writeUInt32BE(out[2], 8)
8277 buf.writeUInt32BE(out[3], 12)
8278 return buf
8279}
8280
8281AES.prototype.decryptBlock = function (M) {
8282 M = bufferToArray(new Buffer(M))
8283 var temp = [M[3], M[1]]
8284 M[1] = temp[0]
8285 M[3] = temp[1]
8286 var out = this._doCryptBlock(M, this._invKeySchedule, G.INV_SUB_MIX, G.INV_SBOX)
8287 var buf = new Buffer(16)
8288 buf.writeUInt32BE(out[0], 0)
8289 buf.writeUInt32BE(out[3], 4)
8290 buf.writeUInt32BE(out[2], 8)
8291 buf.writeUInt32BE(out[1], 12)
8292 return buf
8293}
8294
8295AES.prototype.scrub = function () {
8296 scrub_vec(this._keySchedule)
8297 scrub_vec(this._invKeySchedule)
8298 scrub_vec(this._key)
8299}
8300
8301AES.prototype._doCryptBlock = function (M, keySchedule, SUB_MIX, SBOX) {
8302 var ksRow, s0, s1, s2, s3, t0, t1, t2, t3
8303
8304 s0 = M[0] ^ keySchedule[0]
8305 s1 = M[1] ^ keySchedule[1]
8306 s2 = M[2] ^ keySchedule[2]
8307 s3 = M[3] ^ keySchedule[3]
8308 ksRow = 4
8309 for (var round = 1; round < this._nRounds; round++) {
8310 t0 = SUB_MIX[0][s0 >>> 24] ^ SUB_MIX[1][(s1 >>> 16) & 0xff] ^ SUB_MIX[2][(s2 >>> 8) & 0xff] ^ SUB_MIX[3][s3 & 0xff] ^ keySchedule[ksRow++]
8311 t1 = SUB_MIX[0][s1 >>> 24] ^ SUB_MIX[1][(s2 >>> 16) & 0xff] ^ SUB_MIX[2][(s3 >>> 8) & 0xff] ^ SUB_MIX[3][s0 & 0xff] ^ keySchedule[ksRow++]
8312 t2 = SUB_MIX[0][s2 >>> 24] ^ SUB_MIX[1][(s3 >>> 16) & 0xff] ^ SUB_MIX[2][(s0 >>> 8) & 0xff] ^ SUB_MIX[3][s1 & 0xff] ^ keySchedule[ksRow++]
8313 t3 = SUB_MIX[0][s3 >>> 24] ^ SUB_MIX[1][(s0 >>> 16) & 0xff] ^ SUB_MIX[2][(s1 >>> 8) & 0xff] ^ SUB_MIX[3][s2 & 0xff] ^ keySchedule[ksRow++]
8314 s0 = t0
8315 s1 = t1
8316 s2 = t2
8317 s3 = t3
8318 }
8319 t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]
8320 t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]
8321 t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]
8322 t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]
8323 return [
8324 fixup_uint32(t0),
8325 fixup_uint32(t1),
8326 fixup_uint32(t2),
8327 fixup_uint32(t3)
8328 ]
8329}
8330
8331exports.AES = AES
8332
8333}).call(this,require("buffer").Buffer)
8334},{"buffer":5}],41:[function(require,module,exports){
8335(function (Buffer){
8336var aes = require('./aes')
8337var Transform = require('cipher-base')
8338var inherits = require('inherits')
8339var GHASH = require('./ghash')
8340var xor = require('buffer-xor')
8341inherits(StreamCipher, Transform)
8342module.exports = StreamCipher
8343
8344function StreamCipher (mode, key, iv, decrypt) {
8345 if (!(this instanceof StreamCipher)) {
8346 return new StreamCipher(mode, key, iv)
8347 }
8348 Transform.call(this)
8349 this._finID = Buffer.concat([iv, new Buffer([0, 0, 0, 1])])
8350 iv = Buffer.concat([iv, new Buffer([0, 0, 0, 2])])
8351 this._cipher = new aes.AES(key)
8352 this._prev = new Buffer(iv.length)
8353 this._cache = new Buffer('')
8354 this._secCache = new Buffer('')
8355 this._decrypt = decrypt
8356 this._alen = 0
8357 this._len = 0
8358 iv.copy(this._prev)
8359 this._mode = mode
8360 var h = new Buffer(4)
8361 h.fill(0)
8362 this._ghash = new GHASH(this._cipher.encryptBlock(h))
8363 this._authTag = null
8364 this._called = false
8365}
8366StreamCipher.prototype._update = function (chunk) {
8367 if (!this._called && this._alen) {
8368 var rump = 16 - (this._alen % 16)
8369 if (rump < 16) {
8370 rump = new Buffer(rump)
8371 rump.fill(0)
8372 this._ghash.update(rump)
8373 }
8374 }
8375 this._called = true
8376 var out = this._mode.encrypt(this, chunk)
8377 if (this._decrypt) {
8378 this._ghash.update(chunk)
8379 } else {
8380 this._ghash.update(out)
8381 }
8382 this._len += chunk.length
8383 return out
8384}
8385StreamCipher.prototype._final = function () {
8386 if (this._decrypt && !this._authTag) {
8387 throw new Error('Unsupported state or unable to authenticate data')
8388 }
8389 var tag = xor(this._ghash.final(this._alen * 8, this._len * 8), this._cipher.encryptBlock(this._finID))
8390 if (this._decrypt) {
8391 if (xorTest(tag, this._authTag)) {
8392 throw new Error('Unsupported state or unable to authenticate data')
8393 }
8394 } else {
8395 this._authTag = tag
8396 }
8397 this._cipher.scrub()
8398}
8399StreamCipher.prototype.getAuthTag = function getAuthTag () {
8400 if (!this._decrypt && Buffer.isBuffer(this._authTag)) {
8401 return this._authTag
8402 } else {
8403 throw new Error('Attempting to get auth tag in unsupported state')
8404 }
8405}
8406StreamCipher.prototype.setAuthTag = function setAuthTag (tag) {
8407 if (this._decrypt) {
8408 this._authTag = tag
8409 } else {
8410 throw new Error('Attempting to set auth tag in unsupported state')
8411 }
8412}
8413StreamCipher.prototype.setAAD = function setAAD (buf) {
8414 if (!this._called) {
8415 this._ghash.update(buf)
8416 this._alen += buf.length
8417 } else {
8418 throw new Error('Attempting to set AAD in unsupported state')
8419 }
8420}
8421function xorTest (a, b) {
8422 var out = 0
8423 if (a.length !== b.length) {
8424 out++
8425 }
8426 var len = Math.min(a.length, b.length)
8427 var i = -1
8428 while (++i < len) {
8429 out += (a[i] ^ b[i])
8430 }
8431 return out
8432}
8433
8434}).call(this,require("buffer").Buffer)
8435},{"./aes":40,"./ghash":45,"buffer":5,"buffer-xor":56,"cipher-base":58,"inherits":71}],42:[function(require,module,exports){
8436var ciphers = require('./encrypter')
8437exports.createCipher = exports.Cipher = ciphers.createCipher
8438exports.createCipheriv = exports.Cipheriv = ciphers.createCipheriv
8439var deciphers = require('./decrypter')
8440exports.createDecipher = exports.Decipher = deciphers.createDecipher
8441exports.createDecipheriv = exports.Decipheriv = deciphers.createDecipheriv
8442var modes = require('./modes')
8443function getCiphers () {
8444 return Object.keys(modes)
8445}
8446exports.listCiphers = exports.getCiphers = getCiphers
8447
8448},{"./decrypter":43,"./encrypter":44,"./modes":46}],43:[function(require,module,exports){
8449(function (Buffer){
8450var aes = require('./aes')
8451var Transform = require('cipher-base')
8452var inherits = require('inherits')
8453var modes = require('./modes')
8454var StreamCipher = require('./streamCipher')
8455var AuthCipher = require('./authCipher')
8456var ebtk = require('evp_bytestokey')
8457
8458inherits(Decipher, Transform)
8459function Decipher (mode, key, iv) {
8460 if (!(this instanceof Decipher)) {
8461 return new Decipher(mode, key, iv)
8462 }
8463 Transform.call(this)
8464 this._cache = new Splitter()
8465 this._last = void 0
8466 this._cipher = new aes.AES(key)
8467 this._prev = new Buffer(iv.length)
8468 iv.copy(this._prev)
8469 this._mode = mode
8470 this._autopadding = true
8471}
8472Decipher.prototype._update = function (data) {
8473 this._cache.add(data)
8474 var chunk
8475 var thing
8476 var out = []
8477 while ((chunk = this._cache.get(this._autopadding))) {
8478 thing = this._mode.decrypt(this, chunk)
8479 out.push(thing)
8480 }
8481 return Buffer.concat(out)
8482}
8483Decipher.prototype._final = function () {
8484 var chunk = this._cache.flush()
8485 if (this._autopadding) {
8486 return unpad(this._mode.decrypt(this, chunk))
8487 } else if (chunk) {
8488 throw new Error('data not multiple of block length')
8489 }
8490}
8491Decipher.prototype.setAutoPadding = function (setTo) {
8492 this._autopadding = !!setTo
8493 return this
8494}
8495function Splitter () {
8496 if (!(this instanceof Splitter)) {
8497 return new Splitter()
8498 }
8499 this.cache = new Buffer('')
8500}
8501Splitter.prototype.add = function (data) {
8502 this.cache = Buffer.concat([this.cache, data])
8503}
8504
8505Splitter.prototype.get = function (autoPadding) {
8506 var out
8507 if (autoPadding) {
8508 if (this.cache.length > 16) {
8509 out = this.cache.slice(0, 16)
8510 this.cache = this.cache.slice(16)
8511 return out
8512 }
8513 } else {
8514 if (this.cache.length >= 16) {
8515 out = this.cache.slice(0, 16)
8516 this.cache = this.cache.slice(16)
8517 return out
8518 }
8519 }
8520 return null
8521}
8522Splitter.prototype.flush = function () {
8523 if (this.cache.length) {
8524 return this.cache
8525 }
8526}
8527function unpad (last) {
8528 var padded = last[15]
8529 var i = -1
8530 while (++i < padded) {
8531 if (last[(i + (16 - padded))] !== padded) {
8532 throw new Error('unable to decrypt data')
8533 }
8534 }
8535 if (padded === 16) {
8536 return
8537 }
8538 return last.slice(0, 16 - padded)
8539}
8540
8541var modelist = {
8542 ECB: require('./modes/ecb'),
8543 CBC: require('./modes/cbc'),
8544 CFB: require('./modes/cfb'),
8545 CFB8: require('./modes/cfb8'),
8546 CFB1: require('./modes/cfb1'),
8547 OFB: require('./modes/ofb'),
8548 CTR: require('./modes/ctr'),
8549 GCM: require('./modes/ctr')
8550}
8551
8552function createDecipheriv (suite, password, iv) {
8553 var config = modes[suite.toLowerCase()]
8554 if (!config) {
8555 throw new TypeError('invalid suite type')
8556 }
8557 if (typeof iv === 'string') {
8558 iv = new Buffer(iv)
8559 }
8560 if (typeof password === 'string') {
8561 password = new Buffer(password)
8562 }
8563 if (password.length !== config.key / 8) {
8564 throw new TypeError('invalid key length ' + password.length)
8565 }
8566 if (iv.length !== config.iv) {
8567 throw new TypeError('invalid iv length ' + iv.length)
8568 }
8569 if (config.type === 'stream') {
8570 return new StreamCipher(modelist[config.mode], password, iv, true)
8571 } else if (config.type === 'auth') {
8572 return new AuthCipher(modelist[config.mode], password, iv, true)
8573 }
8574 return new Decipher(modelist[config.mode], password, iv)
8575}
8576
8577function createDecipher (suite, password) {
8578 var config = modes[suite.toLowerCase()]
8579 if (!config) {
8580 throw new TypeError('invalid suite type')
8581 }
8582 var keys = ebtk(password, false, config.key, config.iv)
8583 return createDecipheriv(suite, keys.key, keys.iv)
8584}
8585exports.createDecipher = createDecipher
8586exports.createDecipheriv = createDecipheriv
8587
8588}).call(this,require("buffer").Buffer)
8589},{"./aes":40,"./authCipher":41,"./modes":46,"./modes/cbc":47,"./modes/cfb":48,"./modes/cfb1":49,"./modes/cfb8":50,"./modes/ctr":51,"./modes/ecb":52,"./modes/ofb":53,"./streamCipher":54,"buffer":5,"cipher-base":58,"evp_bytestokey":69,"inherits":71}],44:[function(require,module,exports){
8590(function (Buffer){
8591var aes = require('./aes')
8592var Transform = require('cipher-base')
8593var inherits = require('inherits')
8594var modes = require('./modes')
8595var ebtk = require('evp_bytestokey')
8596var StreamCipher = require('./streamCipher')
8597var AuthCipher = require('./authCipher')
8598inherits(Cipher, Transform)
8599function Cipher (mode, key, iv) {
8600 if (!(this instanceof Cipher)) {
8601 return new Cipher(mode, key, iv)
8602 }
8603 Transform.call(this)
8604 this._cache = new Splitter()
8605 this._cipher = new aes.AES(key)
8606 this._prev = new Buffer(iv.length)
8607 iv.copy(this._prev)
8608 this._mode = mode
8609 this._autopadding = true
8610}
8611Cipher.prototype._update = function (data) {
8612 this._cache.add(data)
8613 var chunk
8614 var thing
8615 var out = []
8616 while ((chunk = this._cache.get())) {
8617 thing = this._mode.encrypt(this, chunk)
8618 out.push(thing)
8619 }
8620 return Buffer.concat(out)
8621}
8622Cipher.prototype._final = function () {
8623 var chunk = this._cache.flush()
8624 if (this._autopadding) {
8625 chunk = this._mode.encrypt(this, chunk)
8626 this._cipher.scrub()
8627 return chunk
8628 } else if (chunk.toString('hex') !== '10101010101010101010101010101010') {
8629 this._cipher.scrub()
8630 throw new Error('data not multiple of block length')
8631 }
8632}
8633Cipher.prototype.setAutoPadding = function (setTo) {
8634 this._autopadding = !!setTo
8635 return this
8636}
8637
8638function Splitter () {
8639 if (!(this instanceof Splitter)) {
8640 return new Splitter()
8641 }
8642 this.cache = new Buffer('')
8643}
8644Splitter.prototype.add = function (data) {
8645 this.cache = Buffer.concat([this.cache, data])
8646}
8647
8648Splitter.prototype.get = function () {
8649 if (this.cache.length > 15) {
8650 var out = this.cache.slice(0, 16)
8651 this.cache = this.cache.slice(16)
8652 return out
8653 }
8654 return null
8655}
8656Splitter.prototype.flush = function () {
8657 var len = 16 - this.cache.length
8658 var padBuff = new Buffer(len)
8659
8660 var i = -1
8661 while (++i < len) {
8662 padBuff.writeUInt8(len, i)
8663 }
8664 var out = Buffer.concat([this.cache, padBuff])
8665 return out
8666}
8667var modelist = {
8668 ECB: require('./modes/ecb'),
8669 CBC: require('./modes/cbc'),
8670 CFB: require('./modes/cfb'),
8671 CFB8: require('./modes/cfb8'),
8672 CFB1: require('./modes/cfb1'),
8673 OFB: require('./modes/ofb'),
8674 CTR: require('./modes/ctr'),
8675 GCM: require('./modes/ctr')
8676}
8677
8678function createCipheriv (suite, password, iv) {
8679 var config = modes[suite.toLowerCase()]
8680 if (!config) {
8681 throw new TypeError('invalid suite type')
8682 }
8683 if (typeof iv === 'string') {
8684 iv = new Buffer(iv)
8685 }
8686 if (typeof password === 'string') {
8687 password = new Buffer(password)
8688 }
8689 if (password.length !== config.key / 8) {
8690 throw new TypeError('invalid key length ' + password.length)
8691 }
8692 if (iv.length !== config.iv) {
8693 throw new TypeError('invalid iv length ' + iv.length)
8694 }
8695 if (config.type === 'stream') {
8696 return new StreamCipher(modelist[config.mode], password, iv)
8697 } else if (config.type === 'auth') {
8698 return new AuthCipher(modelist[config.mode], password, iv)
8699 }
8700 return new Cipher(modelist[config.mode], password, iv)
8701}
8702function createCipher (suite, password) {
8703 var config = modes[suite.toLowerCase()]
8704 if (!config) {
8705 throw new TypeError('invalid suite type')
8706 }
8707 var keys = ebtk(password, false, config.key, config.iv)
8708 return createCipheriv(suite, keys.key, keys.iv)
8709}
8710
8711exports.createCipheriv = createCipheriv
8712exports.createCipher = createCipher
8713
8714}).call(this,require("buffer").Buffer)
8715},{"./aes":40,"./authCipher":41,"./modes":46,"./modes/cbc":47,"./modes/cfb":48,"./modes/cfb1":49,"./modes/cfb8":50,"./modes/ctr":51,"./modes/ecb":52,"./modes/ofb":53,"./streamCipher":54,"buffer":5,"cipher-base":58,"evp_bytestokey":69,"inherits":71}],45:[function(require,module,exports){
8716(function (Buffer){
8717var zeros = new Buffer(16)
8718zeros.fill(0)
8719module.exports = GHASH
8720function GHASH (key) {
8721 this.h = key
8722 this.state = new Buffer(16)
8723 this.state.fill(0)
8724 this.cache = new Buffer('')
8725}
8726// from http://bitwiseshiftleft.github.io/sjcl/doc/symbols/src/core_gcm.js.html
8727// by Juho Vähä-Herttua
8728GHASH.prototype.ghash = function (block) {
8729 var i = -1
8730 while (++i < block.length) {
8731 this.state[i] ^= block[i]
8732 }
8733 this._multiply()
8734}
8735
8736GHASH.prototype._multiply = function () {
8737 var Vi = toArray(this.h)
8738 var Zi = [0, 0, 0, 0]
8739 var j, xi, lsb_Vi
8740 var i = -1
8741 while (++i < 128) {
8742 xi = (this.state[~~(i / 8)] & (1 << (7 - i % 8))) !== 0
8743 if (xi) {
8744 // Z_i+1 = Z_i ^ V_i
8745 Zi = xor(Zi, Vi)
8746 }
8747
8748 // Store the value of LSB(V_i)
8749 lsb_Vi = (Vi[3] & 1) !== 0
8750
8751 // V_i+1 = V_i >> 1
8752 for (j = 3; j > 0; j--) {
8753 Vi[j] = (Vi[j] >>> 1) | ((Vi[j - 1] & 1) << 31)
8754 }
8755 Vi[0] = Vi[0] >>> 1
8756
8757 // If LSB(V_i) is 1, V_i+1 = (V_i >> 1) ^ R
8758 if (lsb_Vi) {
8759 Vi[0] = Vi[0] ^ (0xe1 << 24)
8760 }
8761 }
8762 this.state = fromArray(Zi)
8763}
8764GHASH.prototype.update = function (buf) {
8765 this.cache = Buffer.concat([this.cache, buf])
8766 var chunk
8767 while (this.cache.length >= 16) {
8768 chunk = this.cache.slice(0, 16)
8769 this.cache = this.cache.slice(16)
8770 this.ghash(chunk)
8771 }
8772}
8773GHASH.prototype.final = function (abl, bl) {
8774 if (this.cache.length) {
8775 this.ghash(Buffer.concat([this.cache, zeros], 16))
8776 }
8777 this.ghash(fromArray([
8778 0, abl,
8779 0, bl
8780 ]))
8781 return this.state
8782}
8783
8784function toArray (buf) {
8785 return [
8786 buf.readUInt32BE(0),
8787 buf.readUInt32BE(4),
8788 buf.readUInt32BE(8),
8789 buf.readUInt32BE(12)
8790 ]
8791}
8792function fromArray (out) {
8793 out = out.map(fixup_uint32)
8794 var buf = new Buffer(16)
8795 buf.writeUInt32BE(out[0], 0)
8796 buf.writeUInt32BE(out[1], 4)
8797 buf.writeUInt32BE(out[2], 8)
8798 buf.writeUInt32BE(out[3], 12)
8799 return buf
8800}
8801var uint_max = Math.pow(2, 32)
8802function fixup_uint32 (x) {
8803 var ret, x_pos
8804 ret = x > uint_max || x < 0 ? (x_pos = Math.abs(x) % uint_max, x < 0 ? uint_max - x_pos : x_pos) : x
8805 return ret
8806}
8807function xor (a, b) {
8808 return [
8809 a[0] ^ b[0],
8810 a[1] ^ b[1],
8811 a[2] ^ b[2],
8812 a[3] ^ b[3]
8813 ]
8814}
8815
8816}).call(this,require("buffer").Buffer)
8817},{"buffer":5}],46:[function(require,module,exports){
8818exports['aes-128-ecb'] = {
8819 cipher: 'AES',
8820 key: 128,
8821 iv: 0,
8822 mode: 'ECB',
8823 type: 'block'
8824}
8825exports['aes-192-ecb'] = {
8826 cipher: 'AES',
8827 key: 192,
8828 iv: 0,
8829 mode: 'ECB',
8830 type: 'block'
8831}
8832exports['aes-256-ecb'] = {
8833 cipher: 'AES',
8834 key: 256,
8835 iv: 0,
8836 mode: 'ECB',
8837 type: 'block'
8838}
8839exports['aes-128-cbc'] = {
8840 cipher: 'AES',
8841 key: 128,
8842 iv: 16,
8843 mode: 'CBC',
8844 type: 'block'
8845}
8846exports['aes-192-cbc'] = {
8847 cipher: 'AES',
8848 key: 192,
8849 iv: 16,
8850 mode: 'CBC',
8851 type: 'block'
8852}
8853exports['aes-256-cbc'] = {
8854 cipher: 'AES',
8855 key: 256,
8856 iv: 16,
8857 mode: 'CBC',
8858 type: 'block'
8859}
8860exports['aes128'] = exports['aes-128-cbc']
8861exports['aes192'] = exports['aes-192-cbc']
8862exports['aes256'] = exports['aes-256-cbc']
8863exports['aes-128-cfb'] = {
8864 cipher: 'AES',
8865 key: 128,
8866 iv: 16,
8867 mode: 'CFB',
8868 type: 'stream'
8869}
8870exports['aes-192-cfb'] = {
8871 cipher: 'AES',
8872 key: 192,
8873 iv: 16,
8874 mode: 'CFB',
8875 type: 'stream'
8876}
8877exports['aes-256-cfb'] = {
8878 cipher: 'AES',
8879 key: 256,
8880 iv: 16,
8881 mode: 'CFB',
8882 type: 'stream'
8883}
8884exports['aes-128-cfb8'] = {
8885 cipher: 'AES',
8886 key: 128,
8887 iv: 16,
8888 mode: 'CFB8',
8889 type: 'stream'
8890}
8891exports['aes-192-cfb8'] = {
8892 cipher: 'AES',
8893 key: 192,
8894 iv: 16,
8895 mode: 'CFB8',
8896 type: 'stream'
8897}
8898exports['aes-256-cfb8'] = {
8899 cipher: 'AES',
8900 key: 256,
8901 iv: 16,
8902 mode: 'CFB8',
8903 type: 'stream'
8904}
8905exports['aes-128-cfb1'] = {
8906 cipher: 'AES',
8907 key: 128,
8908 iv: 16,
8909 mode: 'CFB1',
8910 type: 'stream'
8911}
8912exports['aes-192-cfb1'] = {
8913 cipher: 'AES',
8914 key: 192,
8915 iv: 16,
8916 mode: 'CFB1',
8917 type: 'stream'
8918}
8919exports['aes-256-cfb1'] = {
8920 cipher: 'AES',
8921 key: 256,
8922 iv: 16,
8923 mode: 'CFB1',
8924 type: 'stream'
8925}
8926exports['aes-128-ofb'] = {
8927 cipher: 'AES',
8928 key: 128,
8929 iv: 16,
8930 mode: 'OFB',
8931 type: 'stream'
8932}
8933exports['aes-192-ofb'] = {
8934 cipher: 'AES',
8935 key: 192,
8936 iv: 16,
8937 mode: 'OFB',
8938 type: 'stream'
8939}
8940exports['aes-256-ofb'] = {
8941 cipher: 'AES',
8942 key: 256,
8943 iv: 16,
8944 mode: 'OFB',
8945 type: 'stream'
8946}
8947exports['aes-128-ctr'] = {
8948 cipher: 'AES',
8949 key: 128,
8950 iv: 16,
8951 mode: 'CTR',
8952 type: 'stream'
8953}
8954exports['aes-192-ctr'] = {
8955 cipher: 'AES',
8956 key: 192,
8957 iv: 16,
8958 mode: 'CTR',
8959 type: 'stream'
8960}
8961exports['aes-256-ctr'] = {
8962 cipher: 'AES',
8963 key: 256,
8964 iv: 16,
8965 mode: 'CTR',
8966 type: 'stream'
8967}
8968exports['aes-128-gcm'] = {
8969 cipher: 'AES',
8970 key: 128,
8971 iv: 12,
8972 mode: 'GCM',
8973 type: 'auth'
8974}
8975exports['aes-192-gcm'] = {
8976 cipher: 'AES',
8977 key: 192,
8978 iv: 12,
8979 mode: 'GCM',
8980 type: 'auth'
8981}
8982exports['aes-256-gcm'] = {
8983 cipher: 'AES',
8984 key: 256,
8985 iv: 12,
8986 mode: 'GCM',
8987 type: 'auth'
8988}
8989
8990},{}],47:[function(require,module,exports){
8991var xor = require('buffer-xor')
8992
8993exports.encrypt = function (self, block) {
8994 var data = xor(block, self._prev)
8995
8996 self._prev = self._cipher.encryptBlock(data)
8997 return self._prev
8998}
8999
9000exports.decrypt = function (self, block) {
9001 var pad = self._prev
9002
9003 self._prev = block
9004 var out = self._cipher.decryptBlock(block)
9005
9006 return xor(out, pad)
9007}
9008
9009},{"buffer-xor":56}],48:[function(require,module,exports){
9010(function (Buffer){
9011var xor = require('buffer-xor')
9012
9013exports.encrypt = function (self, data, decrypt) {
9014 var out = new Buffer('')
9015 var len
9016
9017 while (data.length) {
9018 if (self._cache.length === 0) {
9019 self._cache = self._cipher.encryptBlock(self._prev)
9020 self._prev = new Buffer('')
9021 }
9022
9023 if (self._cache.length <= data.length) {
9024 len = self._cache.length
9025 out = Buffer.concat([out, encryptStart(self, data.slice(0, len), decrypt)])
9026 data = data.slice(len)
9027 } else {
9028 out = Buffer.concat([out, encryptStart(self, data, decrypt)])
9029 break
9030 }
9031 }
9032
9033 return out
9034}
9035function encryptStart (self, data, decrypt) {
9036 var len = data.length
9037 var out = xor(data, self._cache)
9038 self._cache = self._cache.slice(len)
9039 self._prev = Buffer.concat([self._prev, decrypt ? data : out])
9040 return out
9041}
9042
9043}).call(this,require("buffer").Buffer)
9044},{"buffer":5,"buffer-xor":56}],49:[function(require,module,exports){
9045(function (Buffer){
9046function encryptByte (self, byteParam, decrypt) {
9047 var pad
9048 var i = -1
9049 var len = 8
9050 var out = 0
9051 var bit, value
9052 while (++i < len) {
9053 pad = self._cipher.encryptBlock(self._prev)
9054 bit = (byteParam & (1 << (7 - i))) ? 0x80 : 0
9055 value = pad[0] ^ bit
9056 out += ((value & 0x80) >> (i % 8))
9057 self._prev = shiftIn(self._prev, decrypt ? bit : value)
9058 }
9059 return out
9060}
9061exports.encrypt = function (self, chunk, decrypt) {
9062 var len = chunk.length
9063 var out = new Buffer(len)
9064 var i = -1
9065 while (++i < len) {
9066 out[i] = encryptByte(self, chunk[i], decrypt)
9067 }
9068 return out
9069}
9070function shiftIn (buffer, value) {
9071 var len = buffer.length
9072 var i = -1
9073 var out = new Buffer(buffer.length)
9074 buffer = Buffer.concat([buffer, new Buffer([value])])
9075 while (++i < len) {
9076 out[i] = buffer[i] << 1 | buffer[i + 1] >> (7)
9077 }
9078 return out
9079}
9080
9081}).call(this,require("buffer").Buffer)
9082},{"buffer":5}],50:[function(require,module,exports){
9083(function (Buffer){
9084function encryptByte (self, byteParam, decrypt) {
9085 var pad = self._cipher.encryptBlock(self._prev)
9086 var out = pad[0] ^ byteParam
9087 self._prev = Buffer.concat([self._prev.slice(1), new Buffer([decrypt ? byteParam : out])])
9088 return out
9089}
9090exports.encrypt = function (self, chunk, decrypt) {
9091 var len = chunk.length
9092 var out = new Buffer(len)
9093 var i = -1
9094 while (++i < len) {
9095 out[i] = encryptByte(self, chunk[i], decrypt)
9096 }
9097 return out
9098}
9099
9100}).call(this,require("buffer").Buffer)
9101},{"buffer":5}],51:[function(require,module,exports){
9102(function (Buffer){
9103var xor = require('buffer-xor')
9104
9105function incr32 (iv) {
9106 var len = iv.length
9107 var item
9108 while (len--) {
9109 item = iv.readUInt8(len)
9110 if (item === 255) {
9111 iv.writeUInt8(0, len)
9112 } else {
9113 item++
9114 iv.writeUInt8(item, len)
9115 break
9116 }
9117 }
9118}
9119
9120function getBlock (self) {
9121 var out = self._cipher.encryptBlock(self._prev)
9122 incr32(self._prev)
9123 return out
9124}
9125
9126exports.encrypt = function (self, chunk) {
9127 while (self._cache.length < chunk.length) {
9128 self._cache = Buffer.concat([self._cache, getBlock(self)])
9129 }
9130 var pad = self._cache.slice(0, chunk.length)
9131 self._cache = self._cache.slice(chunk.length)
9132 return xor(chunk, pad)
9133}
9134
9135}).call(this,require("buffer").Buffer)
9136},{"buffer":5,"buffer-xor":56}],52:[function(require,module,exports){
9137exports.encrypt = function (self, block) {
9138 return self._cipher.encryptBlock(block)
9139}
9140exports.decrypt = function (self, block) {
9141 return self._cipher.decryptBlock(block)
9142}
9143
9144},{}],53:[function(require,module,exports){
9145(function (Buffer){
9146var xor = require('buffer-xor')
9147
9148function getBlock (self) {
9149 self._prev = self._cipher.encryptBlock(self._prev)
9150 return self._prev
9151}
9152
9153exports.encrypt = function (self, chunk) {
9154 while (self._cache.length < chunk.length) {
9155 self._cache = Buffer.concat([self._cache, getBlock(self)])
9156 }
9157
9158 var pad = self._cache.slice(0, chunk.length)
9159 self._cache = self._cache.slice(chunk.length)
9160 return xor(chunk, pad)
9161}
9162
9163}).call(this,require("buffer").Buffer)
9164},{"buffer":5,"buffer-xor":56}],54:[function(require,module,exports){
9165(function (Buffer){
9166var aes = require('./aes')
9167var Transform = require('cipher-base')
9168var inherits = require('inherits')
9169
9170inherits(StreamCipher, Transform)
9171module.exports = StreamCipher
9172function StreamCipher (mode, key, iv, decrypt) {
9173 if (!(this instanceof StreamCipher)) {
9174 return new StreamCipher(mode, key, iv)
9175 }
9176 Transform.call(this)
9177 this._cipher = new aes.AES(key)
9178 this._prev = new Buffer(iv.length)
9179 this._cache = new Buffer('')
9180 this._secCache = new Buffer('')
9181 this._decrypt = decrypt
9182 iv.copy(this._prev)
9183 this._mode = mode
9184}
9185StreamCipher.prototype._update = function (chunk) {
9186 return this._mode.encrypt(this, chunk, this._decrypt)
9187}
9188StreamCipher.prototype._final = function () {
9189 this._cipher.scrub()
9190}
9191
9192}).call(this,require("buffer").Buffer)
9193},{"./aes":40,"buffer":5,"cipher-base":58,"inherits":71}],55:[function(require,module,exports){
9194var basex = require('base-x')
9195var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
9196
9197module.exports = basex(ALPHABET)
9198
9199},{"base-x":35}],56:[function(require,module,exports){
9200(function (Buffer){
9201module.exports = function xor (a, b) {
9202 var length = Math.min(a.length, b.length)
9203 var buffer = new Buffer(length)
9204
9205 for (var i = 0; i < length; ++i) {
9206 buffer[i] = a[i] ^ b[i]
9207 }
9208
9209 return buffer
9210}
9211
9212}).call(this,require("buffer").Buffer)
9213},{"buffer":5}],57:[function(require,module,exports){
9214/*
9215 Copyright 2013-2014 Daniel Wirtz <dcode@dcode.io>
9216
9217 Licensed under the Apache License, Version 2.0 (the "License");
9218 you may not use this file except in compliance with the License.
9219 You may obtain a copy of the License at
9220
9221 http://www.apache.org/licenses/LICENSE-2.0
9222
9223 Unless required by applicable law or agreed to in writing, software
9224 distributed under the License is distributed on an "AS IS" BASIS,
9225 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9226 See the License for the specific language governing permissions and
9227 limitations under the License.
9228 */
9229
9230/**
9231 * @license bytebuffer.js (c) 2015 Daniel Wirtz <dcode@dcode.io>
9232 * Backing buffer: ArrayBuffer, Accessor: Uint8Array
9233 * Released under the Apache License, Version 2.0
9234 * see: https://github.com/dcodeIO/bytebuffer.js for details
9235 */
9236(function(global, factory) {
9237
9238 /* AMD */ if (typeof define === 'function' && define["amd"])
9239 define(["long"], factory);
9240 /* CommonJS */ else if (typeof require === 'function' && typeof module === "object" && module && module["exports"])
9241 module['exports'] = (function() {
9242 var Long; try { Long = require("long"); } catch (e) {}
9243 return factory(Long);
9244 })();
9245 /* Global */ else
9246 (global["dcodeIO"] = global["dcodeIO"] || {})["ByteBuffer"] = factory(global["dcodeIO"]["Long"]);
9247
9248})(this, function(Long) {
9249 "use strict";
9250
9251 /**
9252 * Constructs a new ByteBuffer.
9253 * @class The swiss army knife for binary data in JavaScript.
9254 * @exports ByteBuffer
9255 * @constructor
9256 * @param {number=} capacity Initial capacity. Defaults to {@link ByteBuffer.DEFAULT_CAPACITY}.
9257 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
9258 * {@link ByteBuffer.DEFAULT_ENDIAN}.
9259 * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
9260 * {@link ByteBuffer.DEFAULT_NOASSERT}.
9261 * @expose
9262 */
9263 var ByteBuffer = function(capacity, littleEndian, noAssert) {
9264 if (typeof capacity === 'undefined')
9265 capacity = ByteBuffer.DEFAULT_CAPACITY;
9266 if (typeof littleEndian === 'undefined')
9267 littleEndian = ByteBuffer.DEFAULT_ENDIAN;
9268 if (typeof noAssert === 'undefined')
9269 noAssert = ByteBuffer.DEFAULT_NOASSERT;
9270 if (!noAssert) {
9271 capacity = capacity | 0;
9272 if (capacity < 0)
9273 throw RangeError("Illegal capacity");
9274 littleEndian = !!littleEndian;
9275 noAssert = !!noAssert;
9276 }
9277
9278 /**
9279 * Backing ArrayBuffer.
9280 * @type {!ArrayBuffer}
9281 * @expose
9282 */
9283 this.buffer = capacity === 0 ? EMPTY_BUFFER : new ArrayBuffer(capacity);
9284
9285 /**
9286 * Uint8Array utilized to manipulate the backing buffer. Becomes `null` if the backing buffer has a capacity of `0`.
9287 * @type {?Uint8Array}
9288 * @expose
9289 */
9290 this.view = capacity === 0 ? null : new Uint8Array(this.buffer);
9291
9292 /**
9293 * Absolute read/write offset.
9294 * @type {number}
9295 * @expose
9296 * @see ByteBuffer#flip
9297 * @see ByteBuffer#clear
9298 */
9299 this.offset = 0;
9300
9301 /**
9302 * Marked offset.
9303 * @type {number}
9304 * @expose
9305 * @see ByteBuffer#mark
9306 * @see ByteBuffer#reset
9307 */
9308 this.markedOffset = -1;
9309
9310 /**
9311 * Absolute limit of the contained data. Set to the backing buffer's capacity upon allocation.
9312 * @type {number}
9313 * @expose
9314 * @see ByteBuffer#flip
9315 * @see ByteBuffer#clear
9316 */
9317 this.limit = capacity;
9318
9319 /**
9320 * Whether to use little endian byte order, defaults to `false` for big endian.
9321 * @type {boolean}
9322 * @expose
9323 */
9324 this.littleEndian = littleEndian;
9325
9326 /**
9327 * Whether to skip assertions of offsets and values, defaults to `false`.
9328 * @type {boolean}
9329 * @expose
9330 */
9331 this.noAssert = noAssert;
9332 };
9333
9334 /**
9335 * ByteBuffer version.
9336 * @type {string}
9337 * @const
9338 * @expose
9339 */
9340 ByteBuffer.VERSION = "5.0.1";
9341
9342 /**
9343 * Little endian constant that can be used instead of its boolean value. Evaluates to `true`.
9344 * @type {boolean}
9345 * @const
9346 * @expose
9347 */
9348 ByteBuffer.LITTLE_ENDIAN = true;
9349
9350 /**
9351 * Big endian constant that can be used instead of its boolean value. Evaluates to `false`.
9352 * @type {boolean}
9353 * @const
9354 * @expose
9355 */
9356 ByteBuffer.BIG_ENDIAN = false;
9357
9358 /**
9359 * Default initial capacity of `16`.
9360 * @type {number}
9361 * @expose
9362 */
9363 ByteBuffer.DEFAULT_CAPACITY = 16;
9364
9365 /**
9366 * Default endianess of `false` for big endian.
9367 * @type {boolean}
9368 * @expose
9369 */
9370 ByteBuffer.DEFAULT_ENDIAN = ByteBuffer.BIG_ENDIAN;
9371
9372 /**
9373 * Default no assertions flag of `false`.
9374 * @type {boolean}
9375 * @expose
9376 */
9377 ByteBuffer.DEFAULT_NOASSERT = false;
9378
9379 /**
9380 * A `Long` class for representing a 64-bit two's-complement integer value. May be `null` if Long.js has not been loaded
9381 * and int64 support is not available.
9382 * @type {?Long}
9383 * @const
9384 * @see https://github.com/dcodeIO/long.js
9385 * @expose
9386 */
9387 ByteBuffer.Long = Long || null;
9388
9389 /**
9390 * @alias ByteBuffer.prototype
9391 * @inner
9392 */
9393 var ByteBufferPrototype = ByteBuffer.prototype;
9394
9395 /**
9396 * An indicator used to reliably determine if an object is a ByteBuffer or not.
9397 * @type {boolean}
9398 * @const
9399 * @expose
9400 * @private
9401 */
9402 ByteBufferPrototype.__isByteBuffer__;
9403
9404 Object.defineProperty(ByteBufferPrototype, "__isByteBuffer__", {
9405 value: true,
9406 enumerable: false,
9407 configurable: false
9408 });
9409
9410 // helpers
9411
9412 /**
9413 * @type {!ArrayBuffer}
9414 * @inner
9415 */
9416 var EMPTY_BUFFER = new ArrayBuffer(0);
9417
9418 /**
9419 * String.fromCharCode reference for compile-time renaming.
9420 * @type {function(...number):string}
9421 * @inner
9422 */
9423 var stringFromCharCode = String.fromCharCode;
9424
9425 /**
9426 * Creates a source function for a string.
9427 * @param {string} s String to read from
9428 * @returns {function():number|null} Source function returning the next char code respectively `null` if there are
9429 * no more characters left.
9430 * @throws {TypeError} If the argument is invalid
9431 * @inner
9432 */
9433 function stringSource(s) {
9434 var i=0; return function() {
9435 return i < s.length ? s.charCodeAt(i++) : null;
9436 };
9437 }
9438
9439 /**
9440 * Creates a destination function for a string.
9441 * @returns {function(number=):undefined|string} Destination function successively called with the next char code.
9442 * Returns the final string when called without arguments.
9443 * @inner
9444 */
9445 function stringDestination() {
9446 var cs = [], ps = []; return function() {
9447 if (arguments.length === 0)
9448 return ps.join('')+stringFromCharCode.apply(String, cs);
9449 if (cs.length + arguments.length > 1024)
9450 ps.push(stringFromCharCode.apply(String, cs)),
9451 cs.length = 0;
9452 Array.prototype.push.apply(cs, arguments);
9453 };
9454 }
9455
9456 /**
9457 * Gets the accessor type.
9458 * @returns {Function} `Buffer` under node.js, `Uint8Array` respectively `DataView` in the browser (classes)
9459 * @expose
9460 */
9461 ByteBuffer.accessor = function() {
9462 return Uint8Array;
9463 };
9464 /**
9465 * Allocates a new ByteBuffer backed by a buffer of the specified capacity.
9466 * @param {number=} capacity Initial capacity. Defaults to {@link ByteBuffer.DEFAULT_CAPACITY}.
9467 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
9468 * {@link ByteBuffer.DEFAULT_ENDIAN}.
9469 * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
9470 * {@link ByteBuffer.DEFAULT_NOASSERT}.
9471 * @returns {!ByteBuffer}
9472 * @expose
9473 */
9474 ByteBuffer.allocate = function(capacity, littleEndian, noAssert) {
9475 return new ByteBuffer(capacity, littleEndian, noAssert);
9476 };
9477
9478 /**
9479 * Concatenates multiple ByteBuffers into one.
9480 * @param {!Array.<!ByteBuffer|!ArrayBuffer|!Uint8Array|string>} buffers Buffers to concatenate
9481 * @param {(string|boolean)=} encoding String encoding if `buffers` contains a string ("base64", "hex", "binary",
9482 * defaults to "utf8")
9483 * @param {boolean=} littleEndian Whether to use little or big endian byte order for the resulting ByteBuffer. Defaults
9484 * to {@link ByteBuffer.DEFAULT_ENDIAN}.
9485 * @param {boolean=} noAssert Whether to skip assertions of offsets and values for the resulting ByteBuffer. Defaults to
9486 * {@link ByteBuffer.DEFAULT_NOASSERT}.
9487 * @returns {!ByteBuffer} Concatenated ByteBuffer
9488 * @expose
9489 */
9490 ByteBuffer.concat = function(buffers, encoding, littleEndian, noAssert) {
9491 if (typeof encoding === 'boolean' || typeof encoding !== 'string') {
9492 noAssert = littleEndian;
9493 littleEndian = encoding;
9494 encoding = undefined;
9495 }
9496 var capacity = 0;
9497 for (var i=0, k=buffers.length, length; i<k; ++i) {
9498 if (!ByteBuffer.isByteBuffer(buffers[i]))
9499 buffers[i] = ByteBuffer.wrap(buffers[i], encoding);
9500 length = buffers[i].limit - buffers[i].offset;
9501 if (length > 0) capacity += length;
9502 }
9503 if (capacity === 0)
9504 return new ByteBuffer(0, littleEndian, noAssert);
9505 var bb = new ByteBuffer(capacity, littleEndian, noAssert),
9506 bi;
9507 i=0; while (i<k) {
9508 bi = buffers[i++];
9509 length = bi.limit - bi.offset;
9510 if (length <= 0) continue;
9511 bb.view.set(bi.view.subarray(bi.offset, bi.limit), bb.offset);
9512 bb.offset += length;
9513 }
9514 bb.limit = bb.offset;
9515 bb.offset = 0;
9516 return bb;
9517 };
9518
9519 /**
9520 * Tests if the specified type is a ByteBuffer.
9521 * @param {*} bb ByteBuffer to test
9522 * @returns {boolean} `true` if it is a ByteBuffer, otherwise `false`
9523 * @expose
9524 */
9525 ByteBuffer.isByteBuffer = function(bb) {
9526 return (bb && bb["__isByteBuffer__"]) === true;
9527 };
9528 /**
9529 * Gets the backing buffer type.
9530 * @returns {Function} `Buffer` under node.js, `ArrayBuffer` in the browser (classes)
9531 * @expose
9532 */
9533 ByteBuffer.type = function() {
9534 return ArrayBuffer;
9535 };
9536 /**
9537 * Wraps a buffer or a string. Sets the allocated ByteBuffer's {@link ByteBuffer#offset} to `0` and its
9538 * {@link ByteBuffer#limit} to the length of the wrapped data.
9539 * @param {!ByteBuffer|!ArrayBuffer|!Uint8Array|string|!Array.<number>} buffer Anything that can be wrapped
9540 * @param {(string|boolean)=} encoding String encoding if `buffer` is a string ("base64", "hex", "binary", defaults to
9541 * "utf8")
9542 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
9543 * {@link ByteBuffer.DEFAULT_ENDIAN}.
9544 * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
9545 * {@link ByteBuffer.DEFAULT_NOASSERT}.
9546 * @returns {!ByteBuffer} A ByteBuffer wrapping `buffer`
9547 * @expose
9548 */
9549 ByteBuffer.wrap = function(buffer, encoding, littleEndian, noAssert) {
9550 if (typeof encoding !== 'string') {
9551 noAssert = littleEndian;
9552 littleEndian = encoding;
9553 encoding = undefined;
9554 }
9555 if (typeof buffer === 'string') {
9556 if (typeof encoding === 'undefined')
9557 encoding = "utf8";
9558 switch (encoding) {
9559 case "base64":
9560 return ByteBuffer.fromBase64(buffer, littleEndian);
9561 case "hex":
9562 return ByteBuffer.fromHex(buffer, littleEndian);
9563 case "binary":
9564 return ByteBuffer.fromBinary(buffer, littleEndian);
9565 case "utf8":
9566 return ByteBuffer.fromUTF8(buffer, littleEndian);
9567 case "debug":
9568 return ByteBuffer.fromDebug(buffer, littleEndian);
9569 default:
9570 throw Error("Unsupported encoding: "+encoding);
9571 }
9572 }
9573 if (buffer === null || typeof buffer !== 'object')
9574 throw TypeError("Illegal buffer");
9575 var bb;
9576 if (ByteBuffer.isByteBuffer(buffer)) {
9577 bb = ByteBufferPrototype.clone.call(buffer);
9578 bb.markedOffset = -1;
9579 return bb;
9580 }
9581 if (buffer instanceof Uint8Array) { // Extract ArrayBuffer from Uint8Array
9582 bb = new ByteBuffer(0, littleEndian, noAssert);
9583 if (buffer.length > 0) { // Avoid references to more than one EMPTY_BUFFER
9584 bb.buffer = buffer.buffer;
9585 bb.offset = buffer.byteOffset;
9586 bb.limit = buffer.byteOffset + buffer.byteLength;
9587 bb.view = new Uint8Array(buffer.buffer);
9588 }
9589 } else if (buffer instanceof ArrayBuffer) { // Reuse ArrayBuffer
9590 bb = new ByteBuffer(0, littleEndian, noAssert);
9591 if (buffer.byteLength > 0) {
9592 bb.buffer = buffer;
9593 bb.offset = 0;
9594 bb.limit = buffer.byteLength;
9595 bb.view = buffer.byteLength > 0 ? new Uint8Array(buffer) : null;
9596 }
9597 } else if (Object.prototype.toString.call(buffer) === "[object Array]") { // Create from octets
9598 bb = new ByteBuffer(buffer.length, littleEndian, noAssert);
9599 bb.limit = buffer.length;
9600 for (var i=0; i<buffer.length; ++i)
9601 bb.view[i] = buffer[i];
9602 } else
9603 throw TypeError("Illegal buffer"); // Otherwise fail
9604 return bb;
9605 };
9606
9607 /**
9608 * Writes the array as a bitset.
9609 * @param {Array<boolean>} value Array of booleans to write
9610 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `length` if omitted.
9611 * @returns {!ByteBuffer}
9612 * @expose
9613 */
9614 ByteBufferPrototype.writeBitSet = function(value, offset) {
9615 var relative = typeof offset === 'undefined';
9616 if (relative) offset = this.offset;
9617 if (!this.noAssert) {
9618 if (!(value instanceof Array))
9619 throw TypeError("Illegal BitSet: Not an array");
9620 if (typeof offset !== 'number' || offset % 1 !== 0)
9621 throw TypeError("Illegal offset: "+offset+" (not an integer)");
9622 offset >>>= 0;
9623 if (offset < 0 || offset + 0 > this.buffer.byteLength)
9624 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
9625 }
9626
9627 var start = offset,
9628 bits = value.length,
9629 bytes = (bits >> 3),
9630 bit = 0,
9631 k;
9632
9633 offset += this.writeVarint32(bits,offset);
9634
9635 while(bytes--) {
9636 k = (!!value[bit++] & 1) |
9637 ((!!value[bit++] & 1) << 1) |
9638 ((!!value[bit++] & 1) << 2) |
9639 ((!!value[bit++] & 1) << 3) |
9640 ((!!value[bit++] & 1) << 4) |
9641 ((!!value[bit++] & 1) << 5) |
9642 ((!!value[bit++] & 1) << 6) |
9643 ((!!value[bit++] & 1) << 7);
9644 this.writeByte(k,offset++);
9645 }
9646
9647 if(bit < bits) {
9648 var m = 0; k = 0;
9649 while(bit < bits) k = k | ((!!value[bit++] & 1) << (m++));
9650 this.writeByte(k,offset++);
9651 }
9652
9653 if (relative) {
9654 this.offset = offset;
9655 return this;
9656 }
9657 return offset - start;
9658 }
9659
9660 /**
9661 * Reads a BitSet as an array of booleans.
9662 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `length` if omitted.
9663 * @returns {Array<boolean>
9664 * @expose
9665 */
9666 ByteBufferPrototype.readBitSet = function(offset) {
9667 var relative = typeof offset === 'undefined';
9668 if (relative) offset = this.offset;
9669
9670 var ret = this.readVarint32(offset),
9671 bits = ret.value,
9672 bytes = (bits >> 3),
9673 bit = 0,
9674 value = [],
9675 k;
9676
9677 offset += ret.length;
9678
9679 while(bytes--) {
9680 k = this.readByte(offset++);
9681 value[bit++] = !!(k & 0x01);
9682 value[bit++] = !!(k & 0x02);
9683 value[bit++] = !!(k & 0x04);
9684 value[bit++] = !!(k & 0x08);
9685 value[bit++] = !!(k & 0x10);
9686 value[bit++] = !!(k & 0x20);
9687 value[bit++] = !!(k & 0x40);
9688 value[bit++] = !!(k & 0x80);
9689 }
9690
9691 if(bit < bits) {
9692 var m = 0;
9693 k = this.readByte(offset++);
9694 while(bit < bits) value[bit++] = !!((k >> (m++)) & 1);
9695 }
9696
9697 if (relative) {
9698 this.offset = offset;
9699 }
9700 return value;
9701 }
9702 /**
9703 * Reads the specified number of bytes.
9704 * @param {number} length Number of bytes to read
9705 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `length` if omitted.
9706 * @returns {!ByteBuffer}
9707 * @expose
9708 */
9709 ByteBufferPrototype.readBytes = function(length, offset) {
9710 var relative = typeof offset === 'undefined';
9711 if (relative) offset = this.offset;
9712 if (!this.noAssert) {
9713 if (typeof offset !== 'number' || offset % 1 !== 0)
9714 throw TypeError("Illegal offset: "+offset+" (not an integer)");
9715 offset >>>= 0;
9716 if (offset < 0 || offset + length > this.buffer.byteLength)
9717 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+length+") <= "+this.buffer.byteLength);
9718 }
9719 var slice = this.slice(offset, offset + length);
9720 if (relative) this.offset += length;
9721 return slice;
9722 };
9723
9724 /**
9725 * Writes a payload of bytes. This is an alias of {@link ByteBuffer#append}.
9726 * @function
9727 * @param {!ByteBuffer|!ArrayBuffer|!Uint8Array|string} source Data to write. If `source` is a ByteBuffer, its offsets
9728 * will be modified according to the performed read operation.
9729 * @param {(string|number)=} encoding Encoding if `data` is a string ("base64", "hex", "binary", defaults to "utf8")
9730 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
9731 * written if omitted.
9732 * @returns {!ByteBuffer} this
9733 * @expose
9734 */
9735 ByteBufferPrototype.writeBytes = ByteBufferPrototype.append;
9736
9737 // types/ints/int8
9738
9739 /**
9740 * Writes an 8bit signed integer.
9741 * @param {number} value Value to write
9742 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
9743 * @returns {!ByteBuffer} this
9744 * @expose
9745 */
9746 ByteBufferPrototype.writeInt8 = function(value, offset) {
9747 var relative = typeof offset === 'undefined';
9748 if (relative) offset = this.offset;
9749 if (!this.noAssert) {
9750 if (typeof value !== 'number' || value % 1 !== 0)
9751 throw TypeError("Illegal value: "+value+" (not an integer)");
9752 value |= 0;
9753 if (typeof offset !== 'number' || offset % 1 !== 0)
9754 throw TypeError("Illegal offset: "+offset+" (not an integer)");
9755 offset >>>= 0;
9756 if (offset < 0 || offset + 0 > this.buffer.byteLength)
9757 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
9758 }
9759 offset += 1;
9760 var capacity0 = this.buffer.byteLength;
9761 if (offset > capacity0)
9762 this.resize((capacity0 *= 2) > offset ? capacity0 : offset);
9763 offset -= 1;
9764 this.view[offset] = value;
9765 if (relative) this.offset += 1;
9766 return this;
9767 };
9768
9769 /**
9770 * Writes an 8bit signed integer. This is an alias of {@link ByteBuffer#writeInt8}.
9771 * @function
9772 * @param {number} value Value to write
9773 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
9774 * @returns {!ByteBuffer} this
9775 * @expose
9776 */
9777 ByteBufferPrototype.writeByte = ByteBufferPrototype.writeInt8;
9778
9779 /**
9780 * Reads an 8bit signed integer.
9781 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
9782 * @returns {number} Value read
9783 * @expose
9784 */
9785 ByteBufferPrototype.readInt8 = function(offset) {
9786 var relative = typeof offset === 'undefined';
9787 if (relative) offset = this.offset;
9788 if (!this.noAssert) {
9789 if (typeof offset !== 'number' || offset % 1 !== 0)
9790 throw TypeError("Illegal offset: "+offset+" (not an integer)");
9791 offset >>>= 0;
9792 if (offset < 0 || offset + 1 > this.buffer.byteLength)
9793 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
9794 }
9795 var value = this.view[offset];
9796 if ((value & 0x80) === 0x80) value = -(0xFF - value + 1); // Cast to signed
9797 if (relative) this.offset += 1;
9798 return value;
9799 };
9800
9801 /**
9802 * Reads an 8bit signed integer. This is an alias of {@link ByteBuffer#readInt8}.
9803 * @function
9804 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
9805 * @returns {number} Value read
9806 * @expose
9807 */
9808 ByteBufferPrototype.readByte = ByteBufferPrototype.readInt8;
9809
9810 /**
9811 * Writes an 8bit unsigned integer.
9812 * @param {number} value Value to write
9813 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
9814 * @returns {!ByteBuffer} this
9815 * @expose
9816 */
9817 ByteBufferPrototype.writeUint8 = function(value, offset) {
9818 var relative = typeof offset === 'undefined';
9819 if (relative) offset = this.offset;
9820 if (!this.noAssert) {
9821 if (typeof value !== 'number' || value % 1 !== 0)
9822 throw TypeError("Illegal value: "+value+" (not an integer)");
9823 value >>>= 0;
9824 if (typeof offset !== 'number' || offset % 1 !== 0)
9825 throw TypeError("Illegal offset: "+offset+" (not an integer)");
9826 offset >>>= 0;
9827 if (offset < 0 || offset + 0 > this.buffer.byteLength)
9828 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
9829 }
9830 offset += 1;
9831 var capacity1 = this.buffer.byteLength;
9832 if (offset > capacity1)
9833 this.resize((capacity1 *= 2) > offset ? capacity1 : offset);
9834 offset -= 1;
9835 this.view[offset] = value;
9836 if (relative) this.offset += 1;
9837 return this;
9838 };
9839
9840 /**
9841 * Writes an 8bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint8}.
9842 * @function
9843 * @param {number} value Value to write
9844 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
9845 * @returns {!ByteBuffer} this
9846 * @expose
9847 */
9848 ByteBufferPrototype.writeUInt8 = ByteBufferPrototype.writeUint8;
9849
9850 /**
9851 * Reads an 8bit unsigned integer.
9852 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
9853 * @returns {number} Value read
9854 * @expose
9855 */
9856 ByteBufferPrototype.readUint8 = function(offset) {
9857 var relative = typeof offset === 'undefined';
9858 if (relative) offset = this.offset;
9859 if (!this.noAssert) {
9860 if (typeof offset !== 'number' || offset % 1 !== 0)
9861 throw TypeError("Illegal offset: "+offset+" (not an integer)");
9862 offset >>>= 0;
9863 if (offset < 0 || offset + 1 > this.buffer.byteLength)
9864 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
9865 }
9866 var value = this.view[offset];
9867 if (relative) this.offset += 1;
9868 return value;
9869 };
9870
9871 /**
9872 * Reads an 8bit unsigned integer. This is an alias of {@link ByteBuffer#readUint8}.
9873 * @function
9874 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
9875 * @returns {number} Value read
9876 * @expose
9877 */
9878 ByteBufferPrototype.readUInt8 = ByteBufferPrototype.readUint8;
9879
9880 // types/ints/int16
9881
9882 /**
9883 * Writes a 16bit signed integer.
9884 * @param {number} value Value to write
9885 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
9886 * @throws {TypeError} If `offset` or `value` is not a valid number
9887 * @throws {RangeError} If `offset` is out of bounds
9888 * @expose
9889 */
9890 ByteBufferPrototype.writeInt16 = function(value, offset) {
9891 var relative = typeof offset === 'undefined';
9892 if (relative) offset = this.offset;
9893 if (!this.noAssert) {
9894 if (typeof value !== 'number' || value % 1 !== 0)
9895 throw TypeError("Illegal value: "+value+" (not an integer)");
9896 value |= 0;
9897 if (typeof offset !== 'number' || offset % 1 !== 0)
9898 throw TypeError("Illegal offset: "+offset+" (not an integer)");
9899 offset >>>= 0;
9900 if (offset < 0 || offset + 0 > this.buffer.byteLength)
9901 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
9902 }
9903 offset += 2;
9904 var capacity2 = this.buffer.byteLength;
9905 if (offset > capacity2)
9906 this.resize((capacity2 *= 2) > offset ? capacity2 : offset);
9907 offset -= 2;
9908 if (this.littleEndian) {
9909 this.view[offset+1] = (value & 0xFF00) >>> 8;
9910 this.view[offset ] = value & 0x00FF;
9911 } else {
9912 this.view[offset] = (value & 0xFF00) >>> 8;
9913 this.view[offset+1] = value & 0x00FF;
9914 }
9915 if (relative) this.offset += 2;
9916 return this;
9917 };
9918
9919 /**
9920 * Writes a 16bit signed integer. This is an alias of {@link ByteBuffer#writeInt16}.
9921 * @function
9922 * @param {number} value Value to write
9923 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
9924 * @throws {TypeError} If `offset` or `value` is not a valid number
9925 * @throws {RangeError} If `offset` is out of bounds
9926 * @expose
9927 */
9928 ByteBufferPrototype.writeShort = ByteBufferPrototype.writeInt16;
9929
9930 /**
9931 * Reads a 16bit signed integer.
9932 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
9933 * @returns {number} Value read
9934 * @throws {TypeError} If `offset` is not a valid number
9935 * @throws {RangeError} If `offset` is out of bounds
9936 * @expose
9937 */
9938 ByteBufferPrototype.readInt16 = function(offset) {
9939 var relative = typeof offset === 'undefined';
9940 if (relative) offset = this.offset;
9941 if (!this.noAssert) {
9942 if (typeof offset !== 'number' || offset % 1 !== 0)
9943 throw TypeError("Illegal offset: "+offset+" (not an integer)");
9944 offset >>>= 0;
9945 if (offset < 0 || offset + 2 > this.buffer.byteLength)
9946 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+2+") <= "+this.buffer.byteLength);
9947 }
9948 var value = 0;
9949 if (this.littleEndian) {
9950 value = this.view[offset ];
9951 value |= this.view[offset+1] << 8;
9952 } else {
9953 value = this.view[offset ] << 8;
9954 value |= this.view[offset+1];
9955 }
9956 if ((value & 0x8000) === 0x8000) value = -(0xFFFF - value + 1); // Cast to signed
9957 if (relative) this.offset += 2;
9958 return value;
9959 };
9960
9961 /**
9962 * Reads a 16bit signed integer. This is an alias of {@link ByteBuffer#readInt16}.
9963 * @function
9964 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
9965 * @returns {number} Value read
9966 * @throws {TypeError} If `offset` is not a valid number
9967 * @throws {RangeError} If `offset` is out of bounds
9968 * @expose
9969 */
9970 ByteBufferPrototype.readShort = ByteBufferPrototype.readInt16;
9971
9972 /**
9973 * Writes a 16bit unsigned integer.
9974 * @param {number} value Value to write
9975 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
9976 * @throws {TypeError} If `offset` or `value` is not a valid number
9977 * @throws {RangeError} If `offset` is out of bounds
9978 * @expose
9979 */
9980 ByteBufferPrototype.writeUint16 = function(value, offset) {
9981 var relative = typeof offset === 'undefined';
9982 if (relative) offset = this.offset;
9983 if (!this.noAssert) {
9984 if (typeof value !== 'number' || value % 1 !== 0)
9985 throw TypeError("Illegal value: "+value+" (not an integer)");
9986 value >>>= 0;
9987 if (typeof offset !== 'number' || offset % 1 !== 0)
9988 throw TypeError("Illegal offset: "+offset+" (not an integer)");
9989 offset >>>= 0;
9990 if (offset < 0 || offset + 0 > this.buffer.byteLength)
9991 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
9992 }
9993 offset += 2;
9994 var capacity3 = this.buffer.byteLength;
9995 if (offset > capacity3)
9996 this.resize((capacity3 *= 2) > offset ? capacity3 : offset);
9997 offset -= 2;
9998 if (this.littleEndian) {
9999 this.view[offset+1] = (value & 0xFF00) >>> 8;
10000 this.view[offset ] = value & 0x00FF;
10001 } else {
10002 this.view[offset] = (value & 0xFF00) >>> 8;
10003 this.view[offset+1] = value & 0x00FF;
10004 }
10005 if (relative) this.offset += 2;
10006 return this;
10007 };
10008
10009 /**
10010 * Writes a 16bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint16}.
10011 * @function
10012 * @param {number} value Value to write
10013 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
10014 * @throws {TypeError} If `offset` or `value` is not a valid number
10015 * @throws {RangeError} If `offset` is out of bounds
10016 * @expose
10017 */
10018 ByteBufferPrototype.writeUInt16 = ByteBufferPrototype.writeUint16;
10019
10020 /**
10021 * Reads a 16bit unsigned integer.
10022 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
10023 * @returns {number} Value read
10024 * @throws {TypeError} If `offset` is not a valid number
10025 * @throws {RangeError} If `offset` is out of bounds
10026 * @expose
10027 */
10028 ByteBufferPrototype.readUint16 = function(offset) {
10029 var relative = typeof offset === 'undefined';
10030 if (relative) offset = this.offset;
10031 if (!this.noAssert) {
10032 if (typeof offset !== 'number' || offset % 1 !== 0)
10033 throw TypeError("Illegal offset: "+offset+" (not an integer)");
10034 offset >>>= 0;
10035 if (offset < 0 || offset + 2 > this.buffer.byteLength)
10036 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+2+") <= "+this.buffer.byteLength);
10037 }
10038 var value = 0;
10039 if (this.littleEndian) {
10040 value = this.view[offset ];
10041 value |= this.view[offset+1] << 8;
10042 } else {
10043 value = this.view[offset ] << 8;
10044 value |= this.view[offset+1];
10045 }
10046 if (relative) this.offset += 2;
10047 return value;
10048 };
10049
10050 /**
10051 * Reads a 16bit unsigned integer. This is an alias of {@link ByteBuffer#readUint16}.
10052 * @function
10053 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
10054 * @returns {number} Value read
10055 * @throws {TypeError} If `offset` is not a valid number
10056 * @throws {RangeError} If `offset` is out of bounds
10057 * @expose
10058 */
10059 ByteBufferPrototype.readUInt16 = ByteBufferPrototype.readUint16;
10060
10061 // types/ints/int32
10062
10063 /**
10064 * Writes a 32bit signed integer.
10065 * @param {number} value Value to write
10066 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
10067 * @expose
10068 */
10069 ByteBufferPrototype.writeInt32 = function(value, offset) {
10070 var relative = typeof offset === 'undefined';
10071 if (relative) offset = this.offset;
10072 if (!this.noAssert) {
10073 if (typeof value !== 'number' || value % 1 !== 0)
10074 throw TypeError("Illegal value: "+value+" (not an integer)");
10075 value |= 0;
10076 if (typeof offset !== 'number' || offset % 1 !== 0)
10077 throw TypeError("Illegal offset: "+offset+" (not an integer)");
10078 offset >>>= 0;
10079 if (offset < 0 || offset + 0 > this.buffer.byteLength)
10080 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
10081 }
10082 offset += 4;
10083 var capacity4 = this.buffer.byteLength;
10084 if (offset > capacity4)
10085 this.resize((capacity4 *= 2) > offset ? capacity4 : offset);
10086 offset -= 4;
10087 if (this.littleEndian) {
10088 this.view[offset+3] = (value >>> 24) & 0xFF;
10089 this.view[offset+2] = (value >>> 16) & 0xFF;
10090 this.view[offset+1] = (value >>> 8) & 0xFF;
10091 this.view[offset ] = value & 0xFF;
10092 } else {
10093 this.view[offset ] = (value >>> 24) & 0xFF;
10094 this.view[offset+1] = (value >>> 16) & 0xFF;
10095 this.view[offset+2] = (value >>> 8) & 0xFF;
10096 this.view[offset+3] = value & 0xFF;
10097 }
10098 if (relative) this.offset += 4;
10099 return this;
10100 };
10101
10102 /**
10103 * Writes a 32bit signed integer. This is an alias of {@link ByteBuffer#writeInt32}.
10104 * @param {number} value Value to write
10105 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
10106 * @expose
10107 */
10108 ByteBufferPrototype.writeInt = ByteBufferPrototype.writeInt32;
10109
10110 /**
10111 * Reads a 32bit signed integer.
10112 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
10113 * @returns {number} Value read
10114 * @expose
10115 */
10116 ByteBufferPrototype.readInt32 = function(offset) {
10117 var relative = typeof offset === 'undefined';
10118 if (relative) offset = this.offset;
10119 if (!this.noAssert) {
10120 if (typeof offset !== 'number' || offset % 1 !== 0)
10121 throw TypeError("Illegal offset: "+offset+" (not an integer)");
10122 offset >>>= 0;
10123 if (offset < 0 || offset + 4 > this.buffer.byteLength)
10124 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength);
10125 }
10126 var value = 0;
10127 if (this.littleEndian) {
10128 value = this.view[offset+2] << 16;
10129 value |= this.view[offset+1] << 8;
10130 value |= this.view[offset ];
10131 value += this.view[offset+3] << 24 >>> 0;
10132 } else {
10133 value = this.view[offset+1] << 16;
10134 value |= this.view[offset+2] << 8;
10135 value |= this.view[offset+3];
10136 value += this.view[offset ] << 24 >>> 0;
10137 }
10138 value |= 0; // Cast to signed
10139 if (relative) this.offset += 4;
10140 return value;
10141 };
10142
10143 /**
10144 * Reads a 32bit signed integer. This is an alias of {@link ByteBuffer#readInt32}.
10145 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `4` if omitted.
10146 * @returns {number} Value read
10147 * @expose
10148 */
10149 ByteBufferPrototype.readInt = ByteBufferPrototype.readInt32;
10150
10151 /**
10152 * Writes a 32bit unsigned integer.
10153 * @param {number} value Value to write
10154 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
10155 * @expose
10156 */
10157 ByteBufferPrototype.writeUint32 = function(value, offset) {
10158 var relative = typeof offset === 'undefined';
10159 if (relative) offset = this.offset;
10160 if (!this.noAssert) {
10161 if (typeof value !== 'number' || value % 1 !== 0)
10162 throw TypeError("Illegal value: "+value+" (not an integer)");
10163 value >>>= 0;
10164 if (typeof offset !== 'number' || offset % 1 !== 0)
10165 throw TypeError("Illegal offset: "+offset+" (not an integer)");
10166 offset >>>= 0;
10167 if (offset < 0 || offset + 0 > this.buffer.byteLength)
10168 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
10169 }
10170 offset += 4;
10171 var capacity5 = this.buffer.byteLength;
10172 if (offset > capacity5)
10173 this.resize((capacity5 *= 2) > offset ? capacity5 : offset);
10174 offset -= 4;
10175 if (this.littleEndian) {
10176 this.view[offset+3] = (value >>> 24) & 0xFF;
10177 this.view[offset+2] = (value >>> 16) & 0xFF;
10178 this.view[offset+1] = (value >>> 8) & 0xFF;
10179 this.view[offset ] = value & 0xFF;
10180 } else {
10181 this.view[offset ] = (value >>> 24) & 0xFF;
10182 this.view[offset+1] = (value >>> 16) & 0xFF;
10183 this.view[offset+2] = (value >>> 8) & 0xFF;
10184 this.view[offset+3] = value & 0xFF;
10185 }
10186 if (relative) this.offset += 4;
10187 return this;
10188 };
10189
10190 /**
10191 * Writes a 32bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint32}.
10192 * @function
10193 * @param {number} value Value to write
10194 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
10195 * @expose
10196 */
10197 ByteBufferPrototype.writeUInt32 = ByteBufferPrototype.writeUint32;
10198
10199 /**
10200 * Reads a 32bit unsigned integer.
10201 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
10202 * @returns {number} Value read
10203 * @expose
10204 */
10205 ByteBufferPrototype.readUint32 = function(offset) {
10206 var relative = typeof offset === 'undefined';
10207 if (relative) offset = this.offset;
10208 if (!this.noAssert) {
10209 if (typeof offset !== 'number' || offset % 1 !== 0)
10210 throw TypeError("Illegal offset: "+offset+" (not an integer)");
10211 offset >>>= 0;
10212 if (offset < 0 || offset + 4 > this.buffer.byteLength)
10213 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength);
10214 }
10215 var value = 0;
10216 if (this.littleEndian) {
10217 value = this.view[offset+2] << 16;
10218 value |= this.view[offset+1] << 8;
10219 value |= this.view[offset ];
10220 value += this.view[offset+3] << 24 >>> 0;
10221 } else {
10222 value = this.view[offset+1] << 16;
10223 value |= this.view[offset+2] << 8;
10224 value |= this.view[offset+3];
10225 value += this.view[offset ] << 24 >>> 0;
10226 }
10227 if (relative) this.offset += 4;
10228 return value;
10229 };
10230
10231 /**
10232 * Reads a 32bit unsigned integer. This is an alias of {@link ByteBuffer#readUint32}.
10233 * @function
10234 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
10235 * @returns {number} Value read
10236 * @expose
10237 */
10238 ByteBufferPrototype.readUInt32 = ByteBufferPrototype.readUint32;
10239
10240 // types/ints/int64
10241
10242 if (Long) {
10243
10244 /**
10245 * Writes a 64bit signed integer.
10246 * @param {number|!Long} value Value to write
10247 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
10248 * @returns {!ByteBuffer} this
10249 * @expose
10250 */
10251 ByteBufferPrototype.writeInt64 = function(value, offset) {
10252 var relative = typeof offset === 'undefined';
10253 if (relative) offset = this.offset;
10254 if (!this.noAssert) {
10255 if (typeof value === 'number')
10256 value = Long.fromNumber(value);
10257 else if (typeof value === 'string')
10258 value = Long.fromString(value);
10259 else if (!(value && value instanceof Long))
10260 throw TypeError("Illegal value: "+value+" (not an integer or Long)");
10261 if (typeof offset !== 'number' || offset % 1 !== 0)
10262 throw TypeError("Illegal offset: "+offset+" (not an integer)");
10263 offset >>>= 0;
10264 if (offset < 0 || offset + 0 > this.buffer.byteLength)
10265 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
10266 }
10267 if (typeof value === 'number')
10268 value = Long.fromNumber(value);
10269 else if (typeof value === 'string')
10270 value = Long.fromString(value);
10271 offset += 8;
10272 var capacity6 = this.buffer.byteLength;
10273 if (offset > capacity6)
10274 this.resize((capacity6 *= 2) > offset ? capacity6 : offset);
10275 offset -= 8;
10276 var lo = value.low,
10277 hi = value.high;
10278 if (this.littleEndian) {
10279 this.view[offset+3] = (lo >>> 24) & 0xFF;
10280 this.view[offset+2] = (lo >>> 16) & 0xFF;
10281 this.view[offset+1] = (lo >>> 8) & 0xFF;
10282 this.view[offset ] = lo & 0xFF;
10283 offset += 4;
10284 this.view[offset+3] = (hi >>> 24) & 0xFF;
10285 this.view[offset+2] = (hi >>> 16) & 0xFF;
10286 this.view[offset+1] = (hi >>> 8) & 0xFF;
10287 this.view[offset ] = hi & 0xFF;
10288 } else {
10289 this.view[offset ] = (hi >>> 24) & 0xFF;
10290 this.view[offset+1] = (hi >>> 16) & 0xFF;
10291 this.view[offset+2] = (hi >>> 8) & 0xFF;
10292 this.view[offset+3] = hi & 0xFF;
10293 offset += 4;
10294 this.view[offset ] = (lo >>> 24) & 0xFF;
10295 this.view[offset+1] = (lo >>> 16) & 0xFF;
10296 this.view[offset+2] = (lo >>> 8) & 0xFF;
10297 this.view[offset+3] = lo & 0xFF;
10298 }
10299 if (relative) this.offset += 8;
10300 return this;
10301 };
10302
10303 /**
10304 * Writes a 64bit signed integer. This is an alias of {@link ByteBuffer#writeInt64}.
10305 * @param {number|!Long} value Value to write
10306 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
10307 * @returns {!ByteBuffer} this
10308 * @expose
10309 */
10310 ByteBufferPrototype.writeLong = ByteBufferPrototype.writeInt64;
10311
10312 /**
10313 * Reads a 64bit signed integer.
10314 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
10315 * @returns {!Long}
10316 * @expose
10317 */
10318 ByteBufferPrototype.readInt64 = function(offset) {
10319 var relative = typeof offset === 'undefined';
10320 if (relative) offset = this.offset;
10321 if (!this.noAssert) {
10322 if (typeof offset !== 'number' || offset % 1 !== 0)
10323 throw TypeError("Illegal offset: "+offset+" (not an integer)");
10324 offset >>>= 0;
10325 if (offset < 0 || offset + 8 > this.buffer.byteLength)
10326 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+8+") <= "+this.buffer.byteLength);
10327 }
10328 var lo = 0,
10329 hi = 0;
10330 if (this.littleEndian) {
10331 lo = this.view[offset+2] << 16;
10332 lo |= this.view[offset+1] << 8;
10333 lo |= this.view[offset ];
10334 lo += this.view[offset+3] << 24 >>> 0;
10335 offset += 4;
10336 hi = this.view[offset+2] << 16;
10337 hi |= this.view[offset+1] << 8;
10338 hi |= this.view[offset ];
10339 hi += this.view[offset+3] << 24 >>> 0;
10340 } else {
10341 hi = this.view[offset+1] << 16;
10342 hi |= this.view[offset+2] << 8;
10343 hi |= this.view[offset+3];
10344 hi += this.view[offset ] << 24 >>> 0;
10345 offset += 4;
10346 lo = this.view[offset+1] << 16;
10347 lo |= this.view[offset+2] << 8;
10348 lo |= this.view[offset+3];
10349 lo += this.view[offset ] << 24 >>> 0;
10350 }
10351 var value = new Long(lo, hi, false);
10352 if (relative) this.offset += 8;
10353 return value;
10354 };
10355
10356 /**
10357 * Reads a 64bit signed integer. This is an alias of {@link ByteBuffer#readInt64}.
10358 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
10359 * @returns {!Long}
10360 * @expose
10361 */
10362 ByteBufferPrototype.readLong = ByteBufferPrototype.readInt64;
10363
10364 /**
10365 * Writes a 64bit unsigned integer.
10366 * @param {number|!Long} value Value to write
10367 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
10368 * @returns {!ByteBuffer} this
10369 * @expose
10370 */
10371 ByteBufferPrototype.writeUint64 = function(value, offset) {
10372 var relative = typeof offset === 'undefined';
10373 if (relative) offset = this.offset;
10374 if (!this.noAssert) {
10375 if (typeof value === 'number')
10376 value = Long.fromNumber(value);
10377 else if (typeof value === 'string')
10378 value = Long.fromString(value);
10379 else if (!(value && value instanceof Long))
10380 throw TypeError("Illegal value: "+value+" (not an integer or Long)");
10381 if (typeof offset !== 'number' || offset % 1 !== 0)
10382 throw TypeError("Illegal offset: "+offset+" (not an integer)");
10383 offset >>>= 0;
10384 if (offset < 0 || offset + 0 > this.buffer.byteLength)
10385 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
10386 }
10387 if (typeof value === 'number')
10388 value = Long.fromNumber(value);
10389 else if (typeof value === 'string')
10390 value = Long.fromString(value);
10391 offset += 8;
10392 var capacity7 = this.buffer.byteLength;
10393 if (offset > capacity7)
10394 this.resize((capacity7 *= 2) > offset ? capacity7 : offset);
10395 offset -= 8;
10396 var lo = value.low,
10397 hi = value.high;
10398 if (this.littleEndian) {
10399 this.view[offset+3] = (lo >>> 24) & 0xFF;
10400 this.view[offset+2] = (lo >>> 16) & 0xFF;
10401 this.view[offset+1] = (lo >>> 8) & 0xFF;
10402 this.view[offset ] = lo & 0xFF;
10403 offset += 4;
10404 this.view[offset+3] = (hi >>> 24) & 0xFF;
10405 this.view[offset+2] = (hi >>> 16) & 0xFF;
10406 this.view[offset+1] = (hi >>> 8) & 0xFF;
10407 this.view[offset ] = hi & 0xFF;
10408 } else {
10409 this.view[offset ] = (hi >>> 24) & 0xFF;
10410 this.view[offset+1] = (hi >>> 16) & 0xFF;
10411 this.view[offset+2] = (hi >>> 8) & 0xFF;
10412 this.view[offset+3] = hi & 0xFF;
10413 offset += 4;
10414 this.view[offset ] = (lo >>> 24) & 0xFF;
10415 this.view[offset+1] = (lo >>> 16) & 0xFF;
10416 this.view[offset+2] = (lo >>> 8) & 0xFF;
10417 this.view[offset+3] = lo & 0xFF;
10418 }
10419 if (relative) this.offset += 8;
10420 return this;
10421 };
10422
10423 /**
10424 * Writes a 64bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint64}.
10425 * @function
10426 * @param {number|!Long} value Value to write
10427 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
10428 * @returns {!ByteBuffer} this
10429 * @expose
10430 */
10431 ByteBufferPrototype.writeUInt64 = ByteBufferPrototype.writeUint64;
10432
10433 /**
10434 * Reads a 64bit unsigned integer.
10435 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
10436 * @returns {!Long}
10437 * @expose
10438 */
10439 ByteBufferPrototype.readUint64 = function(offset) {
10440 var relative = typeof offset === 'undefined';
10441 if (relative) offset = this.offset;
10442 if (!this.noAssert) {
10443 if (typeof offset !== 'number' || offset % 1 !== 0)
10444 throw TypeError("Illegal offset: "+offset+" (not an integer)");
10445 offset >>>= 0;
10446 if (offset < 0 || offset + 8 > this.buffer.byteLength)
10447 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+8+") <= "+this.buffer.byteLength);
10448 }
10449 var lo = 0,
10450 hi = 0;
10451 if (this.littleEndian) {
10452 lo = this.view[offset+2] << 16;
10453 lo |= this.view[offset+1] << 8;
10454 lo |= this.view[offset ];
10455 lo += this.view[offset+3] << 24 >>> 0;
10456 offset += 4;
10457 hi = this.view[offset+2] << 16;
10458 hi |= this.view[offset+1] << 8;
10459 hi |= this.view[offset ];
10460 hi += this.view[offset+3] << 24 >>> 0;
10461 } else {
10462 hi = this.view[offset+1] << 16;
10463 hi |= this.view[offset+2] << 8;
10464 hi |= this.view[offset+3];
10465 hi += this.view[offset ] << 24 >>> 0;
10466 offset += 4;
10467 lo = this.view[offset+1] << 16;
10468 lo |= this.view[offset+2] << 8;
10469 lo |= this.view[offset+3];
10470 lo += this.view[offset ] << 24 >>> 0;
10471 }
10472 var value = new Long(lo, hi, true);
10473 if (relative) this.offset += 8;
10474 return value;
10475 };
10476
10477 /**
10478 * Reads a 64bit unsigned integer. This is an alias of {@link ByteBuffer#readUint64}.
10479 * @function
10480 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
10481 * @returns {!Long}
10482 * @expose
10483 */
10484 ByteBufferPrototype.readUInt64 = ByteBufferPrototype.readUint64;
10485
10486 } // Long
10487
10488
10489 // types/floats/float32
10490
10491 /*
10492 ieee754 - https://github.com/feross/ieee754
10493
10494 The MIT License (MIT)
10495
10496 Copyright (c) Feross Aboukhadijeh
10497
10498 Permission is hereby granted, free of charge, to any person obtaining a copy
10499 of this software and associated documentation files (the "Software"), to deal
10500 in the Software without restriction, including without limitation the rights
10501 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10502 copies of the Software, and to permit persons to whom the Software is
10503 furnished to do so, subject to the following conditions:
10504
10505 The above copyright notice and this permission notice shall be included in
10506 all copies or substantial portions of the Software.
10507
10508 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
10509 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
10510 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
10511 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
10512 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
10513 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
10514 THE SOFTWARE.
10515 */
10516
10517 /**
10518 * Reads an IEEE754 float from a byte array.
10519 * @param {!Array} buffer
10520 * @param {number} offset
10521 * @param {boolean} isLE
10522 * @param {number} mLen
10523 * @param {number} nBytes
10524 * @returns {number}
10525 * @inner
10526 */
10527 function ieee754_read(buffer, offset, isLE, mLen, nBytes) {
10528 var e, m,
10529 eLen = nBytes * 8 - mLen - 1,
10530 eMax = (1 << eLen) - 1,
10531 eBias = eMax >> 1,
10532 nBits = -7,
10533 i = isLE ? (nBytes - 1) : 0,
10534 d = isLE ? -1 : 1,
10535 s = buffer[offset + i];
10536
10537 i += d;
10538
10539 e = s & ((1 << (-nBits)) - 1);
10540 s >>= (-nBits);
10541 nBits += eLen;
10542 for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
10543
10544 m = e & ((1 << (-nBits)) - 1);
10545 e >>= (-nBits);
10546 nBits += mLen;
10547 for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
10548
10549 if (e === 0) {
10550 e = 1 - eBias;
10551 } else if (e === eMax) {
10552 return m ? NaN : ((s ? -1 : 1) * Infinity);
10553 } else {
10554 m = m + Math.pow(2, mLen);
10555 e = e - eBias;
10556 }
10557 return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
10558 }
10559
10560 /**
10561 * Writes an IEEE754 float to a byte array.
10562 * @param {!Array} buffer
10563 * @param {number} value
10564 * @param {number} offset
10565 * @param {boolean} isLE
10566 * @param {number} mLen
10567 * @param {number} nBytes
10568 * @inner
10569 */
10570 function ieee754_write(buffer, value, offset, isLE, mLen, nBytes) {
10571 var e, m, c,
10572 eLen = nBytes * 8 - mLen - 1,
10573 eMax = (1 << eLen) - 1,
10574 eBias = eMax >> 1,
10575 rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0),
10576 i = isLE ? 0 : (nBytes - 1),
10577 d = isLE ? 1 : -1,
10578 s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
10579
10580 value = Math.abs(value);
10581
10582 if (isNaN(value) || value === Infinity) {
10583 m = isNaN(value) ? 1 : 0;
10584 e = eMax;
10585 } else {
10586 e = Math.floor(Math.log(value) / Math.LN2);
10587 if (value * (c = Math.pow(2, -e)) < 1) {
10588 e--;
10589 c *= 2;
10590 }
10591 if (e + eBias >= 1) {
10592 value += rt / c;
10593 } else {
10594 value += rt * Math.pow(2, 1 - eBias);
10595 }
10596 if (value * c >= 2) {
10597 e++;
10598 c /= 2;
10599 }
10600
10601 if (e + eBias >= eMax) {
10602 m = 0;
10603 e = eMax;
10604 } else if (e + eBias >= 1) {
10605 m = (value * c - 1) * Math.pow(2, mLen);
10606 e = e + eBias;
10607 } else {
10608 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
10609 e = 0;
10610 }
10611 }
10612
10613 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
10614
10615 e = (e << mLen) | m;
10616 eLen += mLen;
10617 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
10618
10619 buffer[offset + i - d] |= s * 128;
10620 }
10621
10622 /**
10623 * Writes a 32bit float.
10624 * @param {number} value Value to write
10625 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
10626 * @returns {!ByteBuffer} this
10627 * @expose
10628 */
10629 ByteBufferPrototype.writeFloat32 = function(value, offset) {
10630 var relative = typeof offset === 'undefined';
10631 if (relative) offset = this.offset;
10632 if (!this.noAssert) {
10633 if (typeof value !== 'number')
10634 throw TypeError("Illegal value: "+value+" (not a number)");
10635 if (typeof offset !== 'number' || offset % 1 !== 0)
10636 throw TypeError("Illegal offset: "+offset+" (not an integer)");
10637 offset >>>= 0;
10638 if (offset < 0 || offset + 0 > this.buffer.byteLength)
10639 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
10640 }
10641 offset += 4;
10642 var capacity8 = this.buffer.byteLength;
10643 if (offset > capacity8)
10644 this.resize((capacity8 *= 2) > offset ? capacity8 : offset);
10645 offset -= 4;
10646 ieee754_write(this.view, value, offset, this.littleEndian, 23, 4);
10647 if (relative) this.offset += 4;
10648 return this;
10649 };
10650
10651 /**
10652 * Writes a 32bit float. This is an alias of {@link ByteBuffer#writeFloat32}.
10653 * @function
10654 * @param {number} value Value to write
10655 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
10656 * @returns {!ByteBuffer} this
10657 * @expose
10658 */
10659 ByteBufferPrototype.writeFloat = ByteBufferPrototype.writeFloat32;
10660
10661 /**
10662 * Reads a 32bit float.
10663 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
10664 * @returns {number}
10665 * @expose
10666 */
10667 ByteBufferPrototype.readFloat32 = function(offset) {
10668 var relative = typeof offset === 'undefined';
10669 if (relative) offset = this.offset;
10670 if (!this.noAssert) {
10671 if (typeof offset !== 'number' || offset % 1 !== 0)
10672 throw TypeError("Illegal offset: "+offset+" (not an integer)");
10673 offset >>>= 0;
10674 if (offset < 0 || offset + 4 > this.buffer.byteLength)
10675 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength);
10676 }
10677 var value = ieee754_read(this.view, offset, this.littleEndian, 23, 4);
10678 if (relative) this.offset += 4;
10679 return value;
10680 };
10681
10682 /**
10683 * Reads a 32bit float. This is an alias of {@link ByteBuffer#readFloat32}.
10684 * @function
10685 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
10686 * @returns {number}
10687 * @expose
10688 */
10689 ByteBufferPrototype.readFloat = ByteBufferPrototype.readFloat32;
10690
10691 // types/floats/float64
10692
10693 /**
10694 * Writes a 64bit float.
10695 * @param {number} value Value to write
10696 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
10697 * @returns {!ByteBuffer} this
10698 * @expose
10699 */
10700 ByteBufferPrototype.writeFloat64 = function(value, offset) {
10701 var relative = typeof offset === 'undefined';
10702 if (relative) offset = this.offset;
10703 if (!this.noAssert) {
10704 if (typeof value !== 'number')
10705 throw TypeError("Illegal value: "+value+" (not a number)");
10706 if (typeof offset !== 'number' || offset % 1 !== 0)
10707 throw TypeError("Illegal offset: "+offset+" (not an integer)");
10708 offset >>>= 0;
10709 if (offset < 0 || offset + 0 > this.buffer.byteLength)
10710 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
10711 }
10712 offset += 8;
10713 var capacity9 = this.buffer.byteLength;
10714 if (offset > capacity9)
10715 this.resize((capacity9 *= 2) > offset ? capacity9 : offset);
10716 offset -= 8;
10717 ieee754_write(this.view, value, offset, this.littleEndian, 52, 8);
10718 if (relative) this.offset += 8;
10719 return this;
10720 };
10721
10722 /**
10723 * Writes a 64bit float. This is an alias of {@link ByteBuffer#writeFloat64}.
10724 * @function
10725 * @param {number} value Value to write
10726 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
10727 * @returns {!ByteBuffer} this
10728 * @expose
10729 */
10730 ByteBufferPrototype.writeDouble = ByteBufferPrototype.writeFloat64;
10731
10732 /**
10733 * Reads a 64bit float.
10734 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
10735 * @returns {number}
10736 * @expose
10737 */
10738 ByteBufferPrototype.readFloat64 = function(offset) {
10739 var relative = typeof offset === 'undefined';
10740 if (relative) offset = this.offset;
10741 if (!this.noAssert) {
10742 if (typeof offset !== 'number' || offset % 1 !== 0)
10743 throw TypeError("Illegal offset: "+offset+" (not an integer)");
10744 offset >>>= 0;
10745 if (offset < 0 || offset + 8 > this.buffer.byteLength)
10746 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+8+") <= "+this.buffer.byteLength);
10747 }
10748 var value = ieee754_read(this.view, offset, this.littleEndian, 52, 8);
10749 if (relative) this.offset += 8;
10750 return value;
10751 };
10752
10753 /**
10754 * Reads a 64bit float. This is an alias of {@link ByteBuffer#readFloat64}.
10755 * @function
10756 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
10757 * @returns {number}
10758 * @expose
10759 */
10760 ByteBufferPrototype.readDouble = ByteBufferPrototype.readFloat64;
10761
10762
10763 // types/varints/varint32
10764
10765 /**
10766 * Maximum number of bytes required to store a 32bit base 128 variable-length integer.
10767 * @type {number}
10768 * @const
10769 * @expose
10770 */
10771 ByteBuffer.MAX_VARINT32_BYTES = 5;
10772
10773 /**
10774 * Calculates the actual number of bytes required to store a 32bit base 128 variable-length integer.
10775 * @param {number} value Value to encode
10776 * @returns {number} Number of bytes required. Capped to {@link ByteBuffer.MAX_VARINT32_BYTES}
10777 * @expose
10778 */
10779 ByteBuffer.calculateVarint32 = function(value) {
10780 // ref: src/google/protobuf/io/coded_stream.cc
10781 value = value >>> 0;
10782 if (value < 1 << 7 ) return 1;
10783 else if (value < 1 << 14) return 2;
10784 else if (value < 1 << 21) return 3;
10785 else if (value < 1 << 28) return 4;
10786 else return 5;
10787 };
10788
10789 /**
10790 * Zigzag encodes a signed 32bit integer so that it can be effectively used with varint encoding.
10791 * @param {number} n Signed 32bit integer
10792 * @returns {number} Unsigned zigzag encoded 32bit integer
10793 * @expose
10794 */
10795 ByteBuffer.zigZagEncode32 = function(n) {
10796 return (((n |= 0) << 1) ^ (n >> 31)) >>> 0; // ref: src/google/protobuf/wire_format_lite.h
10797 };
10798
10799 /**
10800 * Decodes a zigzag encoded signed 32bit integer.
10801 * @param {number} n Unsigned zigzag encoded 32bit integer
10802 * @returns {number} Signed 32bit integer
10803 * @expose
10804 */
10805 ByteBuffer.zigZagDecode32 = function(n) {
10806 return ((n >>> 1) ^ -(n & 1)) | 0; // // ref: src/google/protobuf/wire_format_lite.h
10807 };
10808
10809 /**
10810 * Writes a 32bit base 128 variable-length integer.
10811 * @param {number} value Value to write
10812 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
10813 * written if omitted.
10814 * @returns {!ByteBuffer|number} this if `offset` is omitted, else the actual number of bytes written
10815 * @expose
10816 */
10817 ByteBufferPrototype.writeVarint32 = function(value, offset) {
10818 var relative = typeof offset === 'undefined';
10819 if (relative) offset = this.offset;
10820 if (!this.noAssert) {
10821 if (typeof value !== 'number' || value % 1 !== 0)
10822 throw TypeError("Illegal value: "+value+" (not an integer)");
10823 value |= 0;
10824 if (typeof offset !== 'number' || offset % 1 !== 0)
10825 throw TypeError("Illegal offset: "+offset+" (not an integer)");
10826 offset >>>= 0;
10827 if (offset < 0 || offset + 0 > this.buffer.byteLength)
10828 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
10829 }
10830 var size = ByteBuffer.calculateVarint32(value),
10831 b;
10832 offset += size;
10833 var capacity10 = this.buffer.byteLength;
10834 if (offset > capacity10)
10835 this.resize((capacity10 *= 2) > offset ? capacity10 : offset);
10836 offset -= size;
10837 value >>>= 0;
10838 while (value >= 0x80) {
10839 b = (value & 0x7f) | 0x80;
10840 this.view[offset++] = b;
10841 value >>>= 7;
10842 }
10843 this.view[offset++] = value;
10844 if (relative) {
10845 this.offset = offset;
10846 return this;
10847 }
10848 return size;
10849 };
10850
10851 /**
10852 * Writes a zig-zag encoded (signed) 32bit base 128 variable-length integer.
10853 * @param {number} value Value to write
10854 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
10855 * written if omitted.
10856 * @returns {!ByteBuffer|number} this if `offset` is omitted, else the actual number of bytes written
10857 * @expose
10858 */
10859 ByteBufferPrototype.writeVarint32ZigZag = function(value, offset) {
10860 return this.writeVarint32(ByteBuffer.zigZagEncode32(value), offset);
10861 };
10862
10863 /**
10864 * Reads a 32bit base 128 variable-length integer.
10865 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
10866 * written if omitted.
10867 * @returns {number|!{value: number, length: number}} The value read if offset is omitted, else the value read
10868 * and the actual number of bytes read.
10869 * @throws {Error} If it's not a valid varint. Has a property `truncated = true` if there is not enough data available
10870 * to fully decode the varint.
10871 * @expose
10872 */
10873 ByteBufferPrototype.readVarint32 = function(offset) {
10874 var relative = typeof offset === 'undefined';
10875 if (relative) offset = this.offset;
10876 if (!this.noAssert) {
10877 if (typeof offset !== 'number' || offset % 1 !== 0)
10878 throw TypeError("Illegal offset: "+offset+" (not an integer)");
10879 offset >>>= 0;
10880 if (offset < 0 || offset + 1 > this.buffer.byteLength)
10881 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
10882 }
10883 var c = 0,
10884 value = 0 >>> 0,
10885 b;
10886 do {
10887 if (!this.noAssert && offset > this.limit) {
10888 var err = Error("Truncated");
10889 err['truncated'] = true;
10890 throw err;
10891 }
10892 b = this.view[offset++];
10893 if (c < 5)
10894 value |= (b & 0x7f) << (7*c);
10895 ++c;
10896 } while ((b & 0x80) !== 0);
10897 value |= 0;
10898 if (relative) {
10899 this.offset = offset;
10900 return value;
10901 }
10902 return {
10903 "value": value,
10904 "length": c
10905 };
10906 };
10907
10908 /**
10909 * Reads a zig-zag encoded (signed) 32bit base 128 variable-length integer.
10910 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
10911 * written if omitted.
10912 * @returns {number|!{value: number, length: number}} The value read if offset is omitted, else the value read
10913 * and the actual number of bytes read.
10914 * @throws {Error} If it's not a valid varint
10915 * @expose
10916 */
10917 ByteBufferPrototype.readVarint32ZigZag = function(offset) {
10918 var val = this.readVarint32(offset);
10919 if (typeof val === 'object')
10920 val["value"] = ByteBuffer.zigZagDecode32(val["value"]);
10921 else
10922 val = ByteBuffer.zigZagDecode32(val);
10923 return val;
10924 };
10925
10926 // types/varints/varint64
10927
10928 if (Long) {
10929
10930 /**
10931 * Maximum number of bytes required to store a 64bit base 128 variable-length integer.
10932 * @type {number}
10933 * @const
10934 * @expose
10935 */
10936 ByteBuffer.MAX_VARINT64_BYTES = 10;
10937
10938 /**
10939 * Calculates the actual number of bytes required to store a 64bit base 128 variable-length integer.
10940 * @param {number|!Long} value Value to encode
10941 * @returns {number} Number of bytes required. Capped to {@link ByteBuffer.MAX_VARINT64_BYTES}
10942 * @expose
10943 */
10944 ByteBuffer.calculateVarint64 = function(value) {
10945 if (typeof value === 'number')
10946 value = Long.fromNumber(value);
10947 else if (typeof value === 'string')
10948 value = Long.fromString(value);
10949 // ref: src/google/protobuf/io/coded_stream.cc
10950 var part0 = value.toInt() >>> 0,
10951 part1 = value.shiftRightUnsigned(28).toInt() >>> 0,
10952 part2 = value.shiftRightUnsigned(56).toInt() >>> 0;
10953 if (part2 == 0) {
10954 if (part1 == 0) {
10955 if (part0 < 1 << 14)
10956 return part0 < 1 << 7 ? 1 : 2;
10957 else
10958 return part0 < 1 << 21 ? 3 : 4;
10959 } else {
10960 if (part1 < 1 << 14)
10961 return part1 < 1 << 7 ? 5 : 6;
10962 else
10963 return part1 < 1 << 21 ? 7 : 8;
10964 }
10965 } else
10966 return part2 < 1 << 7 ? 9 : 10;
10967 };
10968
10969 /**
10970 * Zigzag encodes a signed 64bit integer so that it can be effectively used with varint encoding.
10971 * @param {number|!Long} value Signed long
10972 * @returns {!Long} Unsigned zigzag encoded long
10973 * @expose
10974 */
10975 ByteBuffer.zigZagEncode64 = function(value) {
10976 if (typeof value === 'number')
10977 value = Long.fromNumber(value, false);
10978 else if (typeof value === 'string')
10979 value = Long.fromString(value, false);
10980 else if (value.unsigned !== false) value = value.toSigned();
10981 // ref: src/google/protobuf/wire_format_lite.h
10982 return value.shiftLeft(1).xor(value.shiftRight(63)).toUnsigned();
10983 };
10984
10985 /**
10986 * Decodes a zigzag encoded signed 64bit integer.
10987 * @param {!Long|number} value Unsigned zigzag encoded long or JavaScript number
10988 * @returns {!Long} Signed long
10989 * @expose
10990 */
10991 ByteBuffer.zigZagDecode64 = function(value) {
10992 if (typeof value === 'number')
10993 value = Long.fromNumber(value, false);
10994 else if (typeof value === 'string')
10995 value = Long.fromString(value, false);
10996 else if (value.unsigned !== false) value = value.toSigned();
10997 // ref: src/google/protobuf/wire_format_lite.h
10998 return value.shiftRightUnsigned(1).xor(value.and(Long.ONE).toSigned().negate()).toSigned();
10999 };
11000
11001 /**
11002 * Writes a 64bit base 128 variable-length integer.
11003 * @param {number|Long} value Value to write
11004 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
11005 * written if omitted.
11006 * @returns {!ByteBuffer|number} `this` if offset is omitted, else the actual number of bytes written.
11007 * @expose
11008 */
11009 ByteBufferPrototype.writeVarint64 = function(value, offset) {
11010 var relative = typeof offset === 'undefined';
11011 if (relative) offset = this.offset;
11012 if (!this.noAssert) {
11013 if (typeof value === 'number')
11014 value = Long.fromNumber(value);
11015 else if (typeof value === 'string')
11016 value = Long.fromString(value);
11017 else if (!(value && value instanceof Long))
11018 throw TypeError("Illegal value: "+value+" (not an integer or Long)");
11019 if (typeof offset !== 'number' || offset % 1 !== 0)
11020 throw TypeError("Illegal offset: "+offset+" (not an integer)");
11021 offset >>>= 0;
11022 if (offset < 0 || offset + 0 > this.buffer.byteLength)
11023 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
11024 }
11025 if (typeof value === 'number')
11026 value = Long.fromNumber(value, false);
11027 else if (typeof value === 'string')
11028 value = Long.fromString(value, false);
11029 else if (value.unsigned !== false) value = value.toSigned();
11030 var size = ByteBuffer.calculateVarint64(value),
11031 part0 = value.toInt() >>> 0,
11032 part1 = value.shiftRightUnsigned(28).toInt() >>> 0,
11033 part2 = value.shiftRightUnsigned(56).toInt() >>> 0;
11034 offset += size;
11035 var capacity11 = this.buffer.byteLength;
11036 if (offset > capacity11)
11037 this.resize((capacity11 *= 2) > offset ? capacity11 : offset);
11038 offset -= size;
11039 switch (size) {
11040 case 10: this.view[offset+9] = (part2 >>> 7) & 0x01;
11041 case 9 : this.view[offset+8] = size !== 9 ? (part2 ) | 0x80 : (part2 ) & 0x7F;
11042 case 8 : this.view[offset+7] = size !== 8 ? (part1 >>> 21) | 0x80 : (part1 >>> 21) & 0x7F;
11043 case 7 : this.view[offset+6] = size !== 7 ? (part1 >>> 14) | 0x80 : (part1 >>> 14) & 0x7F;
11044 case 6 : this.view[offset+5] = size !== 6 ? (part1 >>> 7) | 0x80 : (part1 >>> 7) & 0x7F;
11045 case 5 : this.view[offset+4] = size !== 5 ? (part1 ) | 0x80 : (part1 ) & 0x7F;
11046 case 4 : this.view[offset+3] = size !== 4 ? (part0 >>> 21) | 0x80 : (part0 >>> 21) & 0x7F;
11047 case 3 : this.view[offset+2] = size !== 3 ? (part0 >>> 14) | 0x80 : (part0 >>> 14) & 0x7F;
11048 case 2 : this.view[offset+1] = size !== 2 ? (part0 >>> 7) | 0x80 : (part0 >>> 7) & 0x7F;
11049 case 1 : this.view[offset ] = size !== 1 ? (part0 ) | 0x80 : (part0 ) & 0x7F;
11050 }
11051 if (relative) {
11052 this.offset += size;
11053 return this;
11054 } else {
11055 return size;
11056 }
11057 };
11058
11059 /**
11060 * Writes a zig-zag encoded 64bit base 128 variable-length integer.
11061 * @param {number|Long} value Value to write
11062 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
11063 * written if omitted.
11064 * @returns {!ByteBuffer|number} `this` if offset is omitted, else the actual number of bytes written.
11065 * @expose
11066 */
11067 ByteBufferPrototype.writeVarint64ZigZag = function(value, offset) {
11068 return this.writeVarint64(ByteBuffer.zigZagEncode64(value), offset);
11069 };
11070
11071 /**
11072 * Reads a 64bit base 128 variable-length integer. Requires Long.js.
11073 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
11074 * read if omitted.
11075 * @returns {!Long|!{value: Long, length: number}} The value read if offset is omitted, else the value read and
11076 * the actual number of bytes read.
11077 * @throws {Error} If it's not a valid varint
11078 * @expose
11079 */
11080 ByteBufferPrototype.readVarint64 = function(offset) {
11081 var relative = typeof offset === 'undefined';
11082 if (relative) offset = this.offset;
11083 if (!this.noAssert) {
11084 if (typeof offset !== 'number' || offset % 1 !== 0)
11085 throw TypeError("Illegal offset: "+offset+" (not an integer)");
11086 offset >>>= 0;
11087 if (offset < 0 || offset + 1 > this.buffer.byteLength)
11088 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
11089 }
11090 // ref: src/google/protobuf/io/coded_stream.cc
11091 var start = offset,
11092 part0 = 0,
11093 part1 = 0,
11094 part2 = 0,
11095 b = 0;
11096 b = this.view[offset++]; part0 = (b & 0x7F) ; if ( b & 0x80 ) {
11097 b = this.view[offset++]; part0 |= (b & 0x7F) << 7; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
11098 b = this.view[offset++]; part0 |= (b & 0x7F) << 14; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
11099 b = this.view[offset++]; part0 |= (b & 0x7F) << 21; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
11100 b = this.view[offset++]; part1 = (b & 0x7F) ; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
11101 b = this.view[offset++]; part1 |= (b & 0x7F) << 7; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
11102 b = this.view[offset++]; part1 |= (b & 0x7F) << 14; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
11103 b = this.view[offset++]; part1 |= (b & 0x7F) << 21; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
11104 b = this.view[offset++]; part2 = (b & 0x7F) ; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
11105 b = this.view[offset++]; part2 |= (b & 0x7F) << 7; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
11106 throw Error("Buffer overrun"); }}}}}}}}}}
11107 var value = Long.fromBits(part0 | (part1 << 28), (part1 >>> 4) | (part2) << 24, false);
11108 if (relative) {
11109 this.offset = offset;
11110 return value;
11111 } else {
11112 return {
11113 'value': value,
11114 'length': offset-start
11115 };
11116 }
11117 };
11118
11119 /**
11120 * Reads a zig-zag encoded 64bit base 128 variable-length integer. Requires Long.js.
11121 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
11122 * read if omitted.
11123 * @returns {!Long|!{value: Long, length: number}} The value read if offset is omitted, else the value read and
11124 * the actual number of bytes read.
11125 * @throws {Error} If it's not a valid varint
11126 * @expose
11127 */
11128 ByteBufferPrototype.readVarint64ZigZag = function(offset) {
11129 var val = this.readVarint64(offset);
11130 if (val && val['value'] instanceof Long)
11131 val["value"] = ByteBuffer.zigZagDecode64(val["value"]);
11132 else
11133 val = ByteBuffer.zigZagDecode64(val);
11134 return val;
11135 };
11136
11137 } // Long
11138
11139
11140 // types/strings/cstring
11141
11142 /**
11143 * Writes a NULL-terminated UTF8 encoded string. For this to work the specified string must not contain any NULL
11144 * characters itself.
11145 * @param {string} str String to write
11146 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
11147 * contained in `str` + 1 if omitted.
11148 * @returns {!ByteBuffer|number} this if offset is omitted, else the actual number of bytes written
11149 * @expose
11150 */
11151 ByteBufferPrototype.writeCString = function(str, offset) {
11152 var relative = typeof offset === 'undefined';
11153 if (relative) offset = this.offset;
11154 var i,
11155 k = str.length;
11156 if (!this.noAssert) {
11157 if (typeof str !== 'string')
11158 throw TypeError("Illegal str: Not a string");
11159 for (i=0; i<k; ++i) {
11160 if (str.charCodeAt(i) === 0)
11161 throw RangeError("Illegal str: Contains NULL-characters");
11162 }
11163 if (typeof offset !== 'number' || offset % 1 !== 0)
11164 throw TypeError("Illegal offset: "+offset+" (not an integer)");
11165 offset >>>= 0;
11166 if (offset < 0 || offset + 0 > this.buffer.byteLength)
11167 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
11168 }
11169 // UTF8 strings do not contain zero bytes in between except for the zero character, so:
11170 k = utfx.calculateUTF16asUTF8(stringSource(str))[1];
11171 offset += k+1;
11172 var capacity12 = this.buffer.byteLength;
11173 if (offset > capacity12)
11174 this.resize((capacity12 *= 2) > offset ? capacity12 : offset);
11175 offset -= k+1;
11176 utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
11177 this.view[offset++] = b;
11178 }.bind(this));
11179 this.view[offset++] = 0;
11180 if (relative) {
11181 this.offset = offset;
11182 return this;
11183 }
11184 return k;
11185 };
11186
11187 /**
11188 * Reads a NULL-terminated UTF8 encoded string. For this to work the string read must not contain any NULL characters
11189 * itself.
11190 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
11191 * read if omitted.
11192 * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
11193 * read and the actual number of bytes read.
11194 * @expose
11195 */
11196 ByteBufferPrototype.readCString = function(offset) {
11197 var relative = typeof offset === 'undefined';
11198 if (relative) offset = this.offset;
11199 if (!this.noAssert) {
11200 if (typeof offset !== 'number' || offset % 1 !== 0)
11201 throw TypeError("Illegal offset: "+offset+" (not an integer)");
11202 offset >>>= 0;
11203 if (offset < 0 || offset + 1 > this.buffer.byteLength)
11204 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
11205 }
11206 var start = offset,
11207 temp;
11208 // UTF8 strings do not contain zero bytes in between except for the zero character itself, so:
11209 var sd, b = -1;
11210 utfx.decodeUTF8toUTF16(function() {
11211 if (b === 0) return null;
11212 if (offset >= this.limit)
11213 throw RangeError("Illegal range: Truncated data, "+offset+" < "+this.limit);
11214 b = this.view[offset++];
11215 return b === 0 ? null : b;
11216 }.bind(this), sd = stringDestination(), true);
11217 if (relative) {
11218 this.offset = offset;
11219 return sd();
11220 } else {
11221 return {
11222 "string": sd(),
11223 "length": offset - start
11224 };
11225 }
11226 };
11227
11228 // types/strings/istring
11229
11230 /**
11231 * Writes a length as uint32 prefixed UTF8 encoded string.
11232 * @param {string} str String to write
11233 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
11234 * written if omitted.
11235 * @returns {!ByteBuffer|number} `this` if `offset` is omitted, else the actual number of bytes written
11236 * @expose
11237 * @see ByteBuffer#writeVarint32
11238 */
11239 ByteBufferPrototype.writeIString = function(str, offset) {
11240 var relative = typeof offset === 'undefined';
11241 if (relative) offset = this.offset;
11242 if (!this.noAssert) {
11243 if (typeof str !== 'string')
11244 throw TypeError("Illegal str: Not a string");
11245 if (typeof offset !== 'number' || offset % 1 !== 0)
11246 throw TypeError("Illegal offset: "+offset+" (not an integer)");
11247 offset >>>= 0;
11248 if (offset < 0 || offset + 0 > this.buffer.byteLength)
11249 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
11250 }
11251 var start = offset,
11252 k;
11253 k = utfx.calculateUTF16asUTF8(stringSource(str), this.noAssert)[1];
11254 offset += 4+k;
11255 var capacity13 = this.buffer.byteLength;
11256 if (offset > capacity13)
11257 this.resize((capacity13 *= 2) > offset ? capacity13 : offset);
11258 offset -= 4+k;
11259 if (this.littleEndian) {
11260 this.view[offset+3] = (k >>> 24) & 0xFF;
11261 this.view[offset+2] = (k >>> 16) & 0xFF;
11262 this.view[offset+1] = (k >>> 8) & 0xFF;
11263 this.view[offset ] = k & 0xFF;
11264 } else {
11265 this.view[offset ] = (k >>> 24) & 0xFF;
11266 this.view[offset+1] = (k >>> 16) & 0xFF;
11267 this.view[offset+2] = (k >>> 8) & 0xFF;
11268 this.view[offset+3] = k & 0xFF;
11269 }
11270 offset += 4;
11271 utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
11272 this.view[offset++] = b;
11273 }.bind(this));
11274 if (offset !== start + 4 + k)
11275 throw RangeError("Illegal range: Truncated data, "+offset+" == "+(offset+4+k));
11276 if (relative) {
11277 this.offset = offset;
11278 return this;
11279 }
11280 return offset - start;
11281 };
11282
11283 /**
11284 * Reads a length as uint32 prefixed UTF8 encoded string.
11285 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
11286 * read if omitted.
11287 * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
11288 * read and the actual number of bytes read.
11289 * @expose
11290 * @see ByteBuffer#readVarint32
11291 */
11292 ByteBufferPrototype.readIString = function(offset) {
11293 var relative = typeof offset === 'undefined';
11294 if (relative) offset = this.offset;
11295 if (!this.noAssert) {
11296 if (typeof offset !== 'number' || offset % 1 !== 0)
11297 throw TypeError("Illegal offset: "+offset+" (not an integer)");
11298 offset >>>= 0;
11299 if (offset < 0 || offset + 4 > this.buffer.byteLength)
11300 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength);
11301 }
11302 var start = offset;
11303 var len = this.readUint32(offset);
11304 var str = this.readUTF8String(len, ByteBuffer.METRICS_BYTES, offset += 4);
11305 offset += str['length'];
11306 if (relative) {
11307 this.offset = offset;
11308 return str['string'];
11309 } else {
11310 return {
11311 'string': str['string'],
11312 'length': offset - start
11313 };
11314 }
11315 };
11316
11317 // types/strings/utf8string
11318
11319 /**
11320 * Metrics representing number of UTF8 characters. Evaluates to `c`.
11321 * @type {string}
11322 * @const
11323 * @expose
11324 */
11325 ByteBuffer.METRICS_CHARS = 'c';
11326
11327 /**
11328 * Metrics representing number of bytes. Evaluates to `b`.
11329 * @type {string}
11330 * @const
11331 * @expose
11332 */
11333 ByteBuffer.METRICS_BYTES = 'b';
11334
11335 /**
11336 * Writes an UTF8 encoded string.
11337 * @param {string} str String to write
11338 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} if omitted.
11339 * @returns {!ByteBuffer|number} this if offset is omitted, else the actual number of bytes written.
11340 * @expose
11341 */
11342 ByteBufferPrototype.writeUTF8String = function(str, offset) {
11343 var relative = typeof offset === 'undefined';
11344 if (relative) offset = this.offset;
11345 if (!this.noAssert) {
11346 if (typeof offset !== 'number' || offset % 1 !== 0)
11347 throw TypeError("Illegal offset: "+offset+" (not an integer)");
11348 offset >>>= 0;
11349 if (offset < 0 || offset + 0 > this.buffer.byteLength)
11350 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
11351 }
11352 var k;
11353 var start = offset;
11354 k = utfx.calculateUTF16asUTF8(stringSource(str))[1];
11355 offset += k;
11356 var capacity14 = this.buffer.byteLength;
11357 if (offset > capacity14)
11358 this.resize((capacity14 *= 2) > offset ? capacity14 : offset);
11359 offset -= k;
11360 utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
11361 this.view[offset++] = b;
11362 }.bind(this));
11363 if (relative) {
11364 this.offset = offset;
11365 return this;
11366 }
11367 return offset - start;
11368 };
11369
11370 /**
11371 * Writes an UTF8 encoded string. This is an alias of {@link ByteBuffer#writeUTF8String}.
11372 * @function
11373 * @param {string} str String to write
11374 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} if omitted.
11375 * @returns {!ByteBuffer|number} this if offset is omitted, else the actual number of bytes written.
11376 * @expose
11377 */
11378 ByteBufferPrototype.writeString = ByteBufferPrototype.writeUTF8String;
11379
11380 /**
11381 * Calculates the number of UTF8 characters of a string. JavaScript itself uses UTF-16, so that a string's
11382 * `length` property does not reflect its actual UTF8 size if it contains code points larger than 0xFFFF.
11383 * @param {string} str String to calculate
11384 * @returns {number} Number of UTF8 characters
11385 * @expose
11386 */
11387 ByteBuffer.calculateUTF8Chars = function(str) {
11388 return utfx.calculateUTF16asUTF8(stringSource(str))[0];
11389 };
11390
11391 /**
11392 * Calculates the number of UTF8 bytes of a string.
11393 * @param {string} str String to calculate
11394 * @returns {number} Number of UTF8 bytes
11395 * @expose
11396 */
11397 ByteBuffer.calculateUTF8Bytes = function(str) {
11398 return utfx.calculateUTF16asUTF8(stringSource(str))[1];
11399 };
11400
11401 /**
11402 * Calculates the number of UTF8 bytes of a string. This is an alias of {@link ByteBuffer.calculateUTF8Bytes}.
11403 * @function
11404 * @param {string} str String to calculate
11405 * @returns {number} Number of UTF8 bytes
11406 * @expose
11407 */
11408 ByteBuffer.calculateString = ByteBuffer.calculateUTF8Bytes;
11409
11410 /**
11411 * Reads an UTF8 encoded string.
11412 * @param {number} length Number of characters or bytes to read.
11413 * @param {string=} metrics Metrics specifying what `length` is meant to count. Defaults to
11414 * {@link ByteBuffer.METRICS_CHARS}.
11415 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
11416 * read if omitted.
11417 * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
11418 * read and the actual number of bytes read.
11419 * @expose
11420 */
11421 ByteBufferPrototype.readUTF8String = function(length, metrics, offset) {
11422 if (typeof metrics === 'number') {
11423 offset = metrics;
11424 metrics = undefined;
11425 }
11426 var relative = typeof offset === 'undefined';
11427 if (relative) offset = this.offset;
11428 if (typeof metrics === 'undefined') metrics = ByteBuffer.METRICS_CHARS;
11429 if (!this.noAssert) {
11430 if (typeof length !== 'number' || length % 1 !== 0)
11431 throw TypeError("Illegal length: "+length+" (not an integer)");
11432 length |= 0;
11433 if (typeof offset !== 'number' || offset % 1 !== 0)
11434 throw TypeError("Illegal offset: "+offset+" (not an integer)");
11435 offset >>>= 0;
11436 if (offset < 0 || offset + 0 > this.buffer.byteLength)
11437 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
11438 }
11439 var i = 0,
11440 start = offset,
11441 sd;
11442 if (metrics === ByteBuffer.METRICS_CHARS) { // The same for node and the browser
11443 sd = stringDestination();
11444 utfx.decodeUTF8(function() {
11445 return i < length && offset < this.limit ? this.view[offset++] : null;
11446 }.bind(this), function(cp) {
11447 ++i; utfx.UTF8toUTF16(cp, sd);
11448 });
11449 if (i !== length)
11450 throw RangeError("Illegal range: Truncated data, "+i+" == "+length);
11451 if (relative) {
11452 this.offset = offset;
11453 return sd();
11454 } else {
11455 return {
11456 "string": sd(),
11457 "length": offset - start
11458 };
11459 }
11460 } else if (metrics === ByteBuffer.METRICS_BYTES) {
11461 if (!this.noAssert) {
11462 if (typeof offset !== 'number' || offset % 1 !== 0)
11463 throw TypeError("Illegal offset: "+offset+" (not an integer)");
11464 offset >>>= 0;
11465 if (offset < 0 || offset + length > this.buffer.byteLength)
11466 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+length+") <= "+this.buffer.byteLength);
11467 }
11468 var k = offset + length;
11469 utfx.decodeUTF8toUTF16(function() {
11470 return offset < k ? this.view[offset++] : null;
11471 }.bind(this), sd = stringDestination(), this.noAssert);
11472 if (offset !== k)
11473 throw RangeError("Illegal range: Truncated data, "+offset+" == "+k);
11474 if (relative) {
11475 this.offset = offset;
11476 return sd();
11477 } else {
11478 return {
11479 'string': sd(),
11480 'length': offset - start
11481 };
11482 }
11483 } else
11484 throw TypeError("Unsupported metrics: "+metrics);
11485 };
11486
11487 /**
11488 * Reads an UTF8 encoded string. This is an alias of {@link ByteBuffer#readUTF8String}.
11489 * @function
11490 * @param {number} length Number of characters or bytes to read
11491 * @param {number=} metrics Metrics specifying what `n` is meant to count. Defaults to
11492 * {@link ByteBuffer.METRICS_CHARS}.
11493 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
11494 * read if omitted.
11495 * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
11496 * read and the actual number of bytes read.
11497 * @expose
11498 */
11499 ByteBufferPrototype.readString = ByteBufferPrototype.readUTF8String;
11500
11501 // types/strings/vstring
11502
11503 /**
11504 * Writes a length as varint32 prefixed UTF8 encoded string.
11505 * @param {string} str String to write
11506 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
11507 * written if omitted.
11508 * @returns {!ByteBuffer|number} `this` if `offset` is omitted, else the actual number of bytes written
11509 * @expose
11510 * @see ByteBuffer#writeVarint32
11511 */
11512 ByteBufferPrototype.writeVString = function(str, offset) {
11513 var relative = typeof offset === 'undefined';
11514 if (relative) offset = this.offset;
11515 if (!this.noAssert) {
11516 if (typeof str !== 'string')
11517 throw TypeError("Illegal str: Not a string");
11518 if (typeof offset !== 'number' || offset % 1 !== 0)
11519 throw TypeError("Illegal offset: "+offset+" (not an integer)");
11520 offset >>>= 0;
11521 if (offset < 0 || offset + 0 > this.buffer.byteLength)
11522 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
11523 }
11524 var start = offset,
11525 k, l;
11526 k = utfx.calculateUTF16asUTF8(stringSource(str), this.noAssert)[1];
11527 l = ByteBuffer.calculateVarint32(k);
11528 offset += l+k;
11529 var capacity15 = this.buffer.byteLength;
11530 if (offset > capacity15)
11531 this.resize((capacity15 *= 2) > offset ? capacity15 : offset);
11532 offset -= l+k;
11533 offset += this.writeVarint32(k, offset);
11534 utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
11535 this.view[offset++] = b;
11536 }.bind(this));
11537 if (offset !== start+k+l)
11538 throw RangeError("Illegal range: Truncated data, "+offset+" == "+(offset+k+l));
11539 if (relative) {
11540 this.offset = offset;
11541 return this;
11542 }
11543 return offset - start;
11544 };
11545
11546 /**
11547 * Reads a length as varint32 prefixed UTF8 encoded string.
11548 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
11549 * read if omitted.
11550 * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
11551 * read and the actual number of bytes read.
11552 * @expose
11553 * @see ByteBuffer#readVarint32
11554 */
11555 ByteBufferPrototype.readVString = function(offset) {
11556 var relative = typeof offset === 'undefined';
11557 if (relative) offset = this.offset;
11558 if (!this.noAssert) {
11559 if (typeof offset !== 'number' || offset % 1 !== 0)
11560 throw TypeError("Illegal offset: "+offset+" (not an integer)");
11561 offset >>>= 0;
11562 if (offset < 0 || offset + 1 > this.buffer.byteLength)
11563 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
11564 }
11565 var start = offset;
11566 var len = this.readVarint32(offset);
11567 var str = this.readUTF8String(len['value'], ByteBuffer.METRICS_BYTES, offset += len['length']);
11568 offset += str['length'];
11569 if (relative) {
11570 this.offset = offset;
11571 return str['string'];
11572 } else {
11573 return {
11574 'string': str['string'],
11575 'length': offset - start
11576 };
11577 }
11578 };
11579
11580
11581 /**
11582 * Appends some data to this ByteBuffer. This will overwrite any contents behind the specified offset up to the appended
11583 * data's length.
11584 * @param {!ByteBuffer|!ArrayBuffer|!Uint8Array|string} source Data to append. If `source` is a ByteBuffer, its offsets
11585 * will be modified according to the performed read operation.
11586 * @param {(string|number)=} encoding Encoding if `data` is a string ("base64", "hex", "binary", defaults to "utf8")
11587 * @param {number=} offset Offset to append at. Will use and increase {@link ByteBuffer#offset} by the number of bytes
11588 * written if omitted.
11589 * @returns {!ByteBuffer} this
11590 * @expose
11591 * @example A relative `<01 02>03.append(<04 05>)` will result in `<01 02 04 05>, 04 05|`
11592 * @example An absolute `<01 02>03.append(04 05>, 1)` will result in `<01 04>05, 04 05|`
11593 */
11594 ByteBufferPrototype.append = function(source, encoding, offset) {
11595 if (typeof encoding === 'number' || typeof encoding !== 'string') {
11596 offset = encoding;
11597 encoding = undefined;
11598 }
11599 var relative = typeof offset === 'undefined';
11600 if (relative) offset = this.offset;
11601 if (!this.noAssert) {
11602 if (typeof offset !== 'number' || offset % 1 !== 0)
11603 throw TypeError("Illegal offset: "+offset+" (not an integer)");
11604 offset >>>= 0;
11605 if (offset < 0 || offset + 0 > this.buffer.byteLength)
11606 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
11607 }
11608 if (!(source instanceof ByteBuffer))
11609 source = ByteBuffer.wrap(source, encoding);
11610 var length = source.limit - source.offset;
11611 if (length <= 0) return this; // Nothing to append
11612 offset += length;
11613 var capacity16 = this.buffer.byteLength;
11614 if (offset > capacity16)
11615 this.resize((capacity16 *= 2) > offset ? capacity16 : offset);
11616 offset -= length;
11617 this.view.set(source.view.subarray(source.offset, source.limit), offset);
11618 source.offset += length;
11619 if (relative) this.offset += length;
11620 return this;
11621 };
11622
11623 /**
11624 * Appends this ByteBuffer's contents to another ByteBuffer. This will overwrite any contents at and after the
11625 specified offset up to the length of this ByteBuffer's data.
11626 * @param {!ByteBuffer} target Target ByteBuffer
11627 * @param {number=} offset Offset to append to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
11628 * read if omitted.
11629 * @returns {!ByteBuffer} this
11630 * @expose
11631 * @see ByteBuffer#append
11632 */
11633 ByteBufferPrototype.appendTo = function(target, offset) {
11634 target.append(this, offset);
11635 return this;
11636 };
11637
11638 /**
11639 * Enables or disables assertions of argument types and offsets. Assertions are enabled by default but you can opt to
11640 * disable them if your code already makes sure that everything is valid.
11641 * @param {boolean} assert `true` to enable assertions, otherwise `false`
11642 * @returns {!ByteBuffer} this
11643 * @expose
11644 */
11645 ByteBufferPrototype.assert = function(assert) {
11646 this.noAssert = !assert;
11647 return this;
11648 };
11649
11650 /**
11651 * Gets the capacity of this ByteBuffer's backing buffer.
11652 * @returns {number} Capacity of the backing buffer
11653 * @expose
11654 */
11655 ByteBufferPrototype.capacity = function() {
11656 return this.buffer.byteLength;
11657 };
11658 /**
11659 * Clears this ByteBuffer's offsets by setting {@link ByteBuffer#offset} to `0` and {@link ByteBuffer#limit} to the
11660 * backing buffer's capacity. Discards {@link ByteBuffer#markedOffset}.
11661 * @returns {!ByteBuffer} this
11662 * @expose
11663 */
11664 ByteBufferPrototype.clear = function() {
11665 this.offset = 0;
11666 this.limit = this.buffer.byteLength;
11667 this.markedOffset = -1;
11668 return this;
11669 };
11670
11671 /**
11672 * Creates a cloned instance of this ByteBuffer, preset with this ByteBuffer's values for {@link ByteBuffer#offset},
11673 * {@link ByteBuffer#markedOffset} and {@link ByteBuffer#limit}.
11674 * @param {boolean=} copy Whether to copy the backing buffer or to return another view on the same, defaults to `false`
11675 * @returns {!ByteBuffer} Cloned instance
11676 * @expose
11677 */
11678 ByteBufferPrototype.clone = function(copy) {
11679 var bb = new ByteBuffer(0, this.littleEndian, this.noAssert);
11680 if (copy) {
11681 bb.buffer = new ArrayBuffer(this.buffer.byteLength);
11682 bb.view = new Uint8Array(bb.buffer);
11683 } else {
11684 bb.buffer = this.buffer;
11685 bb.view = this.view;
11686 }
11687 bb.offset = this.offset;
11688 bb.markedOffset = this.markedOffset;
11689 bb.limit = this.limit;
11690 return bb;
11691 };
11692
11693 /**
11694 * Compacts this ByteBuffer to be backed by a {@link ByteBuffer#buffer} of its contents' length. Contents are the bytes
11695 * between {@link ByteBuffer#offset} and {@link ByteBuffer#limit}. Will set `offset = 0` and `limit = capacity` and
11696 * adapt {@link ByteBuffer#markedOffset} to the same relative position if set.
11697 * @param {number=} begin Offset to start at, defaults to {@link ByteBuffer#offset}
11698 * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}
11699 * @returns {!ByteBuffer} this
11700 * @expose
11701 */
11702 ByteBufferPrototype.compact = function(begin, end) {
11703 if (typeof begin === 'undefined') begin = this.offset;
11704 if (typeof end === 'undefined') end = this.limit;
11705 if (!this.noAssert) {
11706 if (typeof begin !== 'number' || begin % 1 !== 0)
11707 throw TypeError("Illegal begin: Not an integer");
11708 begin >>>= 0;
11709 if (typeof end !== 'number' || end % 1 !== 0)
11710 throw TypeError("Illegal end: Not an integer");
11711 end >>>= 0;
11712 if (begin < 0 || begin > end || end > this.buffer.byteLength)
11713 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
11714 }
11715 if (begin === 0 && end === this.buffer.byteLength)
11716 return this; // Already compacted
11717 var len = end - begin;
11718 if (len === 0) {
11719 this.buffer = EMPTY_BUFFER;
11720 this.view = null;
11721 if (this.markedOffset >= 0) this.markedOffset -= begin;
11722 this.offset = 0;
11723 this.limit = 0;
11724 return this;
11725 }
11726 var buffer = new ArrayBuffer(len);
11727 var view = new Uint8Array(buffer);
11728 view.set(this.view.subarray(begin, end));
11729 this.buffer = buffer;
11730 this.view = view;
11731 if (this.markedOffset >= 0) this.markedOffset -= begin;
11732 this.offset = 0;
11733 this.limit = len;
11734 return this;
11735 };
11736
11737 /**
11738 * Creates a copy of this ByteBuffer's contents. Contents are the bytes between {@link ByteBuffer#offset} and
11739 * {@link ByteBuffer#limit}.
11740 * @param {number=} begin Begin offset, defaults to {@link ByteBuffer#offset}.
11741 * @param {number=} end End offset, defaults to {@link ByteBuffer#limit}.
11742 * @returns {!ByteBuffer} Copy
11743 * @expose
11744 */
11745 ByteBufferPrototype.copy = function(begin, end) {
11746 if (typeof begin === 'undefined') begin = this.offset;
11747 if (typeof end === 'undefined') end = this.limit;
11748 if (!this.noAssert) {
11749 if (typeof begin !== 'number' || begin % 1 !== 0)
11750 throw TypeError("Illegal begin: Not an integer");
11751 begin >>>= 0;
11752 if (typeof end !== 'number' || end % 1 !== 0)
11753 throw TypeError("Illegal end: Not an integer");
11754 end >>>= 0;
11755 if (begin < 0 || begin > end || end > this.buffer.byteLength)
11756 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
11757 }
11758 if (begin === end)
11759 return new ByteBuffer(0, this.littleEndian, this.noAssert);
11760 var capacity = end - begin,
11761 bb = new ByteBuffer(capacity, this.littleEndian, this.noAssert);
11762 bb.offset = 0;
11763 bb.limit = capacity;
11764 if (bb.markedOffset >= 0) bb.markedOffset -= begin;
11765 this.copyTo(bb, 0, begin, end);
11766 return bb;
11767 };
11768
11769 /**
11770 * Copies this ByteBuffer's contents to another ByteBuffer. Contents are the bytes between {@link ByteBuffer#offset} and
11771 * {@link ByteBuffer#limit}.
11772 * @param {!ByteBuffer} target Target ByteBuffer
11773 * @param {number=} targetOffset Offset to copy to. Will use and increase the target's {@link ByteBuffer#offset}
11774 * by the number of bytes copied if omitted.
11775 * @param {number=} sourceOffset Offset to start copying from. Will use and increase {@link ByteBuffer#offset} by the
11776 * number of bytes copied if omitted.
11777 * @param {number=} sourceLimit Offset to end copying from, defaults to {@link ByteBuffer#limit}
11778 * @returns {!ByteBuffer} this
11779 * @expose
11780 */
11781 ByteBufferPrototype.copyTo = function(target, targetOffset, sourceOffset, sourceLimit) {
11782 var relative,
11783 targetRelative;
11784 if (!this.noAssert) {
11785 if (!ByteBuffer.isByteBuffer(target))
11786 throw TypeError("Illegal target: Not a ByteBuffer");
11787 }
11788 targetOffset = (targetRelative = typeof targetOffset === 'undefined') ? target.offset : targetOffset | 0;
11789 sourceOffset = (relative = typeof sourceOffset === 'undefined') ? this.offset : sourceOffset | 0;
11790 sourceLimit = typeof sourceLimit === 'undefined' ? this.limit : sourceLimit | 0;
11791
11792 if (targetOffset < 0 || targetOffset > target.buffer.byteLength)
11793 throw RangeError("Illegal target range: 0 <= "+targetOffset+" <= "+target.buffer.byteLength);
11794 if (sourceOffset < 0 || sourceLimit > this.buffer.byteLength)
11795 throw RangeError("Illegal source range: 0 <= "+sourceOffset+" <= "+this.buffer.byteLength);
11796
11797 var len = sourceLimit - sourceOffset;
11798 if (len === 0)
11799 return target; // Nothing to copy
11800
11801 target.ensureCapacity(targetOffset + len);
11802
11803 target.view.set(this.view.subarray(sourceOffset, sourceLimit), targetOffset);
11804
11805 if (relative) this.offset += len;
11806 if (targetRelative) target.offset += len;
11807
11808 return this;
11809 };
11810
11811 /**
11812 * Makes sure that this ByteBuffer is backed by a {@link ByteBuffer#buffer} of at least the specified capacity. If the
11813 * current capacity is exceeded, it will be doubled. If double the current capacity is less than the required capacity,
11814 * the required capacity will be used instead.
11815 * @param {number} capacity Required capacity
11816 * @returns {!ByteBuffer} this
11817 * @expose
11818 */
11819 ByteBufferPrototype.ensureCapacity = function(capacity) {
11820 var current = this.buffer.byteLength;
11821 if (current < capacity)
11822 return this.resize((current *= 2) > capacity ? current : capacity);
11823 return this;
11824 };
11825
11826 /**
11827 * Overwrites this ByteBuffer's contents with the specified value. Contents are the bytes between
11828 * {@link ByteBuffer#offset} and {@link ByteBuffer#limit}.
11829 * @param {number|string} value Byte value to fill with. If given as a string, the first character is used.
11830 * @param {number=} begin Begin offset. Will use and increase {@link ByteBuffer#offset} by the number of bytes
11831 * written if omitted. defaults to {@link ByteBuffer#offset}.
11832 * @param {number=} end End offset, defaults to {@link ByteBuffer#limit}.
11833 * @returns {!ByteBuffer} this
11834 * @expose
11835 * @example `someByteBuffer.clear().fill(0)` fills the entire backing buffer with zeroes
11836 */
11837 ByteBufferPrototype.fill = function(value, begin, end) {
11838 var relative = typeof begin === 'undefined';
11839 if (relative) begin = this.offset;
11840 if (typeof value === 'string' && value.length > 0)
11841 value = value.charCodeAt(0);
11842 if (typeof begin === 'undefined') begin = this.offset;
11843 if (typeof end === 'undefined') end = this.limit;
11844 if (!this.noAssert) {
11845 if (typeof value !== 'number' || value % 1 !== 0)
11846 throw TypeError("Illegal value: "+value+" (not an integer)");
11847 value |= 0;
11848 if (typeof begin !== 'number' || begin % 1 !== 0)
11849 throw TypeError("Illegal begin: Not an integer");
11850 begin >>>= 0;
11851 if (typeof end !== 'number' || end % 1 !== 0)
11852 throw TypeError("Illegal end: Not an integer");
11853 end >>>= 0;
11854 if (begin < 0 || begin > end || end > this.buffer.byteLength)
11855 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
11856 }
11857 if (begin >= end)
11858 return this; // Nothing to fill
11859 while (begin < end) this.view[begin++] = value;
11860 if (relative) this.offset = begin;
11861 return this;
11862 };
11863
11864 /**
11865 * Makes this ByteBuffer ready for a new sequence of write or relative read operations. Sets `limit = offset` and
11866 * `offset = 0`. Make sure always to flip a ByteBuffer when all relative read or write operations are complete.
11867 * @returns {!ByteBuffer} this
11868 * @expose
11869 */
11870 ByteBufferPrototype.flip = function() {
11871 this.limit = this.offset;
11872 this.offset = 0;
11873 return this;
11874 };
11875 /**
11876 * Marks an offset on this ByteBuffer to be used later.
11877 * @param {number=} offset Offset to mark. Defaults to {@link ByteBuffer#offset}.
11878 * @returns {!ByteBuffer} this
11879 * @throws {TypeError} If `offset` is not a valid number
11880 * @throws {RangeError} If `offset` is out of bounds
11881 * @see ByteBuffer#reset
11882 * @expose
11883 */
11884 ByteBufferPrototype.mark = function(offset) {
11885 offset = typeof offset === 'undefined' ? this.offset : offset;
11886 if (!this.noAssert) {
11887 if (typeof offset !== 'number' || offset % 1 !== 0)
11888 throw TypeError("Illegal offset: "+offset+" (not an integer)");
11889 offset >>>= 0;
11890 if (offset < 0 || offset + 0 > this.buffer.byteLength)
11891 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
11892 }
11893 this.markedOffset = offset;
11894 return this;
11895 };
11896 /**
11897 * Sets the byte order.
11898 * @param {boolean} littleEndian `true` for little endian byte order, `false` for big endian
11899 * @returns {!ByteBuffer} this
11900 * @expose
11901 */
11902 ByteBufferPrototype.order = function(littleEndian) {
11903 if (!this.noAssert) {
11904 if (typeof littleEndian !== 'boolean')
11905 throw TypeError("Illegal littleEndian: Not a boolean");
11906 }
11907 this.littleEndian = !!littleEndian;
11908 return this;
11909 };
11910
11911 /**
11912 * Switches (to) little endian byte order.
11913 * @param {boolean=} littleEndian Defaults to `true`, otherwise uses big endian
11914 * @returns {!ByteBuffer} this
11915 * @expose
11916 */
11917 ByteBufferPrototype.LE = function(littleEndian) {
11918 this.littleEndian = typeof littleEndian !== 'undefined' ? !!littleEndian : true;
11919 return this;
11920 };
11921
11922 /**
11923 * Switches (to) big endian byte order.
11924 * @param {boolean=} bigEndian Defaults to `true`, otherwise uses little endian
11925 * @returns {!ByteBuffer} this
11926 * @expose
11927 */
11928 ByteBufferPrototype.BE = function(bigEndian) {
11929 this.littleEndian = typeof bigEndian !== 'undefined' ? !bigEndian : false;
11930 return this;
11931 };
11932 /**
11933 * Prepends some data to this ByteBuffer. This will overwrite any contents before the specified offset up to the
11934 * prepended data's length. If there is not enough space available before the specified `offset`, the backing buffer
11935 * will be resized and its contents moved accordingly.
11936 * @param {!ByteBuffer|string|!ArrayBuffer} source Data to prepend. If `source` is a ByteBuffer, its offset will be
11937 * modified according to the performed read operation.
11938 * @param {(string|number)=} encoding Encoding if `data` is a string ("base64", "hex", "binary", defaults to "utf8")
11939 * @param {number=} offset Offset to prepend at. Will use and decrease {@link ByteBuffer#offset} by the number of bytes
11940 * prepended if omitted.
11941 * @returns {!ByteBuffer} this
11942 * @expose
11943 * @example A relative `00<01 02 03>.prepend(<04 05>)` results in `<04 05 01 02 03>, 04 05|`
11944 * @example An absolute `00<01 02 03>.prepend(<04 05>, 2)` results in `04<05 02 03>, 04 05|`
11945 */
11946 ByteBufferPrototype.prepend = function(source, encoding, offset) {
11947 if (typeof encoding === 'number' || typeof encoding !== 'string') {
11948 offset = encoding;
11949 encoding = undefined;
11950 }
11951 var relative = typeof offset === 'undefined';
11952 if (relative) offset = this.offset;
11953 if (!this.noAssert) {
11954 if (typeof offset !== 'number' || offset % 1 !== 0)
11955 throw TypeError("Illegal offset: "+offset+" (not an integer)");
11956 offset >>>= 0;
11957 if (offset < 0 || offset + 0 > this.buffer.byteLength)
11958 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
11959 }
11960 if (!(source instanceof ByteBuffer))
11961 source = ByteBuffer.wrap(source, encoding);
11962 var len = source.limit - source.offset;
11963 if (len <= 0) return this; // Nothing to prepend
11964 var diff = len - offset;
11965 if (diff > 0) { // Not enough space before offset, so resize + move
11966 var buffer = new ArrayBuffer(this.buffer.byteLength + diff);
11967 var view = new Uint8Array(buffer);
11968 view.set(this.view.subarray(offset, this.buffer.byteLength), len);
11969 this.buffer = buffer;
11970 this.view = view;
11971 this.offset += diff;
11972 if (this.markedOffset >= 0) this.markedOffset += diff;
11973 this.limit += diff;
11974 offset += diff;
11975 } else {
11976 var arrayView = new Uint8Array(this.buffer);
11977 }
11978 this.view.set(source.view.subarray(source.offset, source.limit), offset - len);
11979
11980 source.offset = source.limit;
11981 if (relative)
11982 this.offset -= len;
11983 return this;
11984 };
11985
11986 /**
11987 * Prepends this ByteBuffer to another ByteBuffer. This will overwrite any contents before the specified offset up to the
11988 * prepended data's length. If there is not enough space available before the specified `offset`, the backing buffer
11989 * will be resized and its contents moved accordingly.
11990 * @param {!ByteBuffer} target Target ByteBuffer
11991 * @param {number=} offset Offset to prepend at. Will use and decrease {@link ByteBuffer#offset} by the number of bytes
11992 * prepended if omitted.
11993 * @returns {!ByteBuffer} this
11994 * @expose
11995 * @see ByteBuffer#prepend
11996 */
11997 ByteBufferPrototype.prependTo = function(target, offset) {
11998 target.prepend(this, offset);
11999 return this;
12000 };
12001 /**
12002 * Prints debug information about this ByteBuffer's contents.
12003 * @param {function(string)=} out Output function to call, defaults to console.log
12004 * @expose
12005 */
12006 ByteBufferPrototype.printDebug = function(out) {
12007 if (typeof out !== 'function') out = console.log.bind(console);
12008 out(
12009 this.toString()+"\n"+
12010 "-------------------------------------------------------------------\n"+
12011 this.toDebug(/* columns */ true)
12012 );
12013 };
12014
12015 /**
12016 * Gets the number of remaining readable bytes. Contents are the bytes between {@link ByteBuffer#offset} and
12017 * {@link ByteBuffer#limit}, so this returns `limit - offset`.
12018 * @returns {number} Remaining readable bytes. May be negative if `offset > limit`.
12019 * @expose
12020 */
12021 ByteBufferPrototype.remaining = function() {
12022 return this.limit - this.offset;
12023 };
12024 /**
12025 * Resets this ByteBuffer's {@link ByteBuffer#offset}. If an offset has been marked through {@link ByteBuffer#mark}
12026 * before, `offset` will be set to {@link ByteBuffer#markedOffset}, which will then be discarded. If no offset has been
12027 * marked, sets `offset = 0`.
12028 * @returns {!ByteBuffer} this
12029 * @see ByteBuffer#mark
12030 * @expose
12031 */
12032 ByteBufferPrototype.reset = function() {
12033 if (this.markedOffset >= 0) {
12034 this.offset = this.markedOffset;
12035 this.markedOffset = -1;
12036 } else {
12037 this.offset = 0;
12038 }
12039 return this;
12040 };
12041 /**
12042 * Resizes this ByteBuffer to be backed by a buffer of at least the given capacity. Will do nothing if already that
12043 * large or larger.
12044 * @param {number} capacity Capacity required
12045 * @returns {!ByteBuffer} this
12046 * @throws {TypeError} If `capacity` is not a number
12047 * @throws {RangeError} If `capacity < 0`
12048 * @expose
12049 */
12050 ByteBufferPrototype.resize = function(capacity) {
12051 if (!this.noAssert) {
12052 if (typeof capacity !== 'number' || capacity % 1 !== 0)
12053 throw TypeError("Illegal capacity: "+capacity+" (not an integer)");
12054 capacity |= 0;
12055 if (capacity < 0)
12056 throw RangeError("Illegal capacity: 0 <= "+capacity);
12057 }
12058 if (this.buffer.byteLength < capacity) {
12059 var buffer = new ArrayBuffer(capacity);
12060 var view = new Uint8Array(buffer);
12061 view.set(this.view);
12062 this.buffer = buffer;
12063 this.view = view;
12064 }
12065 return this;
12066 };
12067 /**
12068 * Reverses this ByteBuffer's contents.
12069 * @param {number=} begin Offset to start at, defaults to {@link ByteBuffer#offset}
12070 * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}
12071 * @returns {!ByteBuffer} this
12072 * @expose
12073 */
12074 ByteBufferPrototype.reverse = function(begin, end) {
12075 if (typeof begin === 'undefined') begin = this.offset;
12076 if (typeof end === 'undefined') end = this.limit;
12077 if (!this.noAssert) {
12078 if (typeof begin !== 'number' || begin % 1 !== 0)
12079 throw TypeError("Illegal begin: Not an integer");
12080 begin >>>= 0;
12081 if (typeof end !== 'number' || end % 1 !== 0)
12082 throw TypeError("Illegal end: Not an integer");
12083 end >>>= 0;
12084 if (begin < 0 || begin > end || end > this.buffer.byteLength)
12085 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
12086 }
12087 if (begin === end)
12088 return this; // Nothing to reverse
12089 Array.prototype.reverse.call(this.view.subarray(begin, end));
12090 return this;
12091 };
12092 /**
12093 * Skips the next `length` bytes. This will just advance
12094 * @param {number} length Number of bytes to skip. May also be negative to move the offset back.
12095 * @returns {!ByteBuffer} this
12096 * @expose
12097 */
12098 ByteBufferPrototype.skip = function(length) {
12099 if (!this.noAssert) {
12100 if (typeof length !== 'number' || length % 1 !== 0)
12101 throw TypeError("Illegal length: "+length+" (not an integer)");
12102 length |= 0;
12103 }
12104 var offset = this.offset + length;
12105 if (!this.noAssert) {
12106 if (offset < 0 || offset > this.buffer.byteLength)
12107 throw RangeError("Illegal length: 0 <= "+this.offset+" + "+length+" <= "+this.buffer.byteLength);
12108 }
12109 this.offset = offset;
12110 return this;
12111 };
12112
12113 /**
12114 * Slices this ByteBuffer by creating a cloned instance with `offset = begin` and `limit = end`.
12115 * @param {number=} begin Begin offset, defaults to {@link ByteBuffer#offset}.
12116 * @param {number=} end End offset, defaults to {@link ByteBuffer#limit}.
12117 * @returns {!ByteBuffer} Clone of this ByteBuffer with slicing applied, backed by the same {@link ByteBuffer#buffer}
12118 * @expose
12119 */
12120 ByteBufferPrototype.slice = function(begin, end) {
12121 if (typeof begin === 'undefined') begin = this.offset;
12122 if (typeof end === 'undefined') end = this.limit;
12123 if (!this.noAssert) {
12124 if (typeof begin !== 'number' || begin % 1 !== 0)
12125 throw TypeError("Illegal begin: Not an integer");
12126 begin >>>= 0;
12127 if (typeof end !== 'number' || end % 1 !== 0)
12128 throw TypeError("Illegal end: Not an integer");
12129 end >>>= 0;
12130 if (begin < 0 || begin > end || end > this.buffer.byteLength)
12131 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
12132 }
12133 var bb = this.clone();
12134 bb.offset = begin;
12135 bb.limit = end;
12136 return bb;
12137 };
12138 /**
12139 * Returns a copy of the backing buffer that contains this ByteBuffer's contents. Contents are the bytes between
12140 * {@link ByteBuffer#offset} and {@link ByteBuffer#limit}.
12141 * @param {boolean=} forceCopy If `true` returns a copy, otherwise returns a view referencing the same memory if
12142 * possible. Defaults to `false`
12143 * @returns {!ArrayBuffer} Contents as an ArrayBuffer
12144 * @expose
12145 */
12146 ByteBufferPrototype.toBuffer = function(forceCopy) {
12147 var offset = this.offset,
12148 limit = this.limit;
12149 if (!this.noAssert) {
12150 if (typeof offset !== 'number' || offset % 1 !== 0)
12151 throw TypeError("Illegal offset: Not an integer");
12152 offset >>>= 0;
12153 if (typeof limit !== 'number' || limit % 1 !== 0)
12154 throw TypeError("Illegal limit: Not an integer");
12155 limit >>>= 0;
12156 if (offset < 0 || offset > limit || limit > this.buffer.byteLength)
12157 throw RangeError("Illegal range: 0 <= "+offset+" <= "+limit+" <= "+this.buffer.byteLength);
12158 }
12159 // NOTE: It's not possible to have another ArrayBuffer reference the same memory as the backing buffer. This is
12160 // possible with Uint8Array#subarray only, but we have to return an ArrayBuffer by contract. So:
12161 if (!forceCopy && offset === 0 && limit === this.buffer.byteLength)
12162 return this.buffer;
12163 if (offset === limit)
12164 return EMPTY_BUFFER;
12165 var buffer = new ArrayBuffer(limit - offset);
12166 new Uint8Array(buffer).set(new Uint8Array(this.buffer).subarray(offset, limit), 0);
12167 return buffer;
12168 };
12169
12170 /**
12171 * Returns a raw buffer compacted to contain this ByteBuffer's contents. Contents are the bytes between
12172 * {@link ByteBuffer#offset} and {@link ByteBuffer#limit}. This is an alias of {@link ByteBuffer#toBuffer}.
12173 * @function
12174 * @param {boolean=} forceCopy If `true` returns a copy, otherwise returns a view referencing the same memory.
12175 * Defaults to `false`
12176 * @returns {!ArrayBuffer} Contents as an ArrayBuffer
12177 * @expose
12178 */
12179 ByteBufferPrototype.toArrayBuffer = ByteBufferPrototype.toBuffer;
12180
12181 /**
12182 * Converts the ByteBuffer's contents to a string.
12183 * @param {string=} encoding Output encoding. Returns an informative string representation if omitted but also allows
12184 * direct conversion to "utf8", "hex", "base64" and "binary" encoding. "debug" returns a hex representation with
12185 * highlighted offsets.
12186 * @param {number=} begin Offset to begin at, defaults to {@link ByteBuffer#offset}
12187 * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}
12188 * @returns {string} String representation
12189 * @throws {Error} If `encoding` is invalid
12190 * @expose
12191 */
12192 ByteBufferPrototype.toString = function(encoding, begin, end) {
12193 if (typeof encoding === 'undefined')
12194 return "ByteBufferAB(offset="+this.offset+",markedOffset="+this.markedOffset+",limit="+this.limit+",capacity="+this.capacity()+")";
12195 if (typeof encoding === 'number')
12196 encoding = "utf8",
12197 begin = encoding,
12198 end = begin;
12199 switch (encoding) {
12200 case "utf8":
12201 return this.toUTF8(begin, end);
12202 case "base64":
12203 return this.toBase64(begin, end);
12204 case "hex":
12205 return this.toHex(begin, end);
12206 case "binary":
12207 return this.toBinary(begin, end);
12208 case "debug":
12209 return this.toDebug();
12210 case "columns":
12211 return this.toColumns();
12212 default:
12213 throw Error("Unsupported encoding: "+encoding);
12214 }
12215 };
12216
12217 // lxiv-embeddable
12218
12219 /**
12220 * lxiv-embeddable (c) 2014 Daniel Wirtz <dcode@dcode.io>
12221 * Released under the Apache License, Version 2.0
12222 * see: https://github.com/dcodeIO/lxiv for details
12223 */
12224 var lxiv = function() {
12225 "use strict";
12226
12227 /**
12228 * lxiv namespace.
12229 * @type {!Object.<string,*>}
12230 * @exports lxiv
12231 */
12232 var lxiv = {};
12233
12234 /**
12235 * Character codes for output.
12236 * @type {!Array.<number>}
12237 * @inner
12238 */
12239 var aout = [
12240 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
12241 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 97, 98, 99, 100, 101, 102,
12242 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118,
12243 119, 120, 121, 122, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 43, 47
12244 ];
12245
12246 /**
12247 * Character codes for input.
12248 * @type {!Array.<number>}
12249 * @inner
12250 */
12251 var ain = [];
12252 for (var i=0, k=aout.length; i<k; ++i)
12253 ain[aout[i]] = i;
12254
12255 /**
12256 * Encodes bytes to base64 char codes.
12257 * @param {!function():number|null} src Bytes source as a function returning the next byte respectively `null` if
12258 * there are no more bytes left.
12259 * @param {!function(number)} dst Characters destination as a function successively called with each encoded char
12260 * code.
12261 */
12262 lxiv.encode = function(src, dst) {
12263 var b, t;
12264 while ((b = src()) !== null) {
12265 dst(aout[(b>>2)&0x3f]);
12266 t = (b&0x3)<<4;
12267 if ((b = src()) !== null) {
12268 t |= (b>>4)&0xf;
12269 dst(aout[(t|((b>>4)&0xf))&0x3f]);
12270 t = (b&0xf)<<2;
12271 if ((b = src()) !== null)
12272 dst(aout[(t|((b>>6)&0x3))&0x3f]),
12273 dst(aout[b&0x3f]);
12274 else
12275 dst(aout[t&0x3f]),
12276 dst(61);
12277 } else
12278 dst(aout[t&0x3f]),
12279 dst(61),
12280 dst(61);
12281 }
12282 };
12283
12284 /**
12285 * Decodes base64 char codes to bytes.
12286 * @param {!function():number|null} src Characters source as a function returning the next char code respectively
12287 * `null` if there are no more characters left.
12288 * @param {!function(number)} dst Bytes destination as a function successively called with the next byte.
12289 * @throws {Error} If a character code is invalid
12290 */
12291 lxiv.decode = function(src, dst) {
12292 var c, t1, t2;
12293 function fail(c) {
12294 throw Error("Illegal character code: "+c);
12295 }
12296 while ((c = src()) !== null) {
12297 t1 = ain[c];
12298 if (typeof t1 === 'undefined') fail(c);
12299 if ((c = src()) !== null) {
12300 t2 = ain[c];
12301 if (typeof t2 === 'undefined') fail(c);
12302 dst((t1<<2)>>>0|(t2&0x30)>>4);
12303 if ((c = src()) !== null) {
12304 t1 = ain[c];
12305 if (typeof t1 === 'undefined')
12306 if (c === 61) break; else fail(c);
12307 dst(((t2&0xf)<<4)>>>0|(t1&0x3c)>>2);
12308 if ((c = src()) !== null) {
12309 t2 = ain[c];
12310 if (typeof t2 === 'undefined')
12311 if (c === 61) break; else fail(c);
12312 dst(((t1&0x3)<<6)>>>0|t2);
12313 }
12314 }
12315 }
12316 }
12317 };
12318
12319 /**
12320 * Tests if a string is valid base64.
12321 * @param {string} str String to test
12322 * @returns {boolean} `true` if valid, otherwise `false`
12323 */
12324 lxiv.test = function(str) {
12325 return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(str);
12326 };
12327
12328 return lxiv;
12329 }();
12330
12331 // encodings/base64
12332
12333 /**
12334 * Encodes this ByteBuffer's contents to a base64 encoded string.
12335 * @param {number=} begin Offset to begin at, defaults to {@link ByteBuffer#offset}.
12336 * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}.
12337 * @returns {string} Base64 encoded string
12338 * @throws {RangeError} If `begin` or `end` is out of bounds
12339 * @expose
12340 */
12341 ByteBufferPrototype.toBase64 = function(begin, end) {
12342 if (typeof begin === 'undefined')
12343 begin = this.offset;
12344 if (typeof end === 'undefined')
12345 end = this.limit;
12346 begin = begin | 0; end = end | 0;
12347 if (begin < 0 || end > this.capacity || begin > end)
12348 throw RangeError("begin, end");
12349 var sd; lxiv.encode(function() {
12350 return begin < end ? this.view[begin++] : null;
12351 }.bind(this), sd = stringDestination());
12352 return sd();
12353 };
12354
12355 /**
12356 * Decodes a base64 encoded string to a ByteBuffer.
12357 * @param {string} str String to decode
12358 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
12359 * {@link ByteBuffer.DEFAULT_ENDIAN}.
12360 * @returns {!ByteBuffer} ByteBuffer
12361 * @expose
12362 */
12363 ByteBuffer.fromBase64 = function(str, littleEndian) {
12364 if (typeof str !== 'string')
12365 throw TypeError("str");
12366 var bb = new ByteBuffer(str.length/4*3, littleEndian),
12367 i = 0;
12368 lxiv.decode(stringSource(str), function(b) {
12369 bb.view[i++] = b;
12370 });
12371 bb.limit = i;
12372 return bb;
12373 };
12374
12375 /**
12376 * Encodes a binary string to base64 like `window.btoa` does.
12377 * @param {string} str Binary string
12378 * @returns {string} Base64 encoded string
12379 * @see https://developer.mozilla.org/en-US/docs/Web/API/Window.btoa
12380 * @expose
12381 */
12382 ByteBuffer.btoa = function(str) {
12383 return ByteBuffer.fromBinary(str).toBase64();
12384 };
12385
12386 /**
12387 * Decodes a base64 encoded string to binary like `window.atob` does.
12388 * @param {string} b64 Base64 encoded string
12389 * @returns {string} Binary string
12390 * @see https://developer.mozilla.org/en-US/docs/Web/API/Window.atob
12391 * @expose
12392 */
12393 ByteBuffer.atob = function(b64) {
12394 return ByteBuffer.fromBase64(b64).toBinary();
12395 };
12396
12397 // encodings/binary
12398
12399 /**
12400 * Encodes this ByteBuffer to a binary encoded string, that is using only characters 0x00-0xFF as bytes.
12401 * @param {number=} begin Offset to begin at. Defaults to {@link ByteBuffer#offset}.
12402 * @param {number=} end Offset to end at. Defaults to {@link ByteBuffer#limit}.
12403 * @returns {string} Binary encoded string
12404 * @throws {RangeError} If `offset > limit`
12405 * @expose
12406 */
12407 ByteBufferPrototype.toBinary = function(begin, end) {
12408 if (typeof begin === 'undefined')
12409 begin = this.offset;
12410 if (typeof end === 'undefined')
12411 end = this.limit;
12412 begin |= 0; end |= 0;
12413 if (begin < 0 || end > this.capacity() || begin > end)
12414 throw RangeError("begin, end");
12415 if (begin === end)
12416 return "";
12417 var chars = [],
12418 parts = [];
12419 while (begin < end) {
12420 chars.push(this.view[begin++]);
12421 if (chars.length >= 1024)
12422 parts.push(String.fromCharCode.apply(String, chars)),
12423 chars = [];
12424 }
12425 return parts.join('') + String.fromCharCode.apply(String, chars);
12426 };
12427
12428 /**
12429 * Decodes a binary encoded string, that is using only characters 0x00-0xFF as bytes, to a ByteBuffer.
12430 * @param {string} str String to decode
12431 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
12432 * {@link ByteBuffer.DEFAULT_ENDIAN}.
12433 * @returns {!ByteBuffer} ByteBuffer
12434 * @expose
12435 */
12436 ByteBuffer.fromBinary = function(str, littleEndian) {
12437 if (typeof str !== 'string')
12438 throw TypeError("str");
12439 var i = 0,
12440 k = str.length,
12441 charCode,
12442 bb = new ByteBuffer(k, littleEndian);
12443 while (i<k) {
12444 charCode = str.charCodeAt(i);
12445 if (charCode > 0xff)
12446 throw RangeError("illegal char code: "+charCode);
12447 bb.view[i++] = charCode;
12448 }
12449 bb.limit = k;
12450 return bb;
12451 };
12452
12453 // encodings/debug
12454
12455 /**
12456 * Encodes this ByteBuffer to a hex encoded string with marked offsets. Offset symbols are:
12457 * * `<` : offset,
12458 * * `'` : markedOffset,
12459 * * `>` : limit,
12460 * * `|` : offset and limit,
12461 * * `[` : offset and markedOffset,
12462 * * `]` : markedOffset and limit,
12463 * * `!` : offset, markedOffset and limit
12464 * @param {boolean=} columns If `true` returns two columns hex + ascii, defaults to `false`
12465 * @returns {string|!Array.<string>} Debug string or array of lines if `asArray = true`
12466 * @expose
12467 * @example `>00'01 02<03` contains four bytes with `limit=0, markedOffset=1, offset=3`
12468 * @example `00[01 02 03>` contains four bytes with `offset=markedOffset=1, limit=4`
12469 * @example `00|01 02 03` contains four bytes with `offset=limit=1, markedOffset=-1`
12470 * @example `|` contains zero bytes with `offset=limit=0, markedOffset=-1`
12471 */
12472 ByteBufferPrototype.toDebug = function(columns) {
12473 var i = -1,
12474 k = this.buffer.byteLength,
12475 b,
12476 hex = "",
12477 asc = "",
12478 out = "";
12479 while (i<k) {
12480 if (i !== -1) {
12481 b = this.view[i];
12482 if (b < 0x10) hex += "0"+b.toString(16).toUpperCase();
12483 else hex += b.toString(16).toUpperCase();
12484 if (columns)
12485 asc += b > 32 && b < 127 ? String.fromCharCode(b) : '.';
12486 }
12487 ++i;
12488 if (columns) {
12489 if (i > 0 && i % 16 === 0 && i !== k) {
12490 while (hex.length < 3*16+3) hex += " ";
12491 out += hex+asc+"\n";
12492 hex = asc = "";
12493 }
12494 }
12495 if (i === this.offset && i === this.limit)
12496 hex += i === this.markedOffset ? "!" : "|";
12497 else if (i === this.offset)
12498 hex += i === this.markedOffset ? "[" : "<";
12499 else if (i === this.limit)
12500 hex += i === this.markedOffset ? "]" : ">";
12501 else
12502 hex += i === this.markedOffset ? "'" : (columns || (i !== 0 && i !== k) ? " " : "");
12503 }
12504 if (columns && hex !== " ") {
12505 while (hex.length < 3*16+3)
12506 hex += " ";
12507 out += hex + asc + "\n";
12508 }
12509 return columns ? out : hex;
12510 };
12511
12512 /**
12513 * Decodes a hex encoded string with marked offsets to a ByteBuffer.
12514 * @param {string} str Debug string to decode (not be generated with `columns = true`)
12515 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
12516 * {@link ByteBuffer.DEFAULT_ENDIAN}.
12517 * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
12518 * {@link ByteBuffer.DEFAULT_NOASSERT}.
12519 * @returns {!ByteBuffer} ByteBuffer
12520 * @expose
12521 * @see ByteBuffer#toDebug
12522 */
12523 ByteBuffer.fromDebug = function(str, littleEndian, noAssert) {
12524 var k = str.length,
12525 bb = new ByteBuffer(((k+1)/3)|0, littleEndian, noAssert);
12526 var i = 0, j = 0, ch, b,
12527 rs = false, // Require symbol next
12528 ho = false, hm = false, hl = false, // Already has offset (ho), markedOffset (hm), limit (hl)?
12529 fail = false;
12530 while (i<k) {
12531 switch (ch = str.charAt(i++)) {
12532 case '!':
12533 if (!noAssert) {
12534 if (ho || hm || hl) {
12535 fail = true;
12536 break;
12537 }
12538 ho = hm = hl = true;
12539 }
12540 bb.offset = bb.markedOffset = bb.limit = j;
12541 rs = false;
12542 break;
12543 case '|':
12544 if (!noAssert) {
12545 if (ho || hl) {
12546 fail = true;
12547 break;
12548 }
12549 ho = hl = true;
12550 }
12551 bb.offset = bb.limit = j;
12552 rs = false;
12553 break;
12554 case '[':
12555 if (!noAssert) {
12556 if (ho || hm) {
12557 fail = true;
12558 break;
12559 }
12560 ho = hm = true;
12561 }
12562 bb.offset = bb.markedOffset = j;
12563 rs = false;
12564 break;
12565 case '<':
12566 if (!noAssert) {
12567 if (ho) {
12568 fail = true;
12569 break;
12570 }
12571 ho = true;
12572 }
12573 bb.offset = j;
12574 rs = false;
12575 break;
12576 case ']':
12577 if (!noAssert) {
12578 if (hl || hm) {
12579 fail = true;
12580 break;
12581 }
12582 hl = hm = true;
12583 }
12584 bb.limit = bb.markedOffset = j;
12585 rs = false;
12586 break;
12587 case '>':
12588 if (!noAssert) {
12589 if (hl) {
12590 fail = true;
12591 break;
12592 }
12593 hl = true;
12594 }
12595 bb.limit = j;
12596 rs = false;
12597 break;
12598 case "'":
12599 if (!noAssert) {
12600 if (hm) {
12601 fail = true;
12602 break;
12603 }
12604 hm = true;
12605 }
12606 bb.markedOffset = j;
12607 rs = false;
12608 break;
12609 case ' ':
12610 rs = false;
12611 break;
12612 default:
12613 if (!noAssert) {
12614 if (rs) {
12615 fail = true;
12616 break;
12617 }
12618 }
12619 b = parseInt(ch+str.charAt(i++), 16);
12620 if (!noAssert) {
12621 if (isNaN(b) || b < 0 || b > 255)
12622 throw TypeError("Illegal str: Not a debug encoded string");
12623 }
12624 bb.view[j++] = b;
12625 rs = true;
12626 }
12627 if (fail)
12628 throw TypeError("Illegal str: Invalid symbol at "+i);
12629 }
12630 if (!noAssert) {
12631 if (!ho || !hl)
12632 throw TypeError("Illegal str: Missing offset or limit");
12633 if (j<bb.buffer.byteLength)
12634 throw TypeError("Illegal str: Not a debug encoded string (is it hex?) "+j+" < "+k);
12635 }
12636 return bb;
12637 };
12638
12639 // encodings/hex
12640
12641 /**
12642 * Encodes this ByteBuffer's contents to a hex encoded string.
12643 * @param {number=} begin Offset to begin at. Defaults to {@link ByteBuffer#offset}.
12644 * @param {number=} end Offset to end at. Defaults to {@link ByteBuffer#limit}.
12645 * @returns {string} Hex encoded string
12646 * @expose
12647 */
12648 ByteBufferPrototype.toHex = function(begin, end) {
12649 begin = typeof begin === 'undefined' ? this.offset : begin;
12650 end = typeof end === 'undefined' ? this.limit : end;
12651 if (!this.noAssert) {
12652 if (typeof begin !== 'number' || begin % 1 !== 0)
12653 throw TypeError("Illegal begin: Not an integer");
12654 begin >>>= 0;
12655 if (typeof end !== 'number' || end % 1 !== 0)
12656 throw TypeError("Illegal end: Not an integer");
12657 end >>>= 0;
12658 if (begin < 0 || begin > end || end > this.buffer.byteLength)
12659 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
12660 }
12661 var out = new Array(end - begin),
12662 b;
12663 while (begin < end) {
12664 b = this.view[begin++];
12665 if (b < 0x10)
12666 out.push("0", b.toString(16));
12667 else out.push(b.toString(16));
12668 }
12669 return out.join('');
12670 };
12671
12672 /**
12673 * Decodes a hex encoded string to a ByteBuffer.
12674 * @param {string} str String to decode
12675 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
12676 * {@link ByteBuffer.DEFAULT_ENDIAN}.
12677 * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
12678 * {@link ByteBuffer.DEFAULT_NOASSERT}.
12679 * @returns {!ByteBuffer} ByteBuffer
12680 * @expose
12681 */
12682 ByteBuffer.fromHex = function(str, littleEndian, noAssert) {
12683 if (!noAssert) {
12684 if (typeof str !== 'string')
12685 throw TypeError("Illegal str: Not a string");
12686 if (str.length % 2 !== 0)
12687 throw TypeError("Illegal str: Length not a multiple of 2");
12688 }
12689 var k = str.length,
12690 bb = new ByteBuffer((k / 2) | 0, littleEndian),
12691 b;
12692 for (var i=0, j=0; i<k; i+=2) {
12693 b = parseInt(str.substring(i, i+2), 16);
12694 if (!noAssert)
12695 if (!isFinite(b) || b < 0 || b > 255)
12696 throw TypeError("Illegal str: Contains non-hex characters");
12697 bb.view[j++] = b;
12698 }
12699 bb.limit = j;
12700 return bb;
12701 };
12702
12703 // utfx-embeddable
12704
12705 /**
12706 * utfx-embeddable (c) 2014 Daniel Wirtz <dcode@dcode.io>
12707 * Released under the Apache License, Version 2.0
12708 * see: https://github.com/dcodeIO/utfx for details
12709 */
12710 var utfx = function() {
12711 "use strict";
12712
12713 /**
12714 * utfx namespace.
12715 * @inner
12716 * @type {!Object.<string,*>}
12717 */
12718 var utfx = {};
12719
12720 /**
12721 * Maximum valid code point.
12722 * @type {number}
12723 * @const
12724 */
12725 utfx.MAX_CODEPOINT = 0x10FFFF;
12726
12727 /**
12728 * Encodes UTF8 code points to UTF8 bytes.
12729 * @param {(!function():number|null) | number} src Code points source, either as a function returning the next code point
12730 * respectively `null` if there are no more code points left or a single numeric code point.
12731 * @param {!function(number)} dst Bytes destination as a function successively called with the next byte
12732 */
12733 utfx.encodeUTF8 = function(src, dst) {
12734 var cp = null;
12735 if (typeof src === 'number')
12736 cp = src,
12737 src = function() { return null; };
12738 while (cp !== null || (cp = src()) !== null) {
12739 if (cp < 0x80)
12740 dst(cp&0x7F);
12741 else if (cp < 0x800)
12742 dst(((cp>>6)&0x1F)|0xC0),
12743 dst((cp&0x3F)|0x80);
12744 else if (cp < 0x10000)
12745 dst(((cp>>12)&0x0F)|0xE0),
12746 dst(((cp>>6)&0x3F)|0x80),
12747 dst((cp&0x3F)|0x80);
12748 else
12749 dst(((cp>>18)&0x07)|0xF0),
12750 dst(((cp>>12)&0x3F)|0x80),
12751 dst(((cp>>6)&0x3F)|0x80),
12752 dst((cp&0x3F)|0x80);
12753 cp = null;
12754 }
12755 };
12756
12757 /**
12758 * Decodes UTF8 bytes to UTF8 code points.
12759 * @param {!function():number|null} src Bytes source as a function returning the next byte respectively `null` if there
12760 * are no more bytes left.
12761 * @param {!function(number)} dst Code points destination as a function successively called with each decoded code point.
12762 * @throws {RangeError} If a starting byte is invalid in UTF8
12763 * @throws {Error} If the last sequence is truncated. Has an array property `bytes` holding the
12764 * remaining bytes.
12765 */
12766 utfx.decodeUTF8 = function(src, dst) {
12767 var a, b, c, d, fail = function(b) {
12768 b = b.slice(0, b.indexOf(null));
12769 var err = Error(b.toString());
12770 err.name = "TruncatedError";
12771 err['bytes'] = b;
12772 throw err;
12773 };
12774 while ((a = src()) !== null) {
12775 if ((a&0x80) === 0)
12776 dst(a);
12777 else if ((a&0xE0) === 0xC0)
12778 ((b = src()) === null) && fail([a, b]),
12779 dst(((a&0x1F)<<6) | (b&0x3F));
12780 else if ((a&0xF0) === 0xE0)
12781 ((b=src()) === null || (c=src()) === null) && fail([a, b, c]),
12782 dst(((a&0x0F)<<12) | ((b&0x3F)<<6) | (c&0x3F));
12783 else if ((a&0xF8) === 0xF0)
12784 ((b=src()) === null || (c=src()) === null || (d=src()) === null) && fail([a, b, c ,d]),
12785 dst(((a&0x07)<<18) | ((b&0x3F)<<12) | ((c&0x3F)<<6) | (d&0x3F));
12786 else throw RangeError("Illegal starting byte: "+a);
12787 }
12788 };
12789
12790 /**
12791 * Converts UTF16 characters to UTF8 code points.
12792 * @param {!function():number|null} src Characters source as a function returning the next char code respectively
12793 * `null` if there are no more characters left.
12794 * @param {!function(number)} dst Code points destination as a function successively called with each converted code
12795 * point.
12796 */
12797 utfx.UTF16toUTF8 = function(src, dst) {
12798 var c1, c2 = null;
12799 while (true) {
12800 if ((c1 = c2 !== null ? c2 : src()) === null)
12801 break;
12802 if (c1 >= 0xD800 && c1 <= 0xDFFF) {
12803 if ((c2 = src()) !== null) {
12804 if (c2 >= 0xDC00 && c2 <= 0xDFFF) {
12805 dst((c1-0xD800)*0x400+c2-0xDC00+0x10000);
12806 c2 = null; continue;
12807 }
12808 }
12809 }
12810 dst(c1);
12811 }
12812 if (c2 !== null) dst(c2);
12813 };
12814
12815 /**
12816 * Converts UTF8 code points to UTF16 characters.
12817 * @param {(!function():number|null) | number} src Code points source, either as a function returning the next code point
12818 * respectively `null` if there are no more code points left or a single numeric code point.
12819 * @param {!function(number)} dst Characters destination as a function successively called with each converted char code.
12820 * @throws {RangeError} If a code point is out of range
12821 */
12822 utfx.UTF8toUTF16 = function(src, dst) {
12823 var cp = null;
12824 if (typeof src === 'number')
12825 cp = src, src = function() { return null; };
12826 while (cp !== null || (cp = src()) !== null) {
12827 if (cp <= 0xFFFF)
12828 dst(cp);
12829 else
12830 cp -= 0x10000,
12831 dst((cp>>10)+0xD800),
12832 dst((cp%0x400)+0xDC00);
12833 cp = null;
12834 }
12835 };
12836
12837 /**
12838 * Converts and encodes UTF16 characters to UTF8 bytes.
12839 * @param {!function():number|null} src Characters source as a function returning the next char code respectively `null`
12840 * if there are no more characters left.
12841 * @param {!function(number)} dst Bytes destination as a function successively called with the next byte.
12842 */
12843 utfx.encodeUTF16toUTF8 = function(src, dst) {
12844 utfx.UTF16toUTF8(src, function(cp) {
12845 utfx.encodeUTF8(cp, dst);
12846 });
12847 };
12848
12849 /**
12850 * Decodes and converts UTF8 bytes to UTF16 characters.
12851 * @param {!function():number|null} src Bytes source as a function returning the next byte respectively `null` if there
12852 * are no more bytes left.
12853 * @param {!function(number)} dst Characters destination as a function successively called with each converted char code.
12854 * @throws {RangeError} If a starting byte is invalid in UTF8
12855 * @throws {Error} If the last sequence is truncated. Has an array property `bytes` holding the remaining bytes.
12856 */
12857 utfx.decodeUTF8toUTF16 = function(src, dst) {
12858 utfx.decodeUTF8(src, function(cp) {
12859 utfx.UTF8toUTF16(cp, dst);
12860 });
12861 };
12862
12863 /**
12864 * Calculates the byte length of an UTF8 code point.
12865 * @param {number} cp UTF8 code point
12866 * @returns {number} Byte length
12867 */
12868 utfx.calculateCodePoint = function(cp) {
12869 return (cp < 0x80) ? 1 : (cp < 0x800) ? 2 : (cp < 0x10000) ? 3 : 4;
12870 };
12871
12872 /**
12873 * Calculates the number of UTF8 bytes required to store UTF8 code points.
12874 * @param {(!function():number|null)} src Code points source as a function returning the next code point respectively
12875 * `null` if there are no more code points left.
12876 * @returns {number} The number of UTF8 bytes required
12877 */
12878 utfx.calculateUTF8 = function(src) {
12879 var cp, l=0;
12880 while ((cp = src()) !== null)
12881 l += (cp < 0x80) ? 1 : (cp < 0x800) ? 2 : (cp < 0x10000) ? 3 : 4;
12882 return l;
12883 };
12884
12885 /**
12886 * Calculates the number of UTF8 code points respectively UTF8 bytes required to store UTF16 char codes.
12887 * @param {(!function():number|null)} src Characters source as a function returning the next char code respectively
12888 * `null` if there are no more characters left.
12889 * @returns {!Array.<number>} The number of UTF8 code points at index 0 and the number of UTF8 bytes required at index 1.
12890 */
12891 utfx.calculateUTF16asUTF8 = function(src) {
12892 var n=0, l=0;
12893 utfx.UTF16toUTF8(src, function(cp) {
12894 ++n; l += (cp < 0x80) ? 1 : (cp < 0x800) ? 2 : (cp < 0x10000) ? 3 : 4;
12895 });
12896 return [n,l];
12897 };
12898
12899 return utfx;
12900 }();
12901
12902 // encodings/utf8
12903
12904 /**
12905 * Encodes this ByteBuffer's contents between {@link ByteBuffer#offset} and {@link ByteBuffer#limit} to an UTF8 encoded
12906 * string.
12907 * @returns {string} Hex encoded string
12908 * @throws {RangeError} If `offset > limit`
12909 * @expose
12910 */
12911 ByteBufferPrototype.toUTF8 = function(begin, end) {
12912 if (typeof begin === 'undefined') begin = this.offset;
12913 if (typeof end === 'undefined') end = this.limit;
12914 if (!this.noAssert) {
12915 if (typeof begin !== 'number' || begin % 1 !== 0)
12916 throw TypeError("Illegal begin: Not an integer");
12917 begin >>>= 0;
12918 if (typeof end !== 'number' || end % 1 !== 0)
12919 throw TypeError("Illegal end: Not an integer");
12920 end >>>= 0;
12921 if (begin < 0 || begin > end || end > this.buffer.byteLength)
12922 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
12923 }
12924 var sd; try {
12925 utfx.decodeUTF8toUTF16(function() {
12926 return begin < end ? this.view[begin++] : null;
12927 }.bind(this), sd = stringDestination());
12928 } catch (e) {
12929 if (begin !== end)
12930 throw RangeError("Illegal range: Truncated data, "+begin+" != "+end);
12931 }
12932 return sd();
12933 };
12934
12935 /**
12936 * Decodes an UTF8 encoded string to a ByteBuffer.
12937 * @param {string} str String to decode
12938 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
12939 * {@link ByteBuffer.DEFAULT_ENDIAN}.
12940 * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
12941 * {@link ByteBuffer.DEFAULT_NOASSERT}.
12942 * @returns {!ByteBuffer} ByteBuffer
12943 * @expose
12944 */
12945 ByteBuffer.fromUTF8 = function(str, littleEndian, noAssert) {
12946 if (!noAssert)
12947 if (typeof str !== 'string')
12948 throw TypeError("Illegal str: Not a string");
12949 var bb = new ByteBuffer(utfx.calculateUTF16asUTF8(stringSource(str), true)[1], littleEndian, noAssert),
12950 i = 0;
12951 utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
12952 bb.view[i++] = b;
12953 });
12954 bb.limit = i;
12955 return bb;
12956 };
12957
12958 return ByteBuffer;
12959});
12960
12961},{"long":72}],58:[function(require,module,exports){
12962(function (Buffer){
12963var Transform = require('stream').Transform
12964var inherits = require('inherits')
12965var StringDecoder = require('string_decoder').StringDecoder
12966module.exports = CipherBase
12967inherits(CipherBase, Transform)
12968function CipherBase (hashMode) {
12969 Transform.call(this)
12970 this.hashMode = typeof hashMode === 'string'
12971 if (this.hashMode) {
12972 this[hashMode] = this._finalOrDigest
12973 } else {
12974 this.final = this._finalOrDigest
12975 }
12976 this._decoder = null
12977 this._encoding = null
12978}
12979CipherBase.prototype.update = function (data, inputEnc, outputEnc) {
12980 if (typeof data === 'string') {
12981 data = new Buffer(data, inputEnc)
12982 }
12983 var outData = this._update(data)
12984 if (this.hashMode) {
12985 return this
12986 }
12987 if (outputEnc) {
12988 outData = this._toString(outData, outputEnc)
12989 }
12990 return outData
12991}
12992
12993CipherBase.prototype.setAutoPadding = function () {}
12994
12995CipherBase.prototype.getAuthTag = function () {
12996 throw new Error('trying to get auth tag in unsupported state')
12997}
12998
12999CipherBase.prototype.setAuthTag = function () {
13000 throw new Error('trying to set auth tag in unsupported state')
13001}
13002
13003CipherBase.prototype.setAAD = function () {
13004 throw new Error('trying to set aad in unsupported state')
13005}
13006
13007CipherBase.prototype._transform = function (data, _, next) {
13008 var err
13009 try {
13010 if (this.hashMode) {
13011 this._update(data)
13012 } else {
13013 this.push(this._update(data))
13014 }
13015 } catch (e) {
13016 err = e
13017 } finally {
13018 next(err)
13019 }
13020}
13021CipherBase.prototype._flush = function (done) {
13022 var err
13023 try {
13024 this.push(this._final())
13025 } catch (e) {
13026 err = e
13027 } finally {
13028 done(err)
13029 }
13030}
13031CipherBase.prototype._finalOrDigest = function (outputEnc) {
13032 var outData = this._final() || new Buffer('')
13033 if (outputEnc) {
13034 outData = this._toString(outData, outputEnc, true)
13035 }
13036 return outData
13037}
13038
13039CipherBase.prototype._toString = function (value, enc, fin) {
13040 if (!this._decoder) {
13041 this._decoder = new StringDecoder(enc)
13042 this._encoding = enc
13043 }
13044 if (this._encoding !== enc) {
13045 throw new Error('can\'t switch encodings')
13046 }
13047 var out = this._decoder.write(value)
13048 if (fin) {
13049 out += this._decoder.end()
13050 }
13051 return out
13052}
13053
13054}).call(this,require("buffer").Buffer)
13055},{"buffer":5,"inherits":71,"stream":28,"string_decoder":29}],59:[function(require,module,exports){
13056(function (Buffer){
13057'use strict'
13058var inherits = require('inherits')
13059var md5 = require('./md5')
13060var RIPEMD160 = require('ripemd160')
13061var sha = require('sha.js')
13062
13063var Base = require('cipher-base')
13064
13065function HashNoConstructor (hash) {
13066 Base.call(this, 'digest')
13067
13068 this._hash = hash
13069 this.buffers = []
13070}
13071
13072inherits(HashNoConstructor, Base)
13073
13074HashNoConstructor.prototype._update = function (data) {
13075 this.buffers.push(data)
13076}
13077
13078HashNoConstructor.prototype._final = function () {
13079 var buf = Buffer.concat(this.buffers)
13080 var r = this._hash(buf)
13081 this.buffers = null
13082
13083 return r
13084}
13085
13086function Hash (hash) {
13087 Base.call(this, 'digest')
13088
13089 this._hash = hash
13090}
13091
13092inherits(Hash, Base)
13093
13094Hash.prototype._update = function (data) {
13095 this._hash.update(data)
13096}
13097
13098Hash.prototype._final = function () {
13099 return this._hash.digest()
13100}
13101
13102module.exports = function createHash (alg) {
13103 alg = alg.toLowerCase()
13104 if (alg === 'md5') return new HashNoConstructor(md5)
13105 if (alg === 'rmd160' || alg === 'ripemd160') return new Hash(new RIPEMD160())
13106
13107 return new Hash(sha(alg))
13108}
13109
13110}).call(this,require("buffer").Buffer)
13111},{"./md5":61,"buffer":5,"cipher-base":58,"inherits":71,"ripemd160":73,"sha.js":77}],60:[function(require,module,exports){
13112(function (Buffer){
13113'use strict'
13114var intSize = 4
13115var zeroBuffer = new Buffer(intSize)
13116zeroBuffer.fill(0)
13117
13118var charSize = 8
13119var hashSize = 16
13120
13121function toArray (buf) {
13122 if ((buf.length % intSize) !== 0) {
13123 var len = buf.length + (intSize - (buf.length % intSize))
13124 buf = Buffer.concat([buf, zeroBuffer], len)
13125 }
13126
13127 var arr = new Array(buf.length >>> 2)
13128 for (var i = 0, j = 0; i < buf.length; i += intSize, j++) {
13129 arr[j] = buf.readInt32LE(i)
13130 }
13131
13132 return arr
13133}
13134
13135module.exports = function hash (buf, fn) {
13136 var arr = fn(toArray(buf), buf.length * charSize)
13137 buf = new Buffer(hashSize)
13138 for (var i = 0; i < arr.length; i++) {
13139 buf.writeInt32LE(arr[i], i << 2, true)
13140 }
13141 return buf
13142}
13143
13144}).call(this,require("buffer").Buffer)
13145},{"buffer":5}],61:[function(require,module,exports){
13146'use strict'
13147/*
13148 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
13149 * Digest Algorithm, as defined in RFC 1321.
13150 * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
13151 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
13152 * Distributed under the BSD License
13153 * See http://pajhome.org.uk/crypt/md5 for more info.
13154 */
13155
13156var makeHash = require('./make-hash')
13157
13158/*
13159 * Calculate the MD5 of an array of little-endian words, and a bit length
13160 */
13161function core_md5 (x, len) {
13162 /* append padding */
13163 x[len >> 5] |= 0x80 << ((len) % 32)
13164 x[(((len + 64) >>> 9) << 4) + 14] = len
13165
13166 var a = 1732584193
13167 var b = -271733879
13168 var c = -1732584194
13169 var d = 271733878
13170
13171 for (var i = 0; i < x.length; i += 16) {
13172 var olda = a
13173 var oldb = b
13174 var oldc = c
13175 var oldd = d
13176
13177 a = md5_ff(a, b, c, d, x[i + 0], 7, -680876936)
13178 d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586)
13179 c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819)
13180 b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330)
13181 a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897)
13182 d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426)
13183 c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341)
13184 b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983)
13185 a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416)
13186 d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417)
13187 c = md5_ff(c, d, a, b, x[i + 10], 17, -42063)
13188 b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162)
13189 a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682)
13190 d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101)
13191 c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290)
13192 b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329)
13193
13194 a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510)
13195 d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632)
13196 c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713)
13197 b = md5_gg(b, c, d, a, x[i + 0], 20, -373897302)
13198 a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691)
13199 d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083)
13200 c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335)
13201 b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848)
13202 a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438)
13203 d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690)
13204 c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961)
13205 b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501)
13206 a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467)
13207 d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784)
13208 c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473)
13209 b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734)
13210
13211 a = md5_hh(a, b, c, d, x[i + 5], 4, -378558)
13212 d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463)
13213 c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562)
13214 b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556)
13215 a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060)
13216 d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353)
13217 c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632)
13218 b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640)
13219 a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174)
13220 d = md5_hh(d, a, b, c, x[i + 0], 11, -358537222)
13221 c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979)
13222 b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189)
13223 a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487)
13224 d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835)
13225 c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520)
13226 b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651)
13227
13228 a = md5_ii(a, b, c, d, x[i + 0], 6, -198630844)
13229 d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415)
13230 c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905)
13231 b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055)
13232 a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571)
13233 d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606)
13234 c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523)
13235 b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799)
13236 a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359)
13237 d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744)
13238 c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380)
13239 b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649)
13240 a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070)
13241 d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379)
13242 c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259)
13243 b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551)
13244
13245 a = safe_add(a, olda)
13246 b = safe_add(b, oldb)
13247 c = safe_add(c, oldc)
13248 d = safe_add(d, oldd)
13249 }
13250
13251 return [a, b, c, d]
13252}
13253
13254/*
13255 * These functions implement the four basic operations the algorithm uses.
13256 */
13257function md5_cmn (q, a, b, x, s, t) {
13258 return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b)
13259}
13260
13261function md5_ff (a, b, c, d, x, s, t) {
13262 return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t)
13263}
13264
13265function md5_gg (a, b, c, d, x, s, t) {
13266 return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t)
13267}
13268
13269function md5_hh (a, b, c, d, x, s, t) {
13270 return md5_cmn(b ^ c ^ d, a, b, x, s, t)
13271}
13272
13273function md5_ii (a, b, c, d, x, s, t) {
13274 return md5_cmn(c ^ (b | (~d)), a, b, x, s, t)
13275}
13276
13277/*
13278 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
13279 * to work around bugs in some JS interpreters.
13280 */
13281function safe_add (x, y) {
13282 var lsw = (x & 0xFFFF) + (y & 0xFFFF)
13283 var msw = (x >> 16) + (y >> 16) + (lsw >> 16)
13284 return (msw << 16) | (lsw & 0xFFFF)
13285}
13286
13287/*
13288 * Bitwise rotate a 32-bit number to the left.
13289 */
13290function bit_rol (num, cnt) {
13291 return (num << cnt) | (num >>> (32 - cnt))
13292}
13293
13294module.exports = function md5 (buf) {
13295 return makeHash(buf, core_md5)
13296}
13297
13298},{"./make-hash":60}],62:[function(require,module,exports){
13299'use strict'
13300var inherits = require('inherits')
13301var Legacy = require('./legacy')
13302var Base = require('cipher-base')
13303var Buffer = require('safe-buffer').Buffer
13304var md5 = require('create-hash/md5')
13305var RIPEMD160 = require('ripemd160')
13306
13307var sha = require('sha.js')
13308
13309var ZEROS = Buffer.alloc(128)
13310
13311function Hmac (alg, key) {
13312 Base.call(this, 'digest')
13313 if (typeof key === 'string') {
13314 key = Buffer.from(key)
13315 }
13316
13317 var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64
13318
13319 this._alg = alg
13320 this._key = key
13321 if (key.length > blocksize) {
13322 var hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg)
13323 key = hash.update(key).digest()
13324 } else if (key.length < blocksize) {
13325 key = Buffer.concat([key, ZEROS], blocksize)
13326 }
13327
13328 var ipad = this._ipad = Buffer.allocUnsafe(blocksize)
13329 var opad = this._opad = Buffer.allocUnsafe(blocksize)
13330
13331 for (var i = 0; i < blocksize; i++) {
13332 ipad[i] = key[i] ^ 0x36
13333 opad[i] = key[i] ^ 0x5C
13334 }
13335 this._hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg)
13336 this._hash.update(ipad)
13337}
13338
13339inherits(Hmac, Base)
13340
13341Hmac.prototype._update = function (data) {
13342 this._hash.update(data)
13343}
13344
13345Hmac.prototype._final = function () {
13346 var h = this._hash.digest()
13347 var hash = this._alg === 'rmd160' ? new RIPEMD160() : sha(this._alg)
13348 return hash.update(this._opad).update(h).digest()
13349}
13350
13351module.exports = function createHmac (alg, key) {
13352 alg = alg.toLowerCase()
13353 if (alg === 'rmd160' || alg === 'ripemd160') {
13354 return new Hmac('rmd160', key)
13355 }
13356 if (alg === 'md5') {
13357 return new Legacy(md5, key)
13358 }
13359 return new Hmac(alg, key)
13360}
13361
13362},{"./legacy":63,"cipher-base":58,"create-hash/md5":61,"inherits":71,"ripemd160":73,"safe-buffer":74,"sha.js":77}],63:[function(require,module,exports){
13363'use strict'
13364var inherits = require('inherits')
13365var Buffer = require('safe-buffer').Buffer
13366
13367var Base = require('cipher-base')
13368
13369var ZEROS = Buffer.alloc(128)
13370var blocksize = 64
13371
13372function Hmac (alg, key) {
13373 Base.call(this, 'digest')
13374 if (typeof key === 'string') {
13375 key = Buffer.from(key)
13376 }
13377
13378 this._alg = alg
13379 this._key = key
13380
13381 if (key.length > blocksize) {
13382 key = alg(key)
13383 } else if (key.length < blocksize) {
13384 key = Buffer.concat([key, ZEROS], blocksize)
13385 }
13386
13387 var ipad = this._ipad = Buffer.allocUnsafe(blocksize)
13388 var opad = this._opad = Buffer.allocUnsafe(blocksize)
13389
13390 for (var i = 0; i < blocksize; i++) {
13391 ipad[i] = key[i] ^ 0x36
13392 opad[i] = key[i] ^ 0x5C
13393 }
13394
13395 this._hash = [ipad]
13396}
13397
13398inherits(Hmac, Base)
13399
13400Hmac.prototype._update = function (data) {
13401 this._hash.push(data)
13402}
13403
13404Hmac.prototype._final = function () {
13405 var h = this._alg(Buffer.concat(this._hash))
13406 return this._alg(Buffer.concat([this._opad, h]))
13407}
13408module.exports = Hmac
13409
13410},{"cipher-base":58,"inherits":71,"safe-buffer":74}],64:[function(require,module,exports){
13411var assert = require('assert')
13412var BigInteger = require('bigi')
13413
13414var Point = require('./point')
13415
13416function Curve (p, a, b, Gx, Gy, n, h) {
13417 this.p = p
13418 this.a = a
13419 this.b = b
13420 this.G = Point.fromAffine(this, Gx, Gy)
13421 this.n = n
13422 this.h = h
13423
13424 this.infinity = new Point(this, null, null, BigInteger.ZERO)
13425
13426 // result caching
13427 this.pOverFour = p.add(BigInteger.ONE).shiftRight(2)
13428
13429 // determine size of p in bytes
13430 this.pLength = Math.floor((this.p.bitLength() + 7) / 8)
13431}
13432
13433Curve.prototype.pointFromX = function (isOdd, x) {
13434 var alpha = x.pow(3).add(this.a.multiply(x)).add(this.b).mod(this.p)
13435 var beta = alpha.modPow(this.pOverFour, this.p) // XXX: not compatible with all curves
13436
13437 var y = beta
13438 if (beta.isEven() ^ !isOdd) {
13439 y = this.p.subtract(y) // -y % p
13440 }
13441
13442 return Point.fromAffine(this, x, y)
13443}
13444
13445Curve.prototype.isInfinity = function (Q) {
13446 if (Q === this.infinity) return true
13447
13448 return Q.z.signum() === 0 && Q.y.signum() !== 0
13449}
13450
13451Curve.prototype.isOnCurve = function (Q) {
13452 if (this.isInfinity(Q)) return true
13453
13454 var x = Q.affineX
13455 var y = Q.affineY
13456 var a = this.a
13457 var b = this.b
13458 var p = this.p
13459
13460 // Check that xQ and yQ are integers in the interval [0, p - 1]
13461 if (x.signum() < 0 || x.compareTo(p) >= 0) return false
13462 if (y.signum() < 0 || y.compareTo(p) >= 0) return false
13463
13464 // and check that y^2 = x^3 + ax + b (mod p)
13465 var lhs = y.square().mod(p)
13466 var rhs = x.pow(3).add(a.multiply(x)).add(b).mod(p)
13467 return lhs.equals(rhs)
13468}
13469
13470/**
13471 * Validate an elliptic curve point.
13472 *
13473 * See SEC 1, section 3.2.2.1: Elliptic Curve Public Key Validation Primitive
13474 */
13475Curve.prototype.validate = function (Q) {
13476 // Check Q != O
13477 assert(!this.isInfinity(Q), 'Point is at infinity')
13478 assert(this.isOnCurve(Q), 'Point is not on the curve')
13479
13480 // Check nQ = O (where Q is a scalar multiple of G)
13481 var nQ = Q.multiply(this.n)
13482 assert(this.isInfinity(nQ), 'Point is not a scalar multiple of G')
13483
13484 return true
13485}
13486
13487module.exports = Curve
13488
13489},{"./point":68,"assert":1,"bigi":38}],65:[function(require,module,exports){
13490module.exports={
13491 "secp128r1": {
13492 "p": "fffffffdffffffffffffffffffffffff",
13493 "a": "fffffffdfffffffffffffffffffffffc",
13494 "b": "e87579c11079f43dd824993c2cee5ed3",
13495 "n": "fffffffe0000000075a30d1b9038a115",
13496 "h": "01",
13497 "Gx": "161ff7528b899b2d0c28607ca52c5b86",
13498 "Gy": "cf5ac8395bafeb13c02da292dded7a83"
13499 },
13500 "secp160k1": {
13501 "p": "fffffffffffffffffffffffffffffffeffffac73",
13502 "a": "00",
13503 "b": "07",
13504 "n": "0100000000000000000001b8fa16dfab9aca16b6b3",
13505 "h": "01",
13506 "Gx": "3b4c382ce37aa192a4019e763036f4f5dd4d7ebb",
13507 "Gy": "938cf935318fdced6bc28286531733c3f03c4fee"
13508 },
13509 "secp160r1": {
13510 "p": "ffffffffffffffffffffffffffffffff7fffffff",
13511 "a": "ffffffffffffffffffffffffffffffff7ffffffc",
13512 "b": "1c97befc54bd7a8b65acf89f81d4d4adc565fa45",
13513 "n": "0100000000000000000001f4c8f927aed3ca752257",
13514 "h": "01",
13515 "Gx": "4a96b5688ef573284664698968c38bb913cbfc82",
13516 "Gy": "23a628553168947d59dcc912042351377ac5fb32"
13517 },
13518 "secp192k1": {
13519 "p": "fffffffffffffffffffffffffffffffffffffffeffffee37",
13520 "a": "00",
13521 "b": "03",
13522 "n": "fffffffffffffffffffffffe26f2fc170f69466a74defd8d",
13523 "h": "01",
13524 "Gx": "db4ff10ec057e9ae26b07d0280b7f4341da5d1b1eae06c7d",
13525 "Gy": "9b2f2f6d9c5628a7844163d015be86344082aa88d95e2f9d"
13526 },
13527 "secp192r1": {
13528 "p": "fffffffffffffffffffffffffffffffeffffffffffffffff",
13529 "a": "fffffffffffffffffffffffffffffffefffffffffffffffc",
13530 "b": "64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1",
13531 "n": "ffffffffffffffffffffffff99def836146bc9b1b4d22831",
13532 "h": "01",
13533 "Gx": "188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012",
13534 "Gy": "07192b95ffc8da78631011ed6b24cdd573f977a11e794811"
13535 },
13536 "secp256k1": {
13537 "p": "fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f",
13538 "a": "00",
13539 "b": "07",
13540 "n": "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141",
13541 "h": "01",
13542 "Gx": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",
13543 "Gy": "483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"
13544 },
13545 "secp256r1": {
13546 "p": "ffffffff00000001000000000000000000000000ffffffffffffffffffffffff",
13547 "a": "ffffffff00000001000000000000000000000000fffffffffffffffffffffffc",
13548 "b": "5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b",
13549 "n": "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551",
13550 "h": "01",
13551 "Gx": "6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296",
13552 "Gy": "4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"
13553 }
13554}
13555
13556},{}],66:[function(require,module,exports){
13557var Point = require('./point')
13558var Curve = require('./curve')
13559
13560var getCurveByName = require('./names')
13561
13562module.exports = {
13563 Curve: Curve,
13564 Point: Point,
13565 getCurveByName: getCurveByName
13566}
13567
13568},{"./curve":64,"./names":67,"./point":68}],67:[function(require,module,exports){
13569var BigInteger = require('bigi')
13570
13571var curves = require('./curves.json')
13572var Curve = require('./curve')
13573
13574function getCurveByName (name) {
13575 var curve = curves[name]
13576 if (!curve) return null
13577
13578 var p = new BigInteger(curve.p, 16)
13579 var a = new BigInteger(curve.a, 16)
13580 var b = new BigInteger(curve.b, 16)
13581 var n = new BigInteger(curve.n, 16)
13582 var h = new BigInteger(curve.h, 16)
13583 var Gx = new BigInteger(curve.Gx, 16)
13584 var Gy = new BigInteger(curve.Gy, 16)
13585
13586 return new Curve(p, a, b, Gx, Gy, n, h)
13587}
13588
13589module.exports = getCurveByName
13590
13591},{"./curve":64,"./curves.json":65,"bigi":38}],68:[function(require,module,exports){
13592(function (Buffer){
13593var assert = require('assert')
13594var BigInteger = require('bigi')
13595
13596var THREE = BigInteger.valueOf(3)
13597
13598function Point (curve, x, y, z) {
13599 assert.notStrictEqual(z, undefined, 'Missing Z coordinate')
13600
13601 this.curve = curve
13602 this.x = x
13603 this.y = y
13604 this.z = z
13605 this._zInv = null
13606
13607 this.compressed = true
13608}
13609
13610Object.defineProperty(Point.prototype, 'zInv', {
13611 get: function () {
13612 if (this._zInv === null) {
13613 this._zInv = this.z.modInverse(this.curve.p)
13614 }
13615
13616 return this._zInv
13617 }
13618})
13619
13620Object.defineProperty(Point.prototype, 'affineX', {
13621 get: function () {
13622 return this.x.multiply(this.zInv).mod(this.curve.p)
13623 }
13624})
13625
13626Object.defineProperty(Point.prototype, 'affineY', {
13627 get: function () {
13628 return this.y.multiply(this.zInv).mod(this.curve.p)
13629 }
13630})
13631
13632Point.fromAffine = function (curve, x, y) {
13633 return new Point(curve, x, y, BigInteger.ONE)
13634}
13635
13636Point.prototype.equals = function (other) {
13637 if (other === this) return true
13638 if (this.curve.isInfinity(this)) return this.curve.isInfinity(other)
13639 if (this.curve.isInfinity(other)) return this.curve.isInfinity(this)
13640
13641 // u = Y2 * Z1 - Y1 * Z2
13642 var u = other.y.multiply(this.z).subtract(this.y.multiply(other.z)).mod(this.curve.p)
13643
13644 if (u.signum() !== 0) return false
13645
13646 // v = X2 * Z1 - X1 * Z2
13647 var v = other.x.multiply(this.z).subtract(this.x.multiply(other.z)).mod(this.curve.p)
13648
13649 return v.signum() === 0
13650}
13651
13652Point.prototype.negate = function () {
13653 var y = this.curve.p.subtract(this.y)
13654
13655 return new Point(this.curve, this.x, y, this.z)
13656}
13657
13658Point.prototype.add = function (b) {
13659 if (this.curve.isInfinity(this)) return b
13660 if (this.curve.isInfinity(b)) return this
13661
13662 var x1 = this.x
13663 var y1 = this.y
13664 var x2 = b.x
13665 var y2 = b.y
13666
13667 // u = Y2 * Z1 - Y1 * Z2
13668 var u = y2.multiply(this.z).subtract(y1.multiply(b.z)).mod(this.curve.p)
13669 // v = X2 * Z1 - X1 * Z2
13670 var v = x2.multiply(this.z).subtract(x1.multiply(b.z)).mod(this.curve.p)
13671
13672 if (v.signum() === 0) {
13673 if (u.signum() === 0) {
13674 return this.twice() // this == b, so double
13675 }
13676
13677 return this.curve.infinity // this = -b, so infinity
13678 }
13679
13680 var v2 = v.square()
13681 var v3 = v2.multiply(v)
13682 var x1v2 = x1.multiply(v2)
13683 var zu2 = u.square().multiply(this.z)
13684
13685 // x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3)
13686 var x3 = zu2.subtract(x1v2.shiftLeft(1)).multiply(b.z).subtract(v3).multiply(v).mod(this.curve.p)
13687 // y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3
13688 var y3 = x1v2.multiply(THREE).multiply(u).subtract(y1.multiply(v3)).subtract(zu2.multiply(u)).multiply(b.z).add(u.multiply(v3)).mod(this.curve.p)
13689 // z3 = v^3 * z1 * z2
13690 var z3 = v3.multiply(this.z).multiply(b.z).mod(this.curve.p)
13691
13692 return new Point(this.curve, x3, y3, z3)
13693}
13694
13695Point.prototype.twice = function () {
13696 if (this.curve.isInfinity(this)) return this
13697 if (this.y.signum() === 0) return this.curve.infinity
13698
13699 var x1 = this.x
13700 var y1 = this.y
13701
13702 var y1z1 = y1.multiply(this.z).mod(this.curve.p)
13703 var y1sqz1 = y1z1.multiply(y1).mod(this.curve.p)
13704 var a = this.curve.a
13705
13706 // w = 3 * x1^2 + a * z1^2
13707 var w = x1.square().multiply(THREE)
13708
13709 if (a.signum() !== 0) {
13710 w = w.add(this.z.square().multiply(a))
13711 }
13712
13713 w = w.mod(this.curve.p)
13714 // x3 = 2 * y1 * z1 * (w^2 - 8 * x1 * y1^2 * z1)
13715 var x3 = w.square().subtract(x1.shiftLeft(3).multiply(y1sqz1)).shiftLeft(1).multiply(y1z1).mod(this.curve.p)
13716 // y3 = 4 * y1^2 * z1 * (3 * w * x1 - 2 * y1^2 * z1) - w^3
13717 var y3 = w.multiply(THREE).multiply(x1).subtract(y1sqz1.shiftLeft(1)).shiftLeft(2).multiply(y1sqz1).subtract(w.pow(3)).mod(this.curve.p)
13718 // z3 = 8 * (y1 * z1)^3
13719 var z3 = y1z1.pow(3).shiftLeft(3).mod(this.curve.p)
13720
13721 return new Point(this.curve, x3, y3, z3)
13722}
13723
13724// Simple NAF (Non-Adjacent Form) multiplication algorithm
13725// TODO: modularize the multiplication algorithm
13726Point.prototype.multiply = function (k) {
13727 if (this.curve.isInfinity(this)) return this
13728 if (k.signum() === 0) return this.curve.infinity
13729
13730 var e = k
13731 var h = e.multiply(THREE)
13732
13733 var neg = this.negate()
13734 var R = this
13735
13736 for (var i = h.bitLength() - 2; i > 0; --i) {
13737 var hBit = h.testBit(i)
13738 var eBit = e.testBit(i)
13739
13740 R = R.twice()
13741
13742 if (hBit !== eBit) {
13743 R = R.add(hBit ? this : neg)
13744 }
13745 }
13746
13747 return R
13748}
13749
13750// Compute this*j + x*k (simultaneous multiplication)
13751Point.prototype.multiplyTwo = function (j, x, k) {
13752 var i = Math.max(j.bitLength(), k.bitLength()) - 1
13753 var R = this.curve.infinity
13754 var both = this.add(x)
13755
13756 while (i >= 0) {
13757 var jBit = j.testBit(i)
13758 var kBit = k.testBit(i)
13759
13760 R = R.twice()
13761
13762 if (jBit) {
13763 if (kBit) {
13764 R = R.add(both)
13765 } else {
13766 R = R.add(this)
13767 }
13768 } else if (kBit) {
13769 R = R.add(x)
13770 }
13771 --i
13772 }
13773
13774 return R
13775}
13776
13777Point.prototype.getEncoded = function (compressed) {
13778 if (compressed == null) compressed = this.compressed
13779 if (this.curve.isInfinity(this)) return new Buffer('00', 'hex') // Infinity point encoded is simply '00'
13780
13781 var x = this.affineX
13782 var y = this.affineY
13783 var byteLength = this.curve.pLength
13784 var buffer
13785
13786 // 0x02/0x03 | X
13787 if (compressed) {
13788 buffer = new Buffer(1 + byteLength)
13789 buffer.writeUInt8(y.isEven() ? 0x02 : 0x03, 0)
13790
13791 // 0x04 | X | Y
13792 } else {
13793 buffer = new Buffer(1 + byteLength + byteLength)
13794 buffer.writeUInt8(0x04, 0)
13795
13796 y.toBuffer(byteLength).copy(buffer, 1 + byteLength)
13797 }
13798
13799 x.toBuffer(byteLength).copy(buffer, 1)
13800
13801 return buffer
13802}
13803
13804Point.decodeFrom = function (curve, buffer) {
13805 var type = buffer.readUInt8(0)
13806 var compressed = (type !== 4)
13807
13808 var byteLength = Math.floor((curve.p.bitLength() + 7) / 8)
13809 var x = BigInteger.fromBuffer(buffer.slice(1, 1 + byteLength))
13810
13811 var Q
13812 if (compressed) {
13813 assert.equal(buffer.length, byteLength + 1, 'Invalid sequence length')
13814 assert(type === 0x02 || type === 0x03, 'Invalid sequence tag')
13815
13816 var isOdd = (type === 0x03)
13817 Q = curve.pointFromX(isOdd, x)
13818 } else {
13819 assert.equal(buffer.length, 1 + byteLength + byteLength, 'Invalid sequence length')
13820
13821 var y = BigInteger.fromBuffer(buffer.slice(1 + byteLength))
13822 Q = Point.fromAffine(curve, x, y)
13823 }
13824
13825 Q.compressed = compressed
13826 return Q
13827}
13828
13829Point.prototype.toString = function () {
13830 if (this.curve.isInfinity(this)) return '(INFINITY)'
13831
13832 return '(' + this.affineX.toString() + ',' + this.affineY.toString() + ')'
13833}
13834
13835module.exports = Point
13836
13837}).call(this,require("buffer").Buffer)
13838},{"assert":1,"bigi":38,"buffer":5}],69:[function(require,module,exports){
13839(function (Buffer){
13840var md5 = require('create-hash/md5')
13841module.exports = EVP_BytesToKey
13842function EVP_BytesToKey (password, salt, keyLen, ivLen) {
13843 if (!Buffer.isBuffer(password)) {
13844 password = new Buffer(password, 'binary')
13845 }
13846 if (salt && !Buffer.isBuffer(salt)) {
13847 salt = new Buffer(salt, 'binary')
13848 }
13849 keyLen = keyLen / 8
13850 ivLen = ivLen || 0
13851 var ki = 0
13852 var ii = 0
13853 var key = new Buffer(keyLen)
13854 var iv = new Buffer(ivLen)
13855 var addmd = 0
13856 var md_buf
13857 var i
13858 var bufs = []
13859 while (true) {
13860 if (addmd++ > 0) {
13861 bufs.push(md_buf)
13862 }
13863 bufs.push(password)
13864 if (salt) {
13865 bufs.push(salt)
13866 }
13867 md_buf = md5(Buffer.concat(bufs))
13868 bufs = []
13869 i = 0
13870 if (keyLen > 0) {
13871 while (true) {
13872 if (keyLen === 0) {
13873 break
13874 }
13875 if (i === md_buf.length) {
13876 break
13877 }
13878 key[ki++] = md_buf[i]
13879 keyLen--
13880 i++
13881 }
13882 }
13883 if (ivLen > 0 && i !== md_buf.length) {
13884 while (true) {
13885 if (ivLen === 0) {
13886 break
13887 }
13888 if (i === md_buf.length) {
13889 break
13890 }
13891 iv[ii++] = md_buf[i]
13892 ivLen--
13893 i++
13894 }
13895 }
13896 if (keyLen === 0 && ivLen === 0) {
13897 break
13898 }
13899 }
13900 for (i = 0; i < md_buf.length; i++) {
13901 md_buf[i] = 0
13902 }
13903 return {
13904 key: key,
13905 iv: iv
13906 }
13907}
13908
13909}).call(this,require("buffer").Buffer)
13910},{"buffer":5,"create-hash/md5":61}],70:[function(require,module,exports){
13911(function (Buffer){
13912'use strict'
13913var Transform = require('stream').Transform
13914var inherits = require('inherits')
13915
13916function HashBase (blockSize) {
13917 Transform.call(this)
13918
13919 this._block = new Buffer(blockSize)
13920 this._blockSize = blockSize
13921 this._blockOffset = 0
13922 this._length = [0, 0, 0, 0]
13923
13924 this._finalized = false
13925}
13926
13927inherits(HashBase, Transform)
13928
13929HashBase.prototype._transform = function (chunk, encoding, callback) {
13930 var error = null
13931 try {
13932 if (encoding !== 'buffer') chunk = new Buffer(chunk, encoding)
13933 this.update(chunk)
13934 } catch (err) {
13935 error = err
13936 }
13937
13938 callback(error)
13939}
13940
13941HashBase.prototype._flush = function (callback) {
13942 var error = null
13943 try {
13944 this.push(this._digest())
13945 } catch (err) {
13946 error = err
13947 }
13948
13949 callback(error)
13950}
13951
13952HashBase.prototype.update = function (data, encoding) {
13953 if (!Buffer.isBuffer(data) && typeof data !== 'string') throw new TypeError('Data must be a string or a buffer')
13954 if (this._finalized) throw new Error('Digest already called')
13955 if (!Buffer.isBuffer(data)) data = new Buffer(data, encoding || 'binary')
13956
13957 // consume data
13958 var block = this._block
13959 var offset = 0
13960 while (this._blockOffset + data.length - offset >= this._blockSize) {
13961 for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]
13962 this._update()
13963 this._blockOffset = 0
13964 }
13965 while (offset < data.length) block[this._blockOffset++] = data[offset++]
13966
13967 // update length
13968 for (var j = 0, carry = data.length * 8; carry > 0; ++j) {
13969 this._length[j] += carry
13970 carry = (this._length[j] / 0x0100000000) | 0
13971 if (carry > 0) this._length[j] -= 0x0100000000 * carry
13972 }
13973
13974 return this
13975}
13976
13977HashBase.prototype._update = function (data) {
13978 throw new Error('_update is not implemented')
13979}
13980
13981HashBase.prototype.digest = function (encoding) {
13982 if (this._finalized) throw new Error('Digest already called')
13983 this._finalized = true
13984
13985 var digest = this._digest()
13986 if (encoding !== undefined) digest = digest.toString(encoding)
13987 return digest
13988}
13989
13990HashBase.prototype._digest = function () {
13991 throw new Error('_digest is not implemented')
13992}
13993
13994module.exports = HashBase
13995
13996}).call(this,require("buffer").Buffer)
13997},{"buffer":5,"inherits":71,"stream":28}],71:[function(require,module,exports){
13998arguments[4][9][0].apply(exports,arguments)
13999},{"dup":9}],72:[function(require,module,exports){
14000/*
14001 Copyright 2013 Daniel Wirtz <dcode@dcode.io>
14002 Copyright 2009 The Closure Library Authors. All Rights Reserved.
14003
14004 Licensed under the Apache License, Version 2.0 (the "License");
14005 you may not use this file except in compliance with the License.
14006 You may obtain a copy of the License at
14007
14008 http://www.apache.org/licenses/LICENSE-2.0
14009
14010 Unless required by applicable law or agreed to in writing, software
14011 distributed under the License is distributed on an "AS-IS" BASIS,
14012 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14013 See the License for the specific language governing permissions and
14014 limitations under the License.
14015 */
14016
14017/**
14018 * @license long.js (c) 2013 Daniel Wirtz <dcode@dcode.io>
14019 * Released under the Apache License, Version 2.0
14020 * see: https://github.com/dcodeIO/long.js for details
14021 */
14022(function(global, factory) {
14023
14024 /* AMD */ if (typeof define === 'function' && define["amd"])
14025 define([], factory);
14026 /* CommonJS */ else if (typeof require === 'function' && typeof module === "object" && module && module["exports"])
14027 module["exports"] = factory();
14028 /* Global */ else
14029 (global["dcodeIO"] = global["dcodeIO"] || {})["Long"] = factory();
14030
14031})(this, function() {
14032 "use strict";
14033
14034 /**
14035 * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers.
14036 * See the from* functions below for more convenient ways of constructing Longs.
14037 * @exports Long
14038 * @class A Long class for representing a 64 bit two's-complement integer value.
14039 * @param {number} low The low (signed) 32 bits of the long
14040 * @param {number} high The high (signed) 32 bits of the long
14041 * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
14042 * @constructor
14043 */
14044 function Long(low, high, unsigned) {
14045
14046 /**
14047 * The low 32 bits as a signed value.
14048 * @type {number}
14049 */
14050 this.low = low | 0;
14051
14052 /**
14053 * The high 32 bits as a signed value.
14054 * @type {number}
14055 */
14056 this.high = high | 0;
14057
14058 /**
14059 * Whether unsigned or not.
14060 * @type {boolean}
14061 */
14062 this.unsigned = !!unsigned;
14063 }
14064
14065 // The internal representation of a long is the two given signed, 32-bit values.
14066 // We use 32-bit pieces because these are the size of integers on which
14067 // Javascript performs bit-operations. For operations like addition and
14068 // multiplication, we split each number into 16 bit pieces, which can easily be
14069 // multiplied within Javascript's floating-point representation without overflow
14070 // or change in sign.
14071 //
14072 // In the algorithms below, we frequently reduce the negative case to the
14073 // positive case by negating the input(s) and then post-processing the result.
14074 // Note that we must ALWAYS check specially whether those values are MIN_VALUE
14075 // (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as
14076 // a positive number, it overflows back into a negative). Not handling this
14077 // case would often result in infinite recursion.
14078 //
14079 // Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the from*
14080 // methods on which they depend.
14081
14082 /**
14083 * An indicator used to reliably determine if an object is a Long or not.
14084 * @type {boolean}
14085 * @const
14086 * @private
14087 */
14088 Long.prototype.__isLong__;
14089
14090 Object.defineProperty(Long.prototype, "__isLong__", {
14091 value: true,
14092 enumerable: false,
14093 configurable: false
14094 });
14095
14096 /**
14097 * @function
14098 * @param {*} obj Object
14099 * @returns {boolean}
14100 * @inner
14101 */
14102 function isLong(obj) {
14103 return (obj && obj["__isLong__"]) === true;
14104 }
14105
14106 /**
14107 * Tests if the specified object is a Long.
14108 * @function
14109 * @param {*} obj Object
14110 * @returns {boolean}
14111 */
14112 Long.isLong = isLong;
14113
14114 /**
14115 * A cache of the Long representations of small integer values.
14116 * @type {!Object}
14117 * @inner
14118 */
14119 var INT_CACHE = {};
14120
14121 /**
14122 * A cache of the Long representations of small unsigned integer values.
14123 * @type {!Object}
14124 * @inner
14125 */
14126 var UINT_CACHE = {};
14127
14128 /**
14129 * @param {number} value
14130 * @param {boolean=} unsigned
14131 * @returns {!Long}
14132 * @inner
14133 */
14134 function fromInt(value, unsigned) {
14135 var obj, cachedObj, cache;
14136 if (unsigned) {
14137 value >>>= 0;
14138 if (cache = (0 <= value && value < 256)) {
14139 cachedObj = UINT_CACHE[value];
14140 if (cachedObj)
14141 return cachedObj;
14142 }
14143 obj = fromBits(value, (value | 0) < 0 ? -1 : 0, true);
14144 if (cache)
14145 UINT_CACHE[value] = obj;
14146 return obj;
14147 } else {
14148 value |= 0;
14149 if (cache = (-128 <= value && value < 128)) {
14150 cachedObj = INT_CACHE[value];
14151 if (cachedObj)
14152 return cachedObj;
14153 }
14154 obj = fromBits(value, value < 0 ? -1 : 0, false);
14155 if (cache)
14156 INT_CACHE[value] = obj;
14157 return obj;
14158 }
14159 }
14160
14161 /**
14162 * Returns a Long representing the given 32 bit integer value.
14163 * @function
14164 * @param {number} value The 32 bit integer in question
14165 * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
14166 * @returns {!Long} The corresponding Long value
14167 */
14168 Long.fromInt = fromInt;
14169
14170 /**
14171 * @param {number} value
14172 * @param {boolean=} unsigned
14173 * @returns {!Long}
14174 * @inner
14175 */
14176 function fromNumber(value, unsigned) {
14177 if (isNaN(value) || !isFinite(value))
14178 return unsigned ? UZERO : ZERO;
14179 if (unsigned) {
14180 if (value < 0)
14181 return UZERO;
14182 if (value >= TWO_PWR_64_DBL)
14183 return MAX_UNSIGNED_VALUE;
14184 } else {
14185 if (value <= -TWO_PWR_63_DBL)
14186 return MIN_VALUE;
14187 if (value + 1 >= TWO_PWR_63_DBL)
14188 return MAX_VALUE;
14189 }
14190 if (value < 0)
14191 return fromNumber(-value, unsigned).neg();
14192 return fromBits((value % TWO_PWR_32_DBL) | 0, (value / TWO_PWR_32_DBL) | 0, unsigned);
14193 }
14194
14195 /**
14196 * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.
14197 * @function
14198 * @param {number} value The number in question
14199 * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
14200 * @returns {!Long} The corresponding Long value
14201 */
14202 Long.fromNumber = fromNumber;
14203
14204 /**
14205 * @param {number} lowBits
14206 * @param {number} highBits
14207 * @param {boolean=} unsigned
14208 * @returns {!Long}
14209 * @inner
14210 */
14211 function fromBits(lowBits, highBits, unsigned) {
14212 return new Long(lowBits, highBits, unsigned);
14213 }
14214
14215 /**
14216 * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is
14217 * assumed to use 32 bits.
14218 * @function
14219 * @param {number} lowBits The low 32 bits
14220 * @param {number} highBits The high 32 bits
14221 * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
14222 * @returns {!Long} The corresponding Long value
14223 */
14224 Long.fromBits = fromBits;
14225
14226 /**
14227 * @function
14228 * @param {number} base
14229 * @param {number} exponent
14230 * @returns {number}
14231 * @inner
14232 */
14233 var pow_dbl = Math.pow; // Used 4 times (4*8 to 15+4)
14234
14235 /**
14236 * @param {string} str
14237 * @param {(boolean|number)=} unsigned
14238 * @param {number=} radix
14239 * @returns {!Long}
14240 * @inner
14241 */
14242 function fromString(str, unsigned, radix) {
14243 if (str.length === 0)
14244 throw Error('empty string');
14245 if (str === "NaN" || str === "Infinity" || str === "+Infinity" || str === "-Infinity")
14246 return ZERO;
14247 if (typeof unsigned === 'number') {
14248 // For goog.math.long compatibility
14249 radix = unsigned,
14250 unsigned = false;
14251 } else {
14252 unsigned = !! unsigned;
14253 }
14254 radix = radix || 10;
14255 if (radix < 2 || 36 < radix)
14256 throw RangeError('radix');
14257
14258 var p;
14259 if ((p = str.indexOf('-')) > 0)
14260 throw Error('interior hyphen');
14261 else if (p === 0) {
14262 return fromString(str.substring(1), unsigned, radix).neg();
14263 }
14264
14265 // Do several (8) digits each time through the loop, so as to
14266 // minimize the calls to the very expensive emulated div.
14267 var radixToPower = fromNumber(pow_dbl(radix, 8));
14268
14269 var result = ZERO;
14270 for (var i = 0; i < str.length; i += 8) {
14271 var size = Math.min(8, str.length - i),
14272 value = parseInt(str.substring(i, i + size), radix);
14273 if (size < 8) {
14274 var power = fromNumber(pow_dbl(radix, size));
14275 result = result.mul(power).add(fromNumber(value));
14276 } else {
14277 result = result.mul(radixToPower);
14278 result = result.add(fromNumber(value));
14279 }
14280 }
14281 result.unsigned = unsigned;
14282 return result;
14283 }
14284
14285 /**
14286 * Returns a Long representation of the given string, written using the specified radix.
14287 * @function
14288 * @param {string} str The textual representation of the Long
14289 * @param {(boolean|number)=} unsigned Whether unsigned or not, defaults to `false` for signed
14290 * @param {number=} radix The radix in which the text is written (2-36), defaults to 10
14291 * @returns {!Long} The corresponding Long value
14292 */
14293 Long.fromString = fromString;
14294
14295 /**
14296 * @function
14297 * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val
14298 * @returns {!Long}
14299 * @inner
14300 */
14301 function fromValue(val) {
14302 if (val /* is compatible */ instanceof Long)
14303 return val;
14304 if (typeof val === 'number')
14305 return fromNumber(val);
14306 if (typeof val === 'string')
14307 return fromString(val);
14308 // Throws for non-objects, converts non-instanceof Long:
14309 return fromBits(val.low, val.high, val.unsigned);
14310 }
14311
14312 /**
14313 * Converts the specified value to a Long.
14314 * @function
14315 * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val Value
14316 * @returns {!Long}
14317 */
14318 Long.fromValue = fromValue;
14319
14320 // NOTE: the compiler should inline these constant values below and then remove these variables, so there should be
14321 // no runtime penalty for these.
14322
14323 /**
14324 * @type {number}
14325 * @const
14326 * @inner
14327 */
14328 var TWO_PWR_16_DBL = 1 << 16;
14329
14330 /**
14331 * @type {number}
14332 * @const
14333 * @inner
14334 */
14335 var TWO_PWR_24_DBL = 1 << 24;
14336
14337 /**
14338 * @type {number}
14339 * @const
14340 * @inner
14341 */
14342 var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;
14343
14344 /**
14345 * @type {number}
14346 * @const
14347 * @inner
14348 */
14349 var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;
14350
14351 /**
14352 * @type {number}
14353 * @const
14354 * @inner
14355 */
14356 var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;
14357
14358 /**
14359 * @type {!Long}
14360 * @const
14361 * @inner
14362 */
14363 var TWO_PWR_24 = fromInt(TWO_PWR_24_DBL);
14364
14365 /**
14366 * @type {!Long}
14367 * @inner
14368 */
14369 var ZERO = fromInt(0);
14370
14371 /**
14372 * Signed zero.
14373 * @type {!Long}
14374 */
14375 Long.ZERO = ZERO;
14376
14377 /**
14378 * @type {!Long}
14379 * @inner
14380 */
14381 var UZERO = fromInt(0, true);
14382
14383 /**
14384 * Unsigned zero.
14385 * @type {!Long}
14386 */
14387 Long.UZERO = UZERO;
14388
14389 /**
14390 * @type {!Long}
14391 * @inner
14392 */
14393 var ONE = fromInt(1);
14394
14395 /**
14396 * Signed one.
14397 * @type {!Long}
14398 */
14399 Long.ONE = ONE;
14400
14401 /**
14402 * @type {!Long}
14403 * @inner
14404 */
14405 var UONE = fromInt(1, true);
14406
14407 /**
14408 * Unsigned one.
14409 * @type {!Long}
14410 */
14411 Long.UONE = UONE;
14412
14413 /**
14414 * @type {!Long}
14415 * @inner
14416 */
14417 var NEG_ONE = fromInt(-1);
14418
14419 /**
14420 * Signed negative one.
14421 * @type {!Long}
14422 */
14423 Long.NEG_ONE = NEG_ONE;
14424
14425 /**
14426 * @type {!Long}
14427 * @inner
14428 */
14429 var MAX_VALUE = fromBits(0xFFFFFFFF|0, 0x7FFFFFFF|0, false);
14430
14431 /**
14432 * Maximum signed value.
14433 * @type {!Long}
14434 */
14435 Long.MAX_VALUE = MAX_VALUE;
14436
14437 /**
14438 * @type {!Long}
14439 * @inner
14440 */
14441 var MAX_UNSIGNED_VALUE = fromBits(0xFFFFFFFF|0, 0xFFFFFFFF|0, true);
14442
14443 /**
14444 * Maximum unsigned value.
14445 * @type {!Long}
14446 */
14447 Long.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE;
14448
14449 /**
14450 * @type {!Long}
14451 * @inner
14452 */
14453 var MIN_VALUE = fromBits(0, 0x80000000|0, false);
14454
14455 /**
14456 * Minimum signed value.
14457 * @type {!Long}
14458 */
14459 Long.MIN_VALUE = MIN_VALUE;
14460
14461 /**
14462 * @alias Long.prototype
14463 * @inner
14464 */
14465 var LongPrototype = Long.prototype;
14466
14467 /**
14468 * Converts the Long to a 32 bit integer, assuming it is a 32 bit integer.
14469 * @returns {number}
14470 */
14471 LongPrototype.toInt = function toInt() {
14472 return this.unsigned ? this.low >>> 0 : this.low;
14473 };
14474
14475 /**
14476 * Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa).
14477 * @returns {number}
14478 */
14479 LongPrototype.toNumber = function toNumber() {
14480 if (this.unsigned)
14481 return ((this.high >>> 0) * TWO_PWR_32_DBL) + (this.low >>> 0);
14482 return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
14483 };
14484
14485 /**
14486 * Converts the Long to a string written in the specified radix.
14487 * @param {number=} radix Radix (2-36), defaults to 10
14488 * @returns {string}
14489 * @override
14490 * @throws {RangeError} If `radix` is out of range
14491 */
14492 LongPrototype.toString = function toString(radix) {
14493 radix = radix || 10;
14494 if (radix < 2 || 36 < radix)
14495 throw RangeError('radix');
14496 if (this.isZero())
14497 return '0';
14498 if (this.isNegative()) { // Unsigned Longs are never negative
14499 if (this.eq(MIN_VALUE)) {
14500 // We need to change the Long value before it can be negated, so we remove
14501 // the bottom-most digit in this base and then recurse to do the rest.
14502 var radixLong = fromNumber(radix),
14503 div = this.div(radixLong),
14504 rem1 = div.mul(radixLong).sub(this);
14505 return div.toString(radix) + rem1.toInt().toString(radix);
14506 } else
14507 return '-' + this.neg().toString(radix);
14508 }
14509
14510 // Do several (6) digits each time through the loop, so as to
14511 // minimize the calls to the very expensive emulated div.
14512 var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned),
14513 rem = this;
14514 var result = '';
14515 while (true) {
14516 var remDiv = rem.div(radixToPower),
14517 intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0,
14518 digits = intval.toString(radix);
14519 rem = remDiv;
14520 if (rem.isZero())
14521 return digits + result;
14522 else {
14523 while (digits.length < 6)
14524 digits = '0' + digits;
14525 result = '' + digits + result;
14526 }
14527 }
14528 };
14529
14530 /**
14531 * Gets the high 32 bits as a signed integer.
14532 * @returns {number} Signed high bits
14533 */
14534 LongPrototype.getHighBits = function getHighBits() {
14535 return this.high;
14536 };
14537
14538 /**
14539 * Gets the high 32 bits as an unsigned integer.
14540 * @returns {number} Unsigned high bits
14541 */
14542 LongPrototype.getHighBitsUnsigned = function getHighBitsUnsigned() {
14543 return this.high >>> 0;
14544 };
14545
14546 /**
14547 * Gets the low 32 bits as a signed integer.
14548 * @returns {number} Signed low bits
14549 */
14550 LongPrototype.getLowBits = function getLowBits() {
14551 return this.low;
14552 };
14553
14554 /**
14555 * Gets the low 32 bits as an unsigned integer.
14556 * @returns {number} Unsigned low bits
14557 */
14558 LongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() {
14559 return this.low >>> 0;
14560 };
14561
14562 /**
14563 * Gets the number of bits needed to represent the absolute value of this Long.
14564 * @returns {number}
14565 */
14566 LongPrototype.getNumBitsAbs = function getNumBitsAbs() {
14567 if (this.isNegative()) // Unsigned Longs are never negative
14568 return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();
14569 var val = this.high != 0 ? this.high : this.low;
14570 for (var bit = 31; bit > 0; bit--)
14571 if ((val & (1 << bit)) != 0)
14572 break;
14573 return this.high != 0 ? bit + 33 : bit + 1;
14574 };
14575
14576 /**
14577 * Tests if this Long's value equals zero.
14578 * @returns {boolean}
14579 */
14580 LongPrototype.isZero = function isZero() {
14581 return this.high === 0 && this.low === 0;
14582 };
14583
14584 /**
14585 * Tests if this Long's value is negative.
14586 * @returns {boolean}
14587 */
14588 LongPrototype.isNegative = function isNegative() {
14589 return !this.unsigned && this.high < 0;
14590 };
14591
14592 /**
14593 * Tests if this Long's value is positive.
14594 * @returns {boolean}
14595 */
14596 LongPrototype.isPositive = function isPositive() {
14597 return this.unsigned || this.high >= 0;
14598 };
14599
14600 /**
14601 * Tests if this Long's value is odd.
14602 * @returns {boolean}
14603 */
14604 LongPrototype.isOdd = function isOdd() {
14605 return (this.low & 1) === 1;
14606 };
14607
14608 /**
14609 * Tests if this Long's value is even.
14610 * @returns {boolean}
14611 */
14612 LongPrototype.isEven = function isEven() {
14613 return (this.low & 1) === 0;
14614 };
14615
14616 /**
14617 * Tests if this Long's value equals the specified's.
14618 * @param {!Long|number|string} other Other value
14619 * @returns {boolean}
14620 */
14621 LongPrototype.equals = function equals(other) {
14622 if (!isLong(other))
14623 other = fromValue(other);
14624 if (this.unsigned !== other.unsigned && (this.high >>> 31) === 1 && (other.high >>> 31) === 1)
14625 return false;
14626 return this.high === other.high && this.low === other.low;
14627 };
14628
14629 /**
14630 * Tests if this Long's value equals the specified's. This is an alias of {@link Long#equals}.
14631 * @function
14632 * @param {!Long|number|string} other Other value
14633 * @returns {boolean}
14634 */
14635 LongPrototype.eq = LongPrototype.equals;
14636
14637 /**
14638 * Tests if this Long's value differs from the specified's.
14639 * @param {!Long|number|string} other Other value
14640 * @returns {boolean}
14641 */
14642 LongPrototype.notEquals = function notEquals(other) {
14643 return !this.eq(/* validates */ other);
14644 };
14645
14646 /**
14647 * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}.
14648 * @function
14649 * @param {!Long|number|string} other Other value
14650 * @returns {boolean}
14651 */
14652 LongPrototype.neq = LongPrototype.notEquals;
14653
14654 /**
14655 * Tests if this Long's value is less than the specified's.
14656 * @param {!Long|number|string} other Other value
14657 * @returns {boolean}
14658 */
14659 LongPrototype.lessThan = function lessThan(other) {
14660 return this.comp(/* validates */ other) < 0;
14661 };
14662
14663 /**
14664 * Tests if this Long's value is less than the specified's. This is an alias of {@link Long#lessThan}.
14665 * @function
14666 * @param {!Long|number|string} other Other value
14667 * @returns {boolean}
14668 */
14669 LongPrototype.lt = LongPrototype.lessThan;
14670
14671 /**
14672 * Tests if this Long's value is less than or equal the specified's.
14673 * @param {!Long|number|string} other Other value
14674 * @returns {boolean}
14675 */
14676 LongPrototype.lessThanOrEqual = function lessThanOrEqual(other) {
14677 return this.comp(/* validates */ other) <= 0;
14678 };
14679
14680 /**
14681 * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}.
14682 * @function
14683 * @param {!Long|number|string} other Other value
14684 * @returns {boolean}
14685 */
14686 LongPrototype.lte = LongPrototype.lessThanOrEqual;
14687
14688 /**
14689 * Tests if this Long's value is greater than the specified's.
14690 * @param {!Long|number|string} other Other value
14691 * @returns {boolean}
14692 */
14693 LongPrototype.greaterThan = function greaterThan(other) {
14694 return this.comp(/* validates */ other) > 0;
14695 };
14696
14697 /**
14698 * Tests if this Long's value is greater than the specified's. This is an alias of {@link Long#greaterThan}.
14699 * @function
14700 * @param {!Long|number|string} other Other value
14701 * @returns {boolean}
14702 */
14703 LongPrototype.gt = LongPrototype.greaterThan;
14704
14705 /**
14706 * Tests if this Long's value is greater than or equal the specified's.
14707 * @param {!Long|number|string} other Other value
14708 * @returns {boolean}
14709 */
14710 LongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) {
14711 return this.comp(/* validates */ other) >= 0;
14712 };
14713
14714 /**
14715 * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}.
14716 * @function
14717 * @param {!Long|number|string} other Other value
14718 * @returns {boolean}
14719 */
14720 LongPrototype.gte = LongPrototype.greaterThanOrEqual;
14721
14722 /**
14723 * Compares this Long's value with the specified's.
14724 * @param {!Long|number|string} other Other value
14725 * @returns {number} 0 if they are the same, 1 if the this is greater and -1
14726 * if the given one is greater
14727 */
14728 LongPrototype.compare = function compare(other) {
14729 if (!isLong(other))
14730 other = fromValue(other);
14731 if (this.eq(other))
14732 return 0;
14733 var thisNeg = this.isNegative(),
14734 otherNeg = other.isNegative();
14735 if (thisNeg && !otherNeg)
14736 return -1;
14737 if (!thisNeg && otherNeg)
14738 return 1;
14739 // At this point the sign bits are the same
14740 if (!this.unsigned)
14741 return this.sub(other).isNegative() ? -1 : 1;
14742 // Both are positive if at least one is unsigned
14743 return (other.high >>> 0) > (this.high >>> 0) || (other.high === this.high && (other.low >>> 0) > (this.low >>> 0)) ? -1 : 1;
14744 };
14745
14746 /**
14747 * Compares this Long's value with the specified's. This is an alias of {@link Long#compare}.
14748 * @function
14749 * @param {!Long|number|string} other Other value
14750 * @returns {number} 0 if they are the same, 1 if the this is greater and -1
14751 * if the given one is greater
14752 */
14753 LongPrototype.comp = LongPrototype.compare;
14754
14755 /**
14756 * Negates this Long's value.
14757 * @returns {!Long} Negated Long
14758 */
14759 LongPrototype.negate = function negate() {
14760 if (!this.unsigned && this.eq(MIN_VALUE))
14761 return MIN_VALUE;
14762 return this.not().add(ONE);
14763 };
14764
14765 /**
14766 * Negates this Long's value. This is an alias of {@link Long#negate}.
14767 * @function
14768 * @returns {!Long} Negated Long
14769 */
14770 LongPrototype.neg = LongPrototype.negate;
14771
14772 /**
14773 * Returns the sum of this and the specified Long.
14774 * @param {!Long|number|string} addend Addend
14775 * @returns {!Long} Sum
14776 */
14777 LongPrototype.add = function add(addend) {
14778 if (!isLong(addend))
14779 addend = fromValue(addend);
14780
14781 // Divide each number into 4 chunks of 16 bits, and then sum the chunks.
14782
14783 var a48 = this.high >>> 16;
14784 var a32 = this.high & 0xFFFF;
14785 var a16 = this.low >>> 16;
14786 var a00 = this.low & 0xFFFF;
14787
14788 var b48 = addend.high >>> 16;
14789 var b32 = addend.high & 0xFFFF;
14790 var b16 = addend.low >>> 16;
14791 var b00 = addend.low & 0xFFFF;
14792
14793 var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
14794 c00 += a00 + b00;
14795 c16 += c00 >>> 16;
14796 c00 &= 0xFFFF;
14797 c16 += a16 + b16;
14798 c32 += c16 >>> 16;
14799 c16 &= 0xFFFF;
14800 c32 += a32 + b32;
14801 c48 += c32 >>> 16;
14802 c32 &= 0xFFFF;
14803 c48 += a48 + b48;
14804 c48 &= 0xFFFF;
14805 return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
14806 };
14807
14808 /**
14809 * Returns the difference of this and the specified Long.
14810 * @param {!Long|number|string} subtrahend Subtrahend
14811 * @returns {!Long} Difference
14812 */
14813 LongPrototype.subtract = function subtract(subtrahend) {
14814 if (!isLong(subtrahend))
14815 subtrahend = fromValue(subtrahend);
14816 return this.add(subtrahend.neg());
14817 };
14818
14819 /**
14820 * Returns the difference of this and the specified Long. This is an alias of {@link Long#subtract}.
14821 * @function
14822 * @param {!Long|number|string} subtrahend Subtrahend
14823 * @returns {!Long} Difference
14824 */
14825 LongPrototype.sub = LongPrototype.subtract;
14826
14827 /**
14828 * Returns the product of this and the specified Long.
14829 * @param {!Long|number|string} multiplier Multiplier
14830 * @returns {!Long} Product
14831 */
14832 LongPrototype.multiply = function multiply(multiplier) {
14833 if (this.isZero())
14834 return ZERO;
14835 if (!isLong(multiplier))
14836 multiplier = fromValue(multiplier);
14837 if (multiplier.isZero())
14838 return ZERO;
14839 if (this.eq(MIN_VALUE))
14840 return multiplier.isOdd() ? MIN_VALUE : ZERO;
14841 if (multiplier.eq(MIN_VALUE))
14842 return this.isOdd() ? MIN_VALUE : ZERO;
14843
14844 if (this.isNegative()) {
14845 if (multiplier.isNegative())
14846 return this.neg().mul(multiplier.neg());
14847 else
14848 return this.neg().mul(multiplier).neg();
14849 } else if (multiplier.isNegative())
14850 return this.mul(multiplier.neg()).neg();
14851
14852 // If both longs are small, use float multiplication
14853 if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24))
14854 return fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);
14855
14856 // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products.
14857 // We can skip products that would overflow.
14858
14859 var a48 = this.high >>> 16;
14860 var a32 = this.high & 0xFFFF;
14861 var a16 = this.low >>> 16;
14862 var a00 = this.low & 0xFFFF;
14863
14864 var b48 = multiplier.high >>> 16;
14865 var b32 = multiplier.high & 0xFFFF;
14866 var b16 = multiplier.low >>> 16;
14867 var b00 = multiplier.low & 0xFFFF;
14868
14869 var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
14870 c00 += a00 * b00;
14871 c16 += c00 >>> 16;
14872 c00 &= 0xFFFF;
14873 c16 += a16 * b00;
14874 c32 += c16 >>> 16;
14875 c16 &= 0xFFFF;
14876 c16 += a00 * b16;
14877 c32 += c16 >>> 16;
14878 c16 &= 0xFFFF;
14879 c32 += a32 * b00;
14880 c48 += c32 >>> 16;
14881 c32 &= 0xFFFF;
14882 c32 += a16 * b16;
14883 c48 += c32 >>> 16;
14884 c32 &= 0xFFFF;
14885 c32 += a00 * b32;
14886 c48 += c32 >>> 16;
14887 c32 &= 0xFFFF;
14888 c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
14889 c48 &= 0xFFFF;
14890 return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
14891 };
14892
14893 /**
14894 * Returns the product of this and the specified Long. This is an alias of {@link Long#multiply}.
14895 * @function
14896 * @param {!Long|number|string} multiplier Multiplier
14897 * @returns {!Long} Product
14898 */
14899 LongPrototype.mul = LongPrototype.multiply;
14900
14901 /**
14902 * Returns this Long divided by the specified. The result is signed if this Long is signed or
14903 * unsigned if this Long is unsigned.
14904 * @param {!Long|number|string} divisor Divisor
14905 * @returns {!Long} Quotient
14906 */
14907 LongPrototype.divide = function divide(divisor) {
14908 if (!isLong(divisor))
14909 divisor = fromValue(divisor);
14910 if (divisor.isZero())
14911 throw Error('division by zero');
14912 if (this.isZero())
14913 return this.unsigned ? UZERO : ZERO;
14914 var approx, rem, res;
14915 if (!this.unsigned) {
14916 // This section is only relevant for signed longs and is derived from the
14917 // closure library as a whole.
14918 if (this.eq(MIN_VALUE)) {
14919 if (divisor.eq(ONE) || divisor.eq(NEG_ONE))
14920 return MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE
14921 else if (divisor.eq(MIN_VALUE))
14922 return ONE;
14923 else {
14924 // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.
14925 var halfThis = this.shr(1);
14926 approx = halfThis.div(divisor).shl(1);
14927 if (approx.eq(ZERO)) {
14928 return divisor.isNegative() ? ONE : NEG_ONE;
14929 } else {
14930 rem = this.sub(divisor.mul(approx));
14931 res = approx.add(rem.div(divisor));
14932 return res;
14933 }
14934 }
14935 } else if (divisor.eq(MIN_VALUE))
14936 return this.unsigned ? UZERO : ZERO;
14937 if (this.isNegative()) {
14938 if (divisor.isNegative())
14939 return this.neg().div(divisor.neg());
14940 return this.neg().div(divisor).neg();
14941 } else if (divisor.isNegative())
14942 return this.div(divisor.neg()).neg();
14943 res = ZERO;
14944 } else {
14945 // The algorithm below has not been made for unsigned longs. It's therefore
14946 // required to take special care of the MSB prior to running it.
14947 if (!divisor.unsigned)
14948 divisor = divisor.toUnsigned();
14949 if (divisor.gt(this))
14950 return UZERO;
14951 if (divisor.gt(this.shru(1))) // 15 >>> 1 = 7 ; with divisor = 8 ; true
14952 return UONE;
14953 res = UZERO;
14954 }
14955
14956 // Repeat the following until the remainder is less than other: find a
14957 // floating-point that approximates remainder / other *from below*, add this
14958 // into the result, and subtract it from the remainder. It is critical that
14959 // the approximate value is less than or equal to the real value so that the
14960 // remainder never becomes negative.
14961 rem = this;
14962 while (rem.gte(divisor)) {
14963 // Approximate the result of division. This may be a little greater or
14964 // smaller than the actual value.
14965 approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));
14966
14967 // We will tweak the approximate result by changing it in the 48-th digit or
14968 // the smallest non-fractional digit, whichever is larger.
14969 var log2 = Math.ceil(Math.log(approx) / Math.LN2),
14970 delta = (log2 <= 48) ? 1 : pow_dbl(2, log2 - 48),
14971
14972 // Decrease the approximation until it is smaller than the remainder. Note
14973 // that if it is too large, the product overflows and is negative.
14974 approxRes = fromNumber(approx),
14975 approxRem = approxRes.mul(divisor);
14976 while (approxRem.isNegative() || approxRem.gt(rem)) {
14977 approx -= delta;
14978 approxRes = fromNumber(approx, this.unsigned);
14979 approxRem = approxRes.mul(divisor);
14980 }
14981
14982 // We know the answer can't be zero... and actually, zero would cause
14983 // infinite recursion since we would make no progress.
14984 if (approxRes.isZero())
14985 approxRes = ONE;
14986
14987 res = res.add(approxRes);
14988 rem = rem.sub(approxRem);
14989 }
14990 return res;
14991 };
14992
14993 /**
14994 * Returns this Long divided by the specified. This is an alias of {@link Long#divide}.
14995 * @function
14996 * @param {!Long|number|string} divisor Divisor
14997 * @returns {!Long} Quotient
14998 */
14999 LongPrototype.div = LongPrototype.divide;
15000
15001 /**
15002 * Returns this Long modulo the specified.
15003 * @param {!Long|number|string} divisor Divisor
15004 * @returns {!Long} Remainder
15005 */
15006 LongPrototype.modulo = function modulo(divisor) {
15007 if (!isLong(divisor))
15008 divisor = fromValue(divisor);
15009 return this.sub(this.div(divisor).mul(divisor));
15010 };
15011
15012 /**
15013 * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}.
15014 * @function
15015 * @param {!Long|number|string} divisor Divisor
15016 * @returns {!Long} Remainder
15017 */
15018 LongPrototype.mod = LongPrototype.modulo;
15019
15020 /**
15021 * Returns the bitwise NOT of this Long.
15022 * @returns {!Long}
15023 */
15024 LongPrototype.not = function not() {
15025 return fromBits(~this.low, ~this.high, this.unsigned);
15026 };
15027
15028 /**
15029 * Returns the bitwise AND of this Long and the specified.
15030 * @param {!Long|number|string} other Other Long
15031 * @returns {!Long}
15032 */
15033 LongPrototype.and = function and(other) {
15034 if (!isLong(other))
15035 other = fromValue(other);
15036 return fromBits(this.low & other.low, this.high & other.high, this.unsigned);
15037 };
15038
15039 /**
15040 * Returns the bitwise OR of this Long and the specified.
15041 * @param {!Long|number|string} other Other Long
15042 * @returns {!Long}
15043 */
15044 LongPrototype.or = function or(other) {
15045 if (!isLong(other))
15046 other = fromValue(other);
15047 return fromBits(this.low | other.low, this.high | other.high, this.unsigned);
15048 };
15049
15050 /**
15051 * Returns the bitwise XOR of this Long and the given one.
15052 * @param {!Long|number|string} other Other Long
15053 * @returns {!Long}
15054 */
15055 LongPrototype.xor = function xor(other) {
15056 if (!isLong(other))
15057 other = fromValue(other);
15058 return fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);
15059 };
15060
15061 /**
15062 * Returns this Long with bits shifted to the left by the given amount.
15063 * @param {number|!Long} numBits Number of bits
15064 * @returns {!Long} Shifted Long
15065 */
15066 LongPrototype.shiftLeft = function shiftLeft(numBits) {
15067 if (isLong(numBits))
15068 numBits = numBits.toInt();
15069 if ((numBits &= 63) === 0)
15070 return this;
15071 else if (numBits < 32)
15072 return fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned);
15073 else
15074 return fromBits(0, this.low << (numBits - 32), this.unsigned);
15075 };
15076
15077 /**
15078 * Returns this Long with bits shifted to the left by the given amount. This is an alias of {@link Long#shiftLeft}.
15079 * @function
15080 * @param {number|!Long} numBits Number of bits
15081 * @returns {!Long} Shifted Long
15082 */
15083 LongPrototype.shl = LongPrototype.shiftLeft;
15084
15085 /**
15086 * Returns this Long with bits arithmetically shifted to the right by the given amount.
15087 * @param {number|!Long} numBits Number of bits
15088 * @returns {!Long} Shifted Long
15089 */
15090 LongPrototype.shiftRight = function shiftRight(numBits) {
15091 if (isLong(numBits))
15092 numBits = numBits.toInt();
15093 if ((numBits &= 63) === 0)
15094 return this;
15095 else if (numBits < 32)
15096 return fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned);
15097 else
15098 return fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned);
15099 };
15100
15101 /**
15102 * Returns this Long with bits arithmetically shifted to the right by the given amount. This is an alias of {@link Long#shiftRight}.
15103 * @function
15104 * @param {number|!Long} numBits Number of bits
15105 * @returns {!Long} Shifted Long
15106 */
15107 LongPrototype.shr = LongPrototype.shiftRight;
15108
15109 /**
15110 * Returns this Long with bits logically shifted to the right by the given amount.
15111 * @param {number|!Long} numBits Number of bits
15112 * @returns {!Long} Shifted Long
15113 */
15114 LongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) {
15115 if (isLong(numBits))
15116 numBits = numBits.toInt();
15117 numBits &= 63;
15118 if (numBits === 0)
15119 return this;
15120 else {
15121 var high = this.high;
15122 if (numBits < 32) {
15123 var low = this.low;
15124 return fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned);
15125 } else if (numBits === 32)
15126 return fromBits(high, 0, this.unsigned);
15127 else
15128 return fromBits(high >>> (numBits - 32), 0, this.unsigned);
15129 }
15130 };
15131
15132 /**
15133 * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}.
15134 * @function
15135 * @param {number|!Long} numBits Number of bits
15136 * @returns {!Long} Shifted Long
15137 */
15138 LongPrototype.shru = LongPrototype.shiftRightUnsigned;
15139
15140 /**
15141 * Converts this Long to signed.
15142 * @returns {!Long} Signed long
15143 */
15144 LongPrototype.toSigned = function toSigned() {
15145 if (!this.unsigned)
15146 return this;
15147 return fromBits(this.low, this.high, false);
15148 };
15149
15150 /**
15151 * Converts this Long to unsigned.
15152 * @returns {!Long} Unsigned long
15153 */
15154 LongPrototype.toUnsigned = function toUnsigned() {
15155 if (this.unsigned)
15156 return this;
15157 return fromBits(this.low, this.high, true);
15158 };
15159
15160 /**
15161 * Converts this Long to its byte representation.
15162 * @param {boolean=} le Whether little or big endian, defaults to big endian
15163 * @returns {!Array.<number>} Byte representation
15164 */
15165 LongPrototype.toBytes = function(le) {
15166 return le ? this.toBytesLE() : this.toBytesBE();
15167 }
15168
15169 /**
15170 * Converts this Long to its little endian byte representation.
15171 * @returns {!Array.<number>} Little endian byte representation
15172 */
15173 LongPrototype.toBytesLE = function() {
15174 var hi = this.high,
15175 lo = this.low;
15176 return [
15177 lo & 0xff,
15178 (lo >>> 8) & 0xff,
15179 (lo >>> 16) & 0xff,
15180 (lo >>> 24) & 0xff,
15181 hi & 0xff,
15182 (hi >>> 8) & 0xff,
15183 (hi >>> 16) & 0xff,
15184 (hi >>> 24) & 0xff
15185 ];
15186 }
15187
15188 /**
15189 * Converts this Long to its big endian byte representation.
15190 * @returns {!Array.<number>} Big endian byte representation
15191 */
15192 LongPrototype.toBytesBE = function() {
15193 var hi = this.high,
15194 lo = this.low;
15195 return [
15196 (hi >>> 24) & 0xff,
15197 (hi >>> 16) & 0xff,
15198 (hi >>> 8) & 0xff,
15199 hi & 0xff,
15200 (lo >>> 24) & 0xff,
15201 (lo >>> 16) & 0xff,
15202 (lo >>> 8) & 0xff,
15203 lo & 0xff
15204 ];
15205 }
15206
15207 return Long;
15208});
15209
15210},{}],73:[function(require,module,exports){
15211(function (Buffer){
15212'use strict'
15213var inherits = require('inherits')
15214var HashBase = require('hash-base')
15215
15216function RIPEMD160 () {
15217 HashBase.call(this, 64)
15218
15219 // state
15220 this._a = 0x67452301
15221 this._b = 0xefcdab89
15222 this._c = 0x98badcfe
15223 this._d = 0x10325476
15224 this._e = 0xc3d2e1f0
15225}
15226
15227inherits(RIPEMD160, HashBase)
15228
15229RIPEMD160.prototype._update = function () {
15230 var m = new Array(16)
15231 for (var i = 0; i < 16; ++i) m[i] = this._block.readInt32LE(i * 4)
15232
15233 var al = this._a
15234 var bl = this._b
15235 var cl = this._c
15236 var dl = this._d
15237 var el = this._e
15238
15239 // Mj = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
15240 // K = 0x00000000
15241 // Sj = 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8
15242 al = fn1(al, bl, cl, dl, el, m[0], 0x00000000, 11); cl = rotl(cl, 10)
15243 el = fn1(el, al, bl, cl, dl, m[1], 0x00000000, 14); bl = rotl(bl, 10)
15244 dl = fn1(dl, el, al, bl, cl, m[2], 0x00000000, 15); al = rotl(al, 10)
15245 cl = fn1(cl, dl, el, al, bl, m[3], 0x00000000, 12); el = rotl(el, 10)
15246 bl = fn1(bl, cl, dl, el, al, m[4], 0x00000000, 5); dl = rotl(dl, 10)
15247 al = fn1(al, bl, cl, dl, el, m[5], 0x00000000, 8); cl = rotl(cl, 10)
15248 el = fn1(el, al, bl, cl, dl, m[6], 0x00000000, 7); bl = rotl(bl, 10)
15249 dl = fn1(dl, el, al, bl, cl, m[7], 0x00000000, 9); al = rotl(al, 10)
15250 cl = fn1(cl, dl, el, al, bl, m[8], 0x00000000, 11); el = rotl(el, 10)
15251 bl = fn1(bl, cl, dl, el, al, m[9], 0x00000000, 13); dl = rotl(dl, 10)
15252 al = fn1(al, bl, cl, dl, el, m[10], 0x00000000, 14); cl = rotl(cl, 10)
15253 el = fn1(el, al, bl, cl, dl, m[11], 0x00000000, 15); bl = rotl(bl, 10)
15254 dl = fn1(dl, el, al, bl, cl, m[12], 0x00000000, 6); al = rotl(al, 10)
15255 cl = fn1(cl, dl, el, al, bl, m[13], 0x00000000, 7); el = rotl(el, 10)
15256 bl = fn1(bl, cl, dl, el, al, m[14], 0x00000000, 9); dl = rotl(dl, 10)
15257 al = fn1(al, bl, cl, dl, el, m[15], 0x00000000, 8); cl = rotl(cl, 10)
15258
15259 // Mj = 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8
15260 // K = 0x5a827999
15261 // Sj = 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12
15262 el = fn2(el, al, bl, cl, dl, m[7], 0x5a827999, 7); bl = rotl(bl, 10)
15263 dl = fn2(dl, el, al, bl, cl, m[4], 0x5a827999, 6); al = rotl(al, 10)
15264 cl = fn2(cl, dl, el, al, bl, m[13], 0x5a827999, 8); el = rotl(el, 10)
15265 bl = fn2(bl, cl, dl, el, al, m[1], 0x5a827999, 13); dl = rotl(dl, 10)
15266 al = fn2(al, bl, cl, dl, el, m[10], 0x5a827999, 11); cl = rotl(cl, 10)
15267 el = fn2(el, al, bl, cl, dl, m[6], 0x5a827999, 9); bl = rotl(bl, 10)
15268 dl = fn2(dl, el, al, bl, cl, m[15], 0x5a827999, 7); al = rotl(al, 10)
15269 cl = fn2(cl, dl, el, al, bl, m[3], 0x5a827999, 15); el = rotl(el, 10)
15270 bl = fn2(bl, cl, dl, el, al, m[12], 0x5a827999, 7); dl = rotl(dl, 10)
15271 al = fn2(al, bl, cl, dl, el, m[0], 0x5a827999, 12); cl = rotl(cl, 10)
15272 el = fn2(el, al, bl, cl, dl, m[9], 0x5a827999, 15); bl = rotl(bl, 10)
15273 dl = fn2(dl, el, al, bl, cl, m[5], 0x5a827999, 9); al = rotl(al, 10)
15274 cl = fn2(cl, dl, el, al, bl, m[2], 0x5a827999, 11); el = rotl(el, 10)
15275 bl = fn2(bl, cl, dl, el, al, m[14], 0x5a827999, 7); dl = rotl(dl, 10)
15276 al = fn2(al, bl, cl, dl, el, m[11], 0x5a827999, 13); cl = rotl(cl, 10)
15277 el = fn2(el, al, bl, cl, dl, m[8], 0x5a827999, 12); bl = rotl(bl, 10)
15278
15279 // Mj = 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12
15280 // K = 0x6ed9eba1
15281 // Sj = 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5
15282 dl = fn3(dl, el, al, bl, cl, m[3], 0x6ed9eba1, 11); al = rotl(al, 10)
15283 cl = fn3(cl, dl, el, al, bl, m[10], 0x6ed9eba1, 13); el = rotl(el, 10)
15284 bl = fn3(bl, cl, dl, el, al, m[14], 0x6ed9eba1, 6); dl = rotl(dl, 10)
15285 al = fn3(al, bl, cl, dl, el, m[4], 0x6ed9eba1, 7); cl = rotl(cl, 10)
15286 el = fn3(el, al, bl, cl, dl, m[9], 0x6ed9eba1, 14); bl = rotl(bl, 10)
15287 dl = fn3(dl, el, al, bl, cl, m[15], 0x6ed9eba1, 9); al = rotl(al, 10)
15288 cl = fn3(cl, dl, el, al, bl, m[8], 0x6ed9eba1, 13); el = rotl(el, 10)
15289 bl = fn3(bl, cl, dl, el, al, m[1], 0x6ed9eba1, 15); dl = rotl(dl, 10)
15290 al = fn3(al, bl, cl, dl, el, m[2], 0x6ed9eba1, 14); cl = rotl(cl, 10)
15291 el = fn3(el, al, bl, cl, dl, m[7], 0x6ed9eba1, 8); bl = rotl(bl, 10)
15292 dl = fn3(dl, el, al, bl, cl, m[0], 0x6ed9eba1, 13); al = rotl(al, 10)
15293 cl = fn3(cl, dl, el, al, bl, m[6], 0x6ed9eba1, 6); el = rotl(el, 10)
15294 bl = fn3(bl, cl, dl, el, al, m[13], 0x6ed9eba1, 5); dl = rotl(dl, 10)
15295 al = fn3(al, bl, cl, dl, el, m[11], 0x6ed9eba1, 12); cl = rotl(cl, 10)
15296 el = fn3(el, al, bl, cl, dl, m[5], 0x6ed9eba1, 7); bl = rotl(bl, 10)
15297 dl = fn3(dl, el, al, bl, cl, m[12], 0x6ed9eba1, 5); al = rotl(al, 10)
15298
15299 // Mj = 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2
15300 // K = 0x8f1bbcdc
15301 // Sj = 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12
15302 cl = fn4(cl, dl, el, al, bl, m[1], 0x8f1bbcdc, 11); el = rotl(el, 10)
15303 bl = fn4(bl, cl, dl, el, al, m[9], 0x8f1bbcdc, 12); dl = rotl(dl, 10)
15304 al = fn4(al, bl, cl, dl, el, m[11], 0x8f1bbcdc, 14); cl = rotl(cl, 10)
15305 el = fn4(el, al, bl, cl, dl, m[10], 0x8f1bbcdc, 15); bl = rotl(bl, 10)
15306 dl = fn4(dl, el, al, bl, cl, m[0], 0x8f1bbcdc, 14); al = rotl(al, 10)
15307 cl = fn4(cl, dl, el, al, bl, m[8], 0x8f1bbcdc, 15); el = rotl(el, 10)
15308 bl = fn4(bl, cl, dl, el, al, m[12], 0x8f1bbcdc, 9); dl = rotl(dl, 10)
15309 al = fn4(al, bl, cl, dl, el, m[4], 0x8f1bbcdc, 8); cl = rotl(cl, 10)
15310 el = fn4(el, al, bl, cl, dl, m[13], 0x8f1bbcdc, 9); bl = rotl(bl, 10)
15311 dl = fn4(dl, el, al, bl, cl, m[3], 0x8f1bbcdc, 14); al = rotl(al, 10)
15312 cl = fn4(cl, dl, el, al, bl, m[7], 0x8f1bbcdc, 5); el = rotl(el, 10)
15313 bl = fn4(bl, cl, dl, el, al, m[15], 0x8f1bbcdc, 6); dl = rotl(dl, 10)
15314 al = fn4(al, bl, cl, dl, el, m[14], 0x8f1bbcdc, 8); cl = rotl(cl, 10)
15315 el = fn4(el, al, bl, cl, dl, m[5], 0x8f1bbcdc, 6); bl = rotl(bl, 10)
15316 dl = fn4(dl, el, al, bl, cl, m[6], 0x8f1bbcdc, 5); al = rotl(al, 10)
15317 cl = fn4(cl, dl, el, al, bl, m[2], 0x8f1bbcdc, 12); el = rotl(el, 10)
15318
15319 // Mj = 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
15320 // K = 0xa953fd4e
15321 // Sj = 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
15322 bl = fn5(bl, cl, dl, el, al, m[4], 0xa953fd4e, 9); dl = rotl(dl, 10)
15323 al = fn5(al, bl, cl, dl, el, m[0], 0xa953fd4e, 15); cl = rotl(cl, 10)
15324 el = fn5(el, al, bl, cl, dl, m[5], 0xa953fd4e, 5); bl = rotl(bl, 10)
15325 dl = fn5(dl, el, al, bl, cl, m[9], 0xa953fd4e, 11); al = rotl(al, 10)
15326 cl = fn5(cl, dl, el, al, bl, m[7], 0xa953fd4e, 6); el = rotl(el, 10)
15327 bl = fn5(bl, cl, dl, el, al, m[12], 0xa953fd4e, 8); dl = rotl(dl, 10)
15328 al = fn5(al, bl, cl, dl, el, m[2], 0xa953fd4e, 13); cl = rotl(cl, 10)
15329 el = fn5(el, al, bl, cl, dl, m[10], 0xa953fd4e, 12); bl = rotl(bl, 10)
15330 dl = fn5(dl, el, al, bl, cl, m[14], 0xa953fd4e, 5); al = rotl(al, 10)
15331 cl = fn5(cl, dl, el, al, bl, m[1], 0xa953fd4e, 12); el = rotl(el, 10)
15332 bl = fn5(bl, cl, dl, el, al, m[3], 0xa953fd4e, 13); dl = rotl(dl, 10)
15333 al = fn5(al, bl, cl, dl, el, m[8], 0xa953fd4e, 14); cl = rotl(cl, 10)
15334 el = fn5(el, al, bl, cl, dl, m[11], 0xa953fd4e, 11); bl = rotl(bl, 10)
15335 dl = fn5(dl, el, al, bl, cl, m[6], 0xa953fd4e, 8); al = rotl(al, 10)
15336 cl = fn5(cl, dl, el, al, bl, m[15], 0xa953fd4e, 5); el = rotl(el, 10)
15337 bl = fn5(bl, cl, dl, el, al, m[13], 0xa953fd4e, 6); dl = rotl(dl, 10)
15338
15339 var ar = this._a
15340 var br = this._b
15341 var cr = this._c
15342 var dr = this._d
15343 var er = this._e
15344
15345 // M'j = 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12
15346 // K' = 0x50a28be6
15347 // S'j = 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6
15348 ar = fn5(ar, br, cr, dr, er, m[5], 0x50a28be6, 8); cr = rotl(cr, 10)
15349 er = fn5(er, ar, br, cr, dr, m[14], 0x50a28be6, 9); br = rotl(br, 10)
15350 dr = fn5(dr, er, ar, br, cr, m[7], 0x50a28be6, 9); ar = rotl(ar, 10)
15351 cr = fn5(cr, dr, er, ar, br, m[0], 0x50a28be6, 11); er = rotl(er, 10)
15352 br = fn5(br, cr, dr, er, ar, m[9], 0x50a28be6, 13); dr = rotl(dr, 10)
15353 ar = fn5(ar, br, cr, dr, er, m[2], 0x50a28be6, 15); cr = rotl(cr, 10)
15354 er = fn5(er, ar, br, cr, dr, m[11], 0x50a28be6, 15); br = rotl(br, 10)
15355 dr = fn5(dr, er, ar, br, cr, m[4], 0x50a28be6, 5); ar = rotl(ar, 10)
15356 cr = fn5(cr, dr, er, ar, br, m[13], 0x50a28be6, 7); er = rotl(er, 10)
15357 br = fn5(br, cr, dr, er, ar, m[6], 0x50a28be6, 7); dr = rotl(dr, 10)
15358 ar = fn5(ar, br, cr, dr, er, m[15], 0x50a28be6, 8); cr = rotl(cr, 10)
15359 er = fn5(er, ar, br, cr, dr, m[8], 0x50a28be6, 11); br = rotl(br, 10)
15360 dr = fn5(dr, er, ar, br, cr, m[1], 0x50a28be6, 14); ar = rotl(ar, 10)
15361 cr = fn5(cr, dr, er, ar, br, m[10], 0x50a28be6, 14); er = rotl(er, 10)
15362 br = fn5(br, cr, dr, er, ar, m[3], 0x50a28be6, 12); dr = rotl(dr, 10)
15363 ar = fn5(ar, br, cr, dr, er, m[12], 0x50a28be6, 6); cr = rotl(cr, 10)
15364
15365 // M'j = 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2
15366 // K' = 0x5c4dd124
15367 // S'j = 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11
15368 er = fn4(er, ar, br, cr, dr, m[6], 0x5c4dd124, 9); br = rotl(br, 10)
15369 dr = fn4(dr, er, ar, br, cr, m[11], 0x5c4dd124, 13); ar = rotl(ar, 10)
15370 cr = fn4(cr, dr, er, ar, br, m[3], 0x5c4dd124, 15); er = rotl(er, 10)
15371 br = fn4(br, cr, dr, er, ar, m[7], 0x5c4dd124, 7); dr = rotl(dr, 10)
15372 ar = fn4(ar, br, cr, dr, er, m[0], 0x5c4dd124, 12); cr = rotl(cr, 10)
15373 er = fn4(er, ar, br, cr, dr, m[13], 0x5c4dd124, 8); br = rotl(br, 10)
15374 dr = fn4(dr, er, ar, br, cr, m[5], 0x5c4dd124, 9); ar = rotl(ar, 10)
15375 cr = fn4(cr, dr, er, ar, br, m[10], 0x5c4dd124, 11); er = rotl(er, 10)
15376 br = fn4(br, cr, dr, er, ar, m[14], 0x5c4dd124, 7); dr = rotl(dr, 10)
15377 ar = fn4(ar, br, cr, dr, er, m[15], 0x5c4dd124, 7); cr = rotl(cr, 10)
15378 er = fn4(er, ar, br, cr, dr, m[8], 0x5c4dd124, 12); br = rotl(br, 10)
15379 dr = fn4(dr, er, ar, br, cr, m[12], 0x5c4dd124, 7); ar = rotl(ar, 10)
15380 cr = fn4(cr, dr, er, ar, br, m[4], 0x5c4dd124, 6); er = rotl(er, 10)
15381 br = fn4(br, cr, dr, er, ar, m[9], 0x5c4dd124, 15); dr = rotl(dr, 10)
15382 ar = fn4(ar, br, cr, dr, er, m[1], 0x5c4dd124, 13); cr = rotl(cr, 10)
15383 er = fn4(er, ar, br, cr, dr, m[2], 0x5c4dd124, 11); br = rotl(br, 10)
15384
15385 // M'j = 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13
15386 // K' = 0x6d703ef3
15387 // S'j = 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5
15388 dr = fn3(dr, er, ar, br, cr, m[15], 0x6d703ef3, 9); ar = rotl(ar, 10)
15389 cr = fn3(cr, dr, er, ar, br, m[5], 0x6d703ef3, 7); er = rotl(er, 10)
15390 br = fn3(br, cr, dr, er, ar, m[1], 0x6d703ef3, 15); dr = rotl(dr, 10)
15391 ar = fn3(ar, br, cr, dr, er, m[3], 0x6d703ef3, 11); cr = rotl(cr, 10)
15392 er = fn3(er, ar, br, cr, dr, m[7], 0x6d703ef3, 8); br = rotl(br, 10)
15393 dr = fn3(dr, er, ar, br, cr, m[14], 0x6d703ef3, 6); ar = rotl(ar, 10)
15394 cr = fn3(cr, dr, er, ar, br, m[6], 0x6d703ef3, 6); er = rotl(er, 10)
15395 br = fn3(br, cr, dr, er, ar, m[9], 0x6d703ef3, 14); dr = rotl(dr, 10)
15396 ar = fn3(ar, br, cr, dr, er, m[11], 0x6d703ef3, 12); cr = rotl(cr, 10)
15397 er = fn3(er, ar, br, cr, dr, m[8], 0x6d703ef3, 13); br = rotl(br, 10)
15398 dr = fn3(dr, er, ar, br, cr, m[12], 0x6d703ef3, 5); ar = rotl(ar, 10)
15399 cr = fn3(cr, dr, er, ar, br, m[2], 0x6d703ef3, 14); er = rotl(er, 10)
15400 br = fn3(br, cr, dr, er, ar, m[10], 0x6d703ef3, 13); dr = rotl(dr, 10)
15401 ar = fn3(ar, br, cr, dr, er, m[0], 0x6d703ef3, 13); cr = rotl(cr, 10)
15402 er = fn3(er, ar, br, cr, dr, m[4], 0x6d703ef3, 7); br = rotl(br, 10)
15403 dr = fn3(dr, er, ar, br, cr, m[13], 0x6d703ef3, 5); ar = rotl(ar, 10)
15404
15405 // M'j = 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14
15406 // K' = 0x7a6d76e9
15407 // S'j = 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8
15408 cr = fn2(cr, dr, er, ar, br, m[8], 0x7a6d76e9, 15); er = rotl(er, 10)
15409 br = fn2(br, cr, dr, er, ar, m[6], 0x7a6d76e9, 5); dr = rotl(dr, 10)
15410 ar = fn2(ar, br, cr, dr, er, m[4], 0x7a6d76e9, 8); cr = rotl(cr, 10)
15411 er = fn2(er, ar, br, cr, dr, m[1], 0x7a6d76e9, 11); br = rotl(br, 10)
15412 dr = fn2(dr, er, ar, br, cr, m[3], 0x7a6d76e9, 14); ar = rotl(ar, 10)
15413 cr = fn2(cr, dr, er, ar, br, m[11], 0x7a6d76e9, 14); er = rotl(er, 10)
15414 br = fn2(br, cr, dr, er, ar, m[15], 0x7a6d76e9, 6); dr = rotl(dr, 10)
15415 ar = fn2(ar, br, cr, dr, er, m[0], 0x7a6d76e9, 14); cr = rotl(cr, 10)
15416 er = fn2(er, ar, br, cr, dr, m[5], 0x7a6d76e9, 6); br = rotl(br, 10)
15417 dr = fn2(dr, er, ar, br, cr, m[12], 0x7a6d76e9, 9); ar = rotl(ar, 10)
15418 cr = fn2(cr, dr, er, ar, br, m[2], 0x7a6d76e9, 12); er = rotl(er, 10)
15419 br = fn2(br, cr, dr, er, ar, m[13], 0x7a6d76e9, 9); dr = rotl(dr, 10)
15420 ar = fn2(ar, br, cr, dr, er, m[9], 0x7a6d76e9, 12); cr = rotl(cr, 10)
15421 er = fn2(er, ar, br, cr, dr, m[7], 0x7a6d76e9, 5); br = rotl(br, 10)
15422 dr = fn2(dr, er, ar, br, cr, m[10], 0x7a6d76e9, 15); ar = rotl(ar, 10)
15423 cr = fn2(cr, dr, er, ar, br, m[14], 0x7a6d76e9, 8); er = rotl(er, 10)
15424
15425 // M'j = 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
15426 // K' = 0x00000000
15427 // S'j = 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
15428 br = fn1(br, cr, dr, er, ar, m[12], 0x00000000, 8); dr = rotl(dr, 10)
15429 ar = fn1(ar, br, cr, dr, er, m[15], 0x00000000, 5); cr = rotl(cr, 10)
15430 er = fn1(er, ar, br, cr, dr, m[10], 0x00000000, 12); br = rotl(br, 10)
15431 dr = fn1(dr, er, ar, br, cr, m[4], 0x00000000, 9); ar = rotl(ar, 10)
15432 cr = fn1(cr, dr, er, ar, br, m[1], 0x00000000, 12); er = rotl(er, 10)
15433 br = fn1(br, cr, dr, er, ar, m[5], 0x00000000, 5); dr = rotl(dr, 10)
15434 ar = fn1(ar, br, cr, dr, er, m[8], 0x00000000, 14); cr = rotl(cr, 10)
15435 er = fn1(er, ar, br, cr, dr, m[7], 0x00000000, 6); br = rotl(br, 10)
15436 dr = fn1(dr, er, ar, br, cr, m[6], 0x00000000, 8); ar = rotl(ar, 10)
15437 cr = fn1(cr, dr, er, ar, br, m[2], 0x00000000, 13); er = rotl(er, 10)
15438 br = fn1(br, cr, dr, er, ar, m[13], 0x00000000, 6); dr = rotl(dr, 10)
15439 ar = fn1(ar, br, cr, dr, er, m[14], 0x00000000, 5); cr = rotl(cr, 10)
15440 er = fn1(er, ar, br, cr, dr, m[0], 0x00000000, 15); br = rotl(br, 10)
15441 dr = fn1(dr, er, ar, br, cr, m[3], 0x00000000, 13); ar = rotl(ar, 10)
15442 cr = fn1(cr, dr, er, ar, br, m[9], 0x00000000, 11); er = rotl(er, 10)
15443 br = fn1(br, cr, dr, er, ar, m[11], 0x00000000, 11); dr = rotl(dr, 10)
15444
15445 // change state
15446 var t = (this._b + cl + dr) | 0
15447 this._b = (this._c + dl + er) | 0
15448 this._c = (this._d + el + ar) | 0
15449 this._d = (this._e + al + br) | 0
15450 this._e = (this._a + bl + cr) | 0
15451 this._a = t
15452}
15453
15454RIPEMD160.prototype._digest = function () {
15455 // create padding and handle blocks
15456 this._block[this._blockOffset++] = 0x80
15457 if (this._blockOffset > 56) {
15458 this._block.fill(0, this._blockOffset, 64)
15459 this._update()
15460 this._blockOffset = 0
15461 }
15462
15463 this._block.fill(0, this._blockOffset, 56)
15464 this._block.writeUInt32LE(this._length[0], 56)
15465 this._block.writeUInt32LE(this._length[1], 60)
15466 this._update()
15467
15468 // produce result
15469 var buffer = new Buffer(20)
15470 buffer.writeInt32LE(this._a, 0)
15471 buffer.writeInt32LE(this._b, 4)
15472 buffer.writeInt32LE(this._c, 8)
15473 buffer.writeInt32LE(this._d, 12)
15474 buffer.writeInt32LE(this._e, 16)
15475 return buffer
15476}
15477
15478function rotl (x, n) {
15479 return (x << n) | (x >>> (32 - n))
15480}
15481
15482function fn1 (a, b, c, d, e, m, k, s) {
15483 return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0
15484}
15485
15486function fn2 (a, b, c, d, e, m, k, s) {
15487 return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0
15488}
15489
15490function fn3 (a, b, c, d, e, m, k, s) {
15491 return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0
15492}
15493
15494function fn4 (a, b, c, d, e, m, k, s) {
15495 return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0
15496}
15497
15498function fn5 (a, b, c, d, e, m, k, s) {
15499 return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0
15500}
15501
15502module.exports = RIPEMD160
15503
15504}).call(this,require("buffer").Buffer)
15505},{"buffer":5,"hash-base":70,"inherits":71}],74:[function(require,module,exports){
15506/* eslint-disable node/no-deprecated-api */
15507var buffer = require('buffer')
15508var Buffer = buffer.Buffer
15509
15510if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
15511 module.exports = buffer
15512} else {
15513 // Copy properties from require('buffer')
15514 Object.keys(buffer).forEach(function (prop) {
15515 exports[prop] = buffer[prop]
15516 })
15517 exports.Buffer = SafeBuffer
15518}
15519
15520function SafeBuffer (arg, encodingOrOffset, length) {
15521 return Buffer(arg, encodingOrOffset, length)
15522}
15523
15524// Copy static methods from Buffer
15525Object.keys(Buffer).forEach(function (prop) {
15526 SafeBuffer[prop] = Buffer[prop]
15527})
15528
15529SafeBuffer.from = function (arg, encodingOrOffset, length) {
15530 if (typeof arg === 'number') {
15531 throw new TypeError('Argument must not be a number')
15532 }
15533 return Buffer(arg, encodingOrOffset, length)
15534}
15535
15536SafeBuffer.alloc = function (size, fill, encoding) {
15537 if (typeof size !== 'number') {
15538 throw new TypeError('Argument must be a number')
15539 }
15540 var buf = Buffer(size)
15541 if (fill !== undefined) {
15542 if (typeof encoding === 'string') {
15543 buf.fill(fill, encoding)
15544 } else {
15545 buf.fill(fill)
15546 }
15547 } else {
15548 buf.fill(0)
15549 }
15550 return buf
15551}
15552
15553SafeBuffer.allocUnsafe = function (size) {
15554 if (typeof size !== 'number') {
15555 throw new TypeError('Argument must be a number')
15556 }
15557 return Buffer(size)
15558}
15559
15560SafeBuffer.allocUnsafeSlow = function (size) {
15561 if (typeof size !== 'number') {
15562 throw new TypeError('Argument must be a number')
15563 }
15564 return buffer.SlowBuffer(size)
15565}
15566
15567},{"buffer":5}],75:[function(require,module,exports){
15568(function (process,Buffer){
15569!function(globals){
15570'use strict'
15571
15572//*** UMD BEGIN
15573if (typeof define !== 'undefined' && define.amd) { //require.js / AMD
15574 define([], function() {
15575 return secureRandom
15576 })
15577} else if (typeof module !== 'undefined' && module.exports) { //CommonJS
15578 module.exports = secureRandom
15579} else { //script / browser
15580 globals.secureRandom = secureRandom
15581}
15582//*** UMD END
15583
15584//options.type is the only valid option
15585function secureRandom(count, options) {
15586 options = options || {type: 'Array'}
15587 //we check for process.pid to prevent browserify from tricking us
15588 if (typeof process != 'undefined' && typeof process.pid == 'number') {
15589 return nodeRandom(count, options)
15590 } else {
15591 var crypto = window.crypto || window.msCrypto
15592 if (!crypto) throw new Error("Your browser does not support window.crypto.")
15593 return browserRandom(count, options)
15594 }
15595}
15596
15597function nodeRandom(count, options) {
15598 var crypto = require('crypto')
15599 var buf = crypto.randomBytes(count)
15600
15601 switch (options.type) {
15602 case 'Array':
15603 return [].slice.call(buf)
15604 case 'Buffer':
15605 return buf
15606 case 'Uint8Array':
15607 var arr = new Uint8Array(count)
15608 for (var i = 0; i < count; ++i) { arr[i] = buf.readUInt8(i) }
15609 return arr
15610 default:
15611 throw new Error(options.type + " is unsupported.")
15612 }
15613}
15614
15615function browserRandom(count, options) {
15616 var nativeArr = new Uint8Array(count)
15617 var crypto = window.crypto || window.msCrypto
15618 crypto.getRandomValues(nativeArr)
15619
15620 switch (options.type) {
15621 case 'Array':
15622 return [].slice.call(nativeArr)
15623 case 'Buffer':
15624 try { var b = new Buffer(1) } catch(e) { throw new Error('Buffer not supported in this environment. Use Node.js or Browserify for browser support.')}
15625 return new Buffer(nativeArr)
15626 case 'Uint8Array':
15627 return nativeArr
15628 default:
15629 throw new Error(options.type + " is unsupported.")
15630 }
15631}
15632
15633secureRandom.randomArray = function(byteCount) {
15634 return secureRandom(byteCount, {type: 'Array'})
15635}
15636
15637secureRandom.randomUint8Array = function(byteCount) {
15638 return secureRandom(byteCount, {type: 'Uint8Array'})
15639}
15640
15641secureRandom.randomBuffer = function(byteCount) {
15642 return secureRandom(byteCount, {type: 'Buffer'})
15643}
15644
15645
15646}(this);
15647
15648}).call(this,require('_process'),require("buffer").Buffer)
15649},{"_process":13,"buffer":5,"crypto":3}],76:[function(require,module,exports){
15650(function (Buffer){
15651// prototype class for hash functions
15652function Hash (blockSize, finalSize) {
15653 this._block = new Buffer(blockSize)
15654 this._finalSize = finalSize
15655 this._blockSize = blockSize
15656 this._len = 0
15657 this._s = 0
15658}
15659
15660Hash.prototype.update = function (data, enc) {
15661 if (typeof data === 'string') {
15662 enc = enc || 'utf8'
15663 data = new Buffer(data, enc)
15664 }
15665
15666 var l = this._len += data.length
15667 var s = this._s || 0
15668 var f = 0
15669 var buffer = this._block
15670
15671 while (s < l) {
15672 var t = Math.min(data.length, f + this._blockSize - (s % this._blockSize))
15673 var ch = (t - f)
15674
15675 for (var i = 0; i < ch; i++) {
15676 buffer[(s % this._blockSize) + i] = data[i + f]
15677 }
15678
15679 s += ch
15680 f += ch
15681
15682 if ((s % this._blockSize) === 0) {
15683 this._update(buffer)
15684 }
15685 }
15686 this._s = s
15687
15688 return this
15689}
15690
15691Hash.prototype.digest = function (enc) {
15692 // Suppose the length of the message M, in bits, is l
15693 var l = this._len * 8
15694
15695 // Append the bit 1 to the end of the message
15696 this._block[this._len % this._blockSize] = 0x80
15697
15698 // and then k zero bits, where k is the smallest non-negative solution to the equation (l + 1 + k) === finalSize mod blockSize
15699 this._block.fill(0, this._len % this._blockSize + 1)
15700
15701 if (l % (this._blockSize * 8) >= this._finalSize * 8) {
15702 this._update(this._block)
15703 this._block.fill(0)
15704 }
15705
15706 // to this append the block which is equal to the number l written in binary
15707 // TODO: handle case where l is > Math.pow(2, 29)
15708 this._block.writeInt32BE(l, this._blockSize - 4)
15709
15710 var hash = this._update(this._block) || this._hash()
15711
15712 return enc ? hash.toString(enc) : hash
15713}
15714
15715Hash.prototype._update = function () {
15716 throw new Error('_update must be implemented by subclass')
15717}
15718
15719module.exports = Hash
15720
15721}).call(this,require("buffer").Buffer)
15722},{"buffer":5}],77:[function(require,module,exports){
15723var exports = module.exports = function SHA (algorithm) {
15724 algorithm = algorithm.toLowerCase()
15725
15726 var Algorithm = exports[algorithm]
15727 if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)')
15728
15729 return new Algorithm()
15730}
15731
15732exports.sha = require('./sha')
15733exports.sha1 = require('./sha1')
15734exports.sha224 = require('./sha224')
15735exports.sha256 = require('./sha256')
15736exports.sha384 = require('./sha384')
15737exports.sha512 = require('./sha512')
15738
15739},{"./sha":78,"./sha1":79,"./sha224":80,"./sha256":81,"./sha384":82,"./sha512":83}],78:[function(require,module,exports){
15740(function (Buffer){
15741/*
15742 * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined
15743 * in FIPS PUB 180-1
15744 * This source code is derived from sha1.js of the same repository.
15745 * The difference between SHA-0 and SHA-1 is just a bitwise rotate left
15746 * operation was added.
15747 */
15748
15749var inherits = require('inherits')
15750var Hash = require('./hash')
15751
15752var K = [
15753 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
15754]
15755
15756var W = new Array(80)
15757
15758function Sha () {
15759 this.init()
15760 this._w = W
15761
15762 Hash.call(this, 64, 56)
15763}
15764
15765inherits(Sha, Hash)
15766
15767Sha.prototype.init = function () {
15768 this._a = 0x67452301
15769 this._b = 0xefcdab89
15770 this._c = 0x98badcfe
15771 this._d = 0x10325476
15772 this._e = 0xc3d2e1f0
15773
15774 return this
15775}
15776
15777function rotl5 (num) {
15778 return (num << 5) | (num >>> 27)
15779}
15780
15781function rotl30 (num) {
15782 return (num << 30) | (num >>> 2)
15783}
15784
15785function ft (s, b, c, d) {
15786 if (s === 0) return (b & c) | ((~b) & d)
15787 if (s === 2) return (b & c) | (b & d) | (c & d)
15788 return b ^ c ^ d
15789}
15790
15791Sha.prototype._update = function (M) {
15792 var W = this._w
15793
15794 var a = this._a | 0
15795 var b = this._b | 0
15796 var c = this._c | 0
15797 var d = this._d | 0
15798 var e = this._e | 0
15799
15800 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
15801 for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]
15802
15803 for (var j = 0; j < 80; ++j) {
15804 var s = ~~(j / 20)
15805 var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0
15806
15807 e = d
15808 d = c
15809 c = rotl30(b)
15810 b = a
15811 a = t
15812 }
15813
15814 this._a = (a + this._a) | 0
15815 this._b = (b + this._b) | 0
15816 this._c = (c + this._c) | 0
15817 this._d = (d + this._d) | 0
15818 this._e = (e + this._e) | 0
15819}
15820
15821Sha.prototype._hash = function () {
15822 var H = new Buffer(20)
15823
15824 H.writeInt32BE(this._a | 0, 0)
15825 H.writeInt32BE(this._b | 0, 4)
15826 H.writeInt32BE(this._c | 0, 8)
15827 H.writeInt32BE(this._d | 0, 12)
15828 H.writeInt32BE(this._e | 0, 16)
15829
15830 return H
15831}
15832
15833module.exports = Sha
15834
15835}).call(this,require("buffer").Buffer)
15836},{"./hash":76,"buffer":5,"inherits":71}],79:[function(require,module,exports){
15837(function (Buffer){
15838/*
15839 * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
15840 * in FIPS PUB 180-1
15841 * Version 2.1a Copyright Paul Johnston 2000 - 2002.
15842 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
15843 * Distributed under the BSD License
15844 * See http://pajhome.org.uk/crypt/md5 for details.
15845 */
15846
15847var inherits = require('inherits')
15848var Hash = require('./hash')
15849
15850var K = [
15851 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
15852]
15853
15854var W = new Array(80)
15855
15856function Sha1 () {
15857 this.init()
15858 this._w = W
15859
15860 Hash.call(this, 64, 56)
15861}
15862
15863inherits(Sha1, Hash)
15864
15865Sha1.prototype.init = function () {
15866 this._a = 0x67452301
15867 this._b = 0xefcdab89
15868 this._c = 0x98badcfe
15869 this._d = 0x10325476
15870 this._e = 0xc3d2e1f0
15871
15872 return this
15873}
15874
15875function rotl1 (num) {
15876 return (num << 1) | (num >>> 31)
15877}
15878
15879function rotl5 (num) {
15880 return (num << 5) | (num >>> 27)
15881}
15882
15883function rotl30 (num) {
15884 return (num << 30) | (num >>> 2)
15885}
15886
15887function ft (s, b, c, d) {
15888 if (s === 0) return (b & c) | ((~b) & d)
15889 if (s === 2) return (b & c) | (b & d) | (c & d)
15890 return b ^ c ^ d
15891}
15892
15893Sha1.prototype._update = function (M) {
15894 var W = this._w
15895
15896 var a = this._a | 0
15897 var b = this._b | 0
15898 var c = this._c | 0
15899 var d = this._d | 0
15900 var e = this._e | 0
15901
15902 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
15903 for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16])
15904
15905 for (var j = 0; j < 80; ++j) {
15906 var s = ~~(j / 20)
15907 var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0
15908
15909 e = d
15910 d = c
15911 c = rotl30(b)
15912 b = a
15913 a = t
15914 }
15915
15916 this._a = (a + this._a) | 0
15917 this._b = (b + this._b) | 0
15918 this._c = (c + this._c) | 0
15919 this._d = (d + this._d) | 0
15920 this._e = (e + this._e) | 0
15921}
15922
15923Sha1.prototype._hash = function () {
15924 var H = new Buffer(20)
15925
15926 H.writeInt32BE(this._a | 0, 0)
15927 H.writeInt32BE(this._b | 0, 4)
15928 H.writeInt32BE(this._c | 0, 8)
15929 H.writeInt32BE(this._d | 0, 12)
15930 H.writeInt32BE(this._e | 0, 16)
15931
15932 return H
15933}
15934
15935module.exports = Sha1
15936
15937}).call(this,require("buffer").Buffer)
15938},{"./hash":76,"buffer":5,"inherits":71}],80:[function(require,module,exports){
15939(function (Buffer){
15940/**
15941 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
15942 * in FIPS 180-2
15943 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
15944 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
15945 *
15946 */
15947
15948var inherits = require('inherits')
15949var Sha256 = require('./sha256')
15950var Hash = require('./hash')
15951
15952var W = new Array(64)
15953
15954function Sha224 () {
15955 this.init()
15956
15957 this._w = W // new Array(64)
15958
15959 Hash.call(this, 64, 56)
15960}
15961
15962inherits(Sha224, Sha256)
15963
15964Sha224.prototype.init = function () {
15965 this._a = 0xc1059ed8
15966 this._b = 0x367cd507
15967 this._c = 0x3070dd17
15968 this._d = 0xf70e5939
15969 this._e = 0xffc00b31
15970 this._f = 0x68581511
15971 this._g = 0x64f98fa7
15972 this._h = 0xbefa4fa4
15973
15974 return this
15975}
15976
15977Sha224.prototype._hash = function () {
15978 var H = new Buffer(28)
15979
15980 H.writeInt32BE(this._a, 0)
15981 H.writeInt32BE(this._b, 4)
15982 H.writeInt32BE(this._c, 8)
15983 H.writeInt32BE(this._d, 12)
15984 H.writeInt32BE(this._e, 16)
15985 H.writeInt32BE(this._f, 20)
15986 H.writeInt32BE(this._g, 24)
15987
15988 return H
15989}
15990
15991module.exports = Sha224
15992
15993}).call(this,require("buffer").Buffer)
15994},{"./hash":76,"./sha256":81,"buffer":5,"inherits":71}],81:[function(require,module,exports){
15995(function (Buffer){
15996/**
15997 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
15998 * in FIPS 180-2
15999 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
16000 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
16001 *
16002 */
16003
16004var inherits = require('inherits')
16005var Hash = require('./hash')
16006
16007var K = [
16008 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5,
16009 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5,
16010 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3,
16011 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174,
16012 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC,
16013 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,
16014 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7,
16015 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967,
16016 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13,
16017 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85,
16018 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3,
16019 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,
16020 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5,
16021 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3,
16022 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208,
16023 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2
16024]
16025
16026var W = new Array(64)
16027
16028function Sha256 () {
16029 this.init()
16030
16031 this._w = W // new Array(64)
16032
16033 Hash.call(this, 64, 56)
16034}
16035
16036inherits(Sha256, Hash)
16037
16038Sha256.prototype.init = function () {
16039 this._a = 0x6a09e667
16040 this._b = 0xbb67ae85
16041 this._c = 0x3c6ef372
16042 this._d = 0xa54ff53a
16043 this._e = 0x510e527f
16044 this._f = 0x9b05688c
16045 this._g = 0x1f83d9ab
16046 this._h = 0x5be0cd19
16047
16048 return this
16049}
16050
16051function ch (x, y, z) {
16052 return z ^ (x & (y ^ z))
16053}
16054
16055function maj (x, y, z) {
16056 return (x & y) | (z & (x | y))
16057}
16058
16059function sigma0 (x) {
16060 return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10)
16061}
16062
16063function sigma1 (x) {
16064 return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7)
16065}
16066
16067function gamma0 (x) {
16068 return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3)
16069}
16070
16071function gamma1 (x) {
16072 return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10)
16073}
16074
16075Sha256.prototype._update = function (M) {
16076 var W = this._w
16077
16078 var a = this._a | 0
16079 var b = this._b | 0
16080 var c = this._c | 0
16081 var d = this._d | 0
16082 var e = this._e | 0
16083 var f = this._f | 0
16084 var g = this._g | 0
16085 var h = this._h | 0
16086
16087 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
16088 for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0
16089
16090 for (var j = 0; j < 64; ++j) {
16091 var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0
16092 var T2 = (sigma0(a) + maj(a, b, c)) | 0
16093
16094 h = g
16095 g = f
16096 f = e
16097 e = (d + T1) | 0
16098 d = c
16099 c = b
16100 b = a
16101 a = (T1 + T2) | 0
16102 }
16103
16104 this._a = (a + this._a) | 0
16105 this._b = (b + this._b) | 0
16106 this._c = (c + this._c) | 0
16107 this._d = (d + this._d) | 0
16108 this._e = (e + this._e) | 0
16109 this._f = (f + this._f) | 0
16110 this._g = (g + this._g) | 0
16111 this._h = (h + this._h) | 0
16112}
16113
16114Sha256.prototype._hash = function () {
16115 var H = new Buffer(32)
16116
16117 H.writeInt32BE(this._a, 0)
16118 H.writeInt32BE(this._b, 4)
16119 H.writeInt32BE(this._c, 8)
16120 H.writeInt32BE(this._d, 12)
16121 H.writeInt32BE(this._e, 16)
16122 H.writeInt32BE(this._f, 20)
16123 H.writeInt32BE(this._g, 24)
16124 H.writeInt32BE(this._h, 28)
16125
16126 return H
16127}
16128
16129module.exports = Sha256
16130
16131}).call(this,require("buffer").Buffer)
16132},{"./hash":76,"buffer":5,"inherits":71}],82:[function(require,module,exports){
16133(function (Buffer){
16134var inherits = require('inherits')
16135var SHA512 = require('./sha512')
16136var Hash = require('./hash')
16137
16138var W = new Array(160)
16139
16140function Sha384 () {
16141 this.init()
16142 this._w = W
16143
16144 Hash.call(this, 128, 112)
16145}
16146
16147inherits(Sha384, SHA512)
16148
16149Sha384.prototype.init = function () {
16150 this._ah = 0xcbbb9d5d
16151 this._bh = 0x629a292a
16152 this._ch = 0x9159015a
16153 this._dh = 0x152fecd8
16154 this._eh = 0x67332667
16155 this._fh = 0x8eb44a87
16156 this._gh = 0xdb0c2e0d
16157 this._hh = 0x47b5481d
16158
16159 this._al = 0xc1059ed8
16160 this._bl = 0x367cd507
16161 this._cl = 0x3070dd17
16162 this._dl = 0xf70e5939
16163 this._el = 0xffc00b31
16164 this._fl = 0x68581511
16165 this._gl = 0x64f98fa7
16166 this._hl = 0xbefa4fa4
16167
16168 return this
16169}
16170
16171Sha384.prototype._hash = function () {
16172 var H = new Buffer(48)
16173
16174 function writeInt64BE (h, l, offset) {
16175 H.writeInt32BE(h, offset)
16176 H.writeInt32BE(l, offset + 4)
16177 }
16178
16179 writeInt64BE(this._ah, this._al, 0)
16180 writeInt64BE(this._bh, this._bl, 8)
16181 writeInt64BE(this._ch, this._cl, 16)
16182 writeInt64BE(this._dh, this._dl, 24)
16183 writeInt64BE(this._eh, this._el, 32)
16184 writeInt64BE(this._fh, this._fl, 40)
16185
16186 return H
16187}
16188
16189module.exports = Sha384
16190
16191}).call(this,require("buffer").Buffer)
16192},{"./hash":76,"./sha512":83,"buffer":5,"inherits":71}],83:[function(require,module,exports){
16193(function (Buffer){
16194var inherits = require('inherits')
16195var Hash = require('./hash')
16196
16197var K = [
16198 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
16199 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
16200 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
16201 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
16202 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
16203 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
16204 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
16205 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
16206 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
16207 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
16208 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
16209 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
16210 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
16211 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
16212 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
16213 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
16214 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
16215 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
16216 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
16217 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
16218 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
16219 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
16220 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
16221 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
16222 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
16223 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
16224 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
16225 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
16226 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
16227 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
16228 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
16229 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
16230 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
16231 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
16232 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
16233 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
16234 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
16235 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
16236 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
16237 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
16238]
16239
16240var W = new Array(160)
16241
16242function Sha512 () {
16243 this.init()
16244 this._w = W
16245
16246 Hash.call(this, 128, 112)
16247}
16248
16249inherits(Sha512, Hash)
16250
16251Sha512.prototype.init = function () {
16252 this._ah = 0x6a09e667
16253 this._bh = 0xbb67ae85
16254 this._ch = 0x3c6ef372
16255 this._dh = 0xa54ff53a
16256 this._eh = 0x510e527f
16257 this._fh = 0x9b05688c
16258 this._gh = 0x1f83d9ab
16259 this._hh = 0x5be0cd19
16260
16261 this._al = 0xf3bcc908
16262 this._bl = 0x84caa73b
16263 this._cl = 0xfe94f82b
16264 this._dl = 0x5f1d36f1
16265 this._el = 0xade682d1
16266 this._fl = 0x2b3e6c1f
16267 this._gl = 0xfb41bd6b
16268 this._hl = 0x137e2179
16269
16270 return this
16271}
16272
16273function Ch (x, y, z) {
16274 return z ^ (x & (y ^ z))
16275}
16276
16277function maj (x, y, z) {
16278 return (x & y) | (z & (x | y))
16279}
16280
16281function sigma0 (x, xl) {
16282 return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25)
16283}
16284
16285function sigma1 (x, xl) {
16286 return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23)
16287}
16288
16289function Gamma0 (x, xl) {
16290 return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7)
16291}
16292
16293function Gamma0l (x, xl) {
16294 return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25)
16295}
16296
16297function Gamma1 (x, xl) {
16298 return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6)
16299}
16300
16301function Gamma1l (x, xl) {
16302 return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26)
16303}
16304
16305function getCarry (a, b) {
16306 return (a >>> 0) < (b >>> 0) ? 1 : 0
16307}
16308
16309Sha512.prototype._update = function (M) {
16310 var W = this._w
16311
16312 var ah = this._ah | 0
16313 var bh = this._bh | 0
16314 var ch = this._ch | 0
16315 var dh = this._dh | 0
16316 var eh = this._eh | 0
16317 var fh = this._fh | 0
16318 var gh = this._gh | 0
16319 var hh = this._hh | 0
16320
16321 var al = this._al | 0
16322 var bl = this._bl | 0
16323 var cl = this._cl | 0
16324 var dl = this._dl | 0
16325 var el = this._el | 0
16326 var fl = this._fl | 0
16327 var gl = this._gl | 0
16328 var hl = this._hl | 0
16329
16330 for (var i = 0; i < 32; i += 2) {
16331 W[i] = M.readInt32BE(i * 4)
16332 W[i + 1] = M.readInt32BE(i * 4 + 4)
16333 }
16334 for (; i < 160; i += 2) {
16335 var xh = W[i - 15 * 2]
16336 var xl = W[i - 15 * 2 + 1]
16337 var gamma0 = Gamma0(xh, xl)
16338 var gamma0l = Gamma0l(xl, xh)
16339
16340 xh = W[i - 2 * 2]
16341 xl = W[i - 2 * 2 + 1]
16342 var gamma1 = Gamma1(xh, xl)
16343 var gamma1l = Gamma1l(xl, xh)
16344
16345 // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]
16346 var Wi7h = W[i - 7 * 2]
16347 var Wi7l = W[i - 7 * 2 + 1]
16348
16349 var Wi16h = W[i - 16 * 2]
16350 var Wi16l = W[i - 16 * 2 + 1]
16351
16352 var Wil = (gamma0l + Wi7l) | 0
16353 var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0
16354 Wil = (Wil + gamma1l) | 0
16355 Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0
16356 Wil = (Wil + Wi16l) | 0
16357 Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0
16358
16359 W[i] = Wih
16360 W[i + 1] = Wil
16361 }
16362
16363 for (var j = 0; j < 160; j += 2) {
16364 Wih = W[j]
16365 Wil = W[j + 1]
16366
16367 var majh = maj(ah, bh, ch)
16368 var majl = maj(al, bl, cl)
16369
16370 var sigma0h = sigma0(ah, al)
16371 var sigma0l = sigma0(al, ah)
16372 var sigma1h = sigma1(eh, el)
16373 var sigma1l = sigma1(el, eh)
16374
16375 // t1 = h + sigma1 + ch + K[j] + W[j]
16376 var Kih = K[j]
16377 var Kil = K[j + 1]
16378
16379 var chh = Ch(eh, fh, gh)
16380 var chl = Ch(el, fl, gl)
16381
16382 var t1l = (hl + sigma1l) | 0
16383 var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0
16384 t1l = (t1l + chl) | 0
16385 t1h = (t1h + chh + getCarry(t1l, chl)) | 0
16386 t1l = (t1l + Kil) | 0
16387 t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0
16388 t1l = (t1l + Wil) | 0
16389 t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0
16390
16391 // t2 = sigma0 + maj
16392 var t2l = (sigma0l + majl) | 0
16393 var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0
16394
16395 hh = gh
16396 hl = gl
16397 gh = fh
16398 gl = fl
16399 fh = eh
16400 fl = el
16401 el = (dl + t1l) | 0
16402 eh = (dh + t1h + getCarry(el, dl)) | 0
16403 dh = ch
16404 dl = cl
16405 ch = bh
16406 cl = bl
16407 bh = ah
16408 bl = al
16409 al = (t1l + t2l) | 0
16410 ah = (t1h + t2h + getCarry(al, t1l)) | 0
16411 }
16412
16413 this._al = (this._al + al) | 0
16414 this._bl = (this._bl + bl) | 0
16415 this._cl = (this._cl + cl) | 0
16416 this._dl = (this._dl + dl) | 0
16417 this._el = (this._el + el) | 0
16418 this._fl = (this._fl + fl) | 0
16419 this._gl = (this._gl + gl) | 0
16420 this._hl = (this._hl + hl) | 0
16421
16422 this._ah = (this._ah + ah + getCarry(this._al, al)) | 0
16423 this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0
16424 this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0
16425 this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0
16426 this._eh = (this._eh + eh + getCarry(this._el, el)) | 0
16427 this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0
16428 this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0
16429 this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0
16430}
16431
16432Sha512.prototype._hash = function () {
16433 var H = new Buffer(64)
16434
16435 function writeInt64BE (h, l, offset) {
16436 H.writeInt32BE(h, offset)
16437 H.writeInt32BE(l, offset + 4)
16438 }
16439
16440 writeInt64BE(this._ah, this._al, 0)
16441 writeInt64BE(this._bh, this._bl, 8)
16442 writeInt64BE(this._ch, this._cl, 16)
16443 writeInt64BE(this._dh, this._dl, 24)
16444 writeInt64BE(this._eh, this._el, 32)
16445 writeInt64BE(this._fh, this._fl, 40)
16446 writeInt64BE(this._gh, this._gl, 48)
16447 writeInt64BE(this._hh, this._hl, 56)
16448
16449 return H
16450}
16451
16452module.exports = Sha512
16453
16454}).call(this,require("buffer").Buffer)
16455},{"./hash":76,"buffer":5,"inherits":71}],84:[function(require,module,exports){
16456(function (Buffer){
16457const secureRandom = require('secure-random')
16458const ByteBuffer = require('bytebuffer')
16459const crypto = require('browserify-aes')
16460const assert = require('assert')
16461const PublicKey = require('./key_public')
16462const PrivateKey = require('./key_private')
16463const hash = require('./hash')
16464
16465const Long = ByteBuffer.Long;
16466
16467module.exports = {
16468 encrypt,
16469 decrypt
16470}
16471
16472/**
16473 Spec: http://localhost:3002/steem/@dantheman/how-to-encrypt-a-memo-when-transferring-steem
16474 @throws {Error|TypeError} - "Invalid Key, ..."
16475 @arg {PrivateKey} private_key - required and used for decryption
16476 @arg {PublicKey} public_key - required and used to calcualte the shared secret
16477 @arg {string} [nonce = uniqueNonce()] - assigned a random unique uint64
16478
16479 @return {object}
16480 @property {string} nonce - random or unique uint64, provides entropy when re-using the same private/public keys.
16481 @property {Buffer} message - Plain text message
16482 @property {number} checksum - shared secret checksum
16483*/
16484function encrypt(private_key, public_key, message, nonce = uniqueNonce()) {
16485 return crypt(private_key, public_key, nonce, message)
16486}
16487
16488/**
16489 Spec: http://localhost:3002/steem/@dantheman/how-to-encrypt-a-memo-when-transferring-steem
16490 @arg {PrivateKey} private_key - required and used for decryption
16491 @arg {PublicKey} public_key - required and used to calcualte the shared secret
16492 @arg {string} nonce - random or unique uint64, provides entropy when re-using the same private/public keys.
16493 @arg {Buffer} message - Encrypted or plain text message
16494 @arg {number} checksum - shared secret checksum
16495 @throws {Error|TypeError} - "Invalid Key, ..."
16496 @return {Buffer} - message
16497*/
16498function decrypt(private_key, public_key, nonce, message, checksum) {
16499 return crypt(private_key, public_key, nonce, message, checksum).message
16500}
16501
16502/**
16503 @arg {Buffer} message - Encrypted or plain text message (see checksum)
16504 @arg {number} checksum - shared secret checksum (null to encrypt, non-null to decrypt)
16505 @private
16506*/
16507function crypt(private_key, public_key, nonce, message, checksum) {
16508 private_key = toPrivateObj(private_key)
16509 if (!private_key)
16510 throw new TypeError('private_key is required')
16511
16512 public_key = toPublicObj(public_key)
16513 if (!public_key)
16514 throw new TypeError('public_key is required')
16515
16516 nonce = toLongObj(nonce)
16517 if (!nonce)
16518 throw new TypeError('nonce is required')
16519
16520 if (!Buffer.isBuffer(message)) {
16521 if (typeof message !== 'string')
16522 throw new TypeError('message should be buffer or string')
16523 message = new Buffer(message, 'binary')
16524 }
16525 if (checksum && typeof checksum !== 'number')
16526 throw new TypeError('checksum should be a number')
16527
16528 const S = private_key.getSharedSecret(public_key);
16529 let ebuf = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)
16530 ebuf.writeUint64(nonce)
16531 ebuf.append(S.toString('binary'), 'binary')
16532 ebuf = new Buffer(ebuf.copy(0, ebuf.offset).toBinary(), 'binary')
16533 const encryption_key = hash.sha512(ebuf)
16534
16535 // D E B U G
16536 // console.log('crypt', {
16537 // priv_to_pub: private_key.toPublicKey().toString(),
16538 // pub: public_key.toString(),
16539 // nonce: nonce.toString(),
16540 // message: message.length,
16541 // checksum,
16542 // S: S.toString('hex'),
16543 // encryption_key: encryption_key.toString('hex'),
16544 // })
16545
16546 const iv = encryption_key.slice(32, 48)
16547 const key = encryption_key.slice(0, 32)
16548
16549 // check is first 64 bit of sha256 hash treated as uint64_t truncated to 32 bits.
16550 let check = hash.sha256(encryption_key)
16551 check = check.slice(0, 4)
16552 const cbuf = ByteBuffer.fromBinary(check.toString('binary'), ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)
16553 check = cbuf.readUint32()
16554
16555 if (checksum) {
16556 if (check !== checksum)
16557 throw new Error('Invalid key')
16558 message = cryptoJsDecrypt(message, key, iv)
16559 } else {
16560 message = cryptoJsEncrypt(message, key, iv)
16561 }
16562 return {nonce, message, checksum: check}
16563}
16564
16565/** This method does not use a checksum, the returned data must be validated some other way.
16566 @arg {string|Buffer} ciphertext - binary format
16567 @return {Buffer}
16568*/
16569function cryptoJsDecrypt(message, key, iv) {
16570 assert(message, "Missing cipher text")
16571 message = toBinaryBuffer(message)
16572 const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv)
16573 // decipher.setAutoPadding(true)
16574 message = Buffer.concat([decipher.update(message), decipher.final()])
16575 return message
16576}
16577
16578/** This method does not use a checksum, the returned data must be validated some other way.
16579 @arg {string|Buffer} plaintext - binary format
16580 @return {Buffer} binary
16581*/
16582function cryptoJsEncrypt(message, key, iv) {
16583 assert(message, "Missing plain text")
16584 message = toBinaryBuffer(message)
16585 const cipher = crypto.createCipheriv('aes-256-cbc', key, iv)
16586 // cipher.setAutoPadding(true)
16587 message = Buffer.concat([cipher.update(message), cipher.final()])
16588 return message
16589}
16590
16591/** @return {string} unique 64 bit unsigned number string. Being time based, this is careful to never choose the same nonce twice. This value could be recorded in the blockchain for a long time.
16592*/
16593function uniqueNonce() {
16594 if(unique_nonce_entropy === null) {
16595 const b = secureRandom.randomUint8Array(2)
16596 unique_nonce_entropy = parseInt(b[0] << 8 | b[1], 10)
16597 }
16598 let long = Long.fromNumber(Date.now())
16599 const entropy = ++unique_nonce_entropy % 0xFFFF
16600 // console.log('uniqueNonce date\t', ByteBuffer.allocate(8).writeUint64(long).toHex(0))
16601 // console.log('uniqueNonce entropy\t', ByteBuffer.allocate(8).writeUint64(Long.fromNumber(entropy)).toHex(0))
16602 long = long.shiftLeft(16).or(Long.fromNumber(entropy));
16603 // console.log('uniqueNonce final\t', ByteBuffer.allocate(8).writeUint64(long).toHex(0))
16604 return long.toString()
16605}
16606let unique_nonce_entropy = null
16607// for(let i=1; i < 10; i++) key.uniqueNonce()
16608
16609const toPrivateObj = o => (o ? o.d ? o : PrivateKey.fromWif(o) : o/*null or undefined*/)
16610const toPublicObj = o => (o ? o.Q ? o : PublicKey.fromString(o) : o/*null or undefined*/)
16611const toLongObj = o => (o ? Long.isLong(o) ? o : Long.fromString(o) : o)
16612const toBinaryBuffer = o => (o ? Buffer.isBuffer(o) ? o : new Buffer(o, 'binary') : o)
16613
16614}).call(this,require("buffer").Buffer)
16615},{"./hash":89,"./key_private":90,"./key_public":91,"assert":1,"browserify-aes":42,"buffer":5,"bytebuffer":57,"secure-random":75}],85:[function(require,module,exports){
16616
16617module.exports = {
16618 address_prefix: 'EOS'
16619}
16620
16621},{}],86:[function(require,module,exports){
16622(function (Buffer){
16623var assert = require('assert') // from github.com/bitcoinjs/bitcoinjs-lib from github.com/cryptocoinjs/ecdsa
16624var crypto = require('./hash')
16625var enforceType = require('./enforce_types')
16626
16627var BigInteger = require('bigi')
16628var ECSignature = require('./ecsignature')
16629
16630// https://tools.ietf.org/html/rfc6979#section-3.2
16631function deterministicGenerateK(curve, hash, d, checkSig, nonce) {
16632
16633 enforceType('Buffer', hash)
16634 enforceType(BigInteger, d)
16635
16636 if (nonce) {
16637 hash = crypto.sha256(Buffer.concat([hash, new Buffer(nonce)]))
16638 }
16639
16640 // sanity check
16641 assert.equal(hash.length, 32, 'Hash must be 256 bit')
16642
16643 var x = d.toBuffer(32)
16644 var k = new Buffer(32)
16645 var v = new Buffer(32)
16646
16647 // Step B
16648 v.fill(1)
16649
16650 // Step C
16651 k.fill(0)
16652
16653 // Step D
16654 k = crypto.HmacSHA256(Buffer.concat([v, new Buffer([0]), x, hash]), k)
16655
16656 // Step E
16657 v = crypto.HmacSHA256(v, k)
16658
16659 // Step F
16660 k = crypto.HmacSHA256(Buffer.concat([v, new Buffer([1]), x, hash]), k)
16661
16662 // Step G
16663 v = crypto.HmacSHA256(v, k)
16664
16665 // Step H1/H2a, ignored as tlen === qlen (256 bit)
16666 // Step H2b
16667 v = crypto.HmacSHA256(v, k)
16668
16669 var T = BigInteger.fromBuffer(v)
16670
16671 // Step H3, repeat until T is within the interval [1, n - 1]
16672 while ((T.signum() <= 0) || (T.compareTo(curve.n) >= 0) || !checkSig(T)) {
16673 k = crypto.HmacSHA256(Buffer.concat([v, new Buffer([0])]), k)
16674 v = crypto.HmacSHA256(v, k)
16675
16676 // Step H1/H2a, again, ignored as tlen === qlen (256 bit)
16677 // Step H2b again
16678 v = crypto.HmacSHA256(v, k)
16679
16680 T = BigInteger.fromBuffer(v)
16681 }
16682
16683 return T
16684
16685}
16686
16687function sign(curve, hash, d, nonce) {
16688
16689 var e = BigInteger.fromBuffer(hash)
16690 var n = curve.n
16691 var G = curve.G
16692
16693 var r, s
16694 var k = deterministicGenerateK(curve, hash, d, function (k) {
16695 // find canonically valid signature
16696 var Q = G.multiply(k)
16697
16698 if (curve.isInfinity(Q)) return false
16699
16700 r = Q.affineX.mod(n)
16701 if (r.signum() === 0) return false
16702
16703 s = k.modInverse(n).multiply(e.add(d.multiply(r))).mod(n)
16704 if (s.signum() === 0) return false
16705
16706 return true
16707 }, nonce)
16708
16709 var N_OVER_TWO = n.shiftRight(1)
16710
16711 // enforce low S values, see bip62: 'low s values in signatures'
16712 if (s.compareTo(N_OVER_TWO) > 0) {
16713 s = n.subtract(s)
16714 }
16715
16716 return new ECSignature(r, s)
16717}
16718
16719function verifyRaw(curve, e, signature, Q) {
16720 var n = curve.n
16721 var G = curve.G
16722
16723 var r = signature.r
16724 var s = signature.s
16725
16726 // 1.4.1 Enforce r and s are both integers in the interval [1, n − 1]
16727 if (r.signum() <= 0 || r.compareTo(n) >= 0) return false
16728 if (s.signum() <= 0 || s.compareTo(n) >= 0) return false
16729
16730 // c = s^-1 mod n
16731 var c = s.modInverse(n)
16732
16733 // 1.4.4 Compute u1 = es^−1 mod n
16734 // u2 = rs^−1 mod n
16735 var u1 = e.multiply(c).mod(n)
16736 var u2 = r.multiply(c).mod(n)
16737
16738 // 1.4.5 Compute R = (xR, yR) = u1G + u2Q
16739 var R = G.multiplyTwo(u1, Q, u2)
16740
16741 // 1.4.5 (cont.) Enforce R is not at infinity
16742 if (curve.isInfinity(R)) return false
16743
16744 // 1.4.6 Convert the field element R.x to an integer
16745 var xR = R.affineX
16746
16747 // 1.4.7 Set v = xR mod n
16748 var v = xR.mod(n)
16749
16750 // 1.4.8 If v = r, output "valid", and if v != r, output "invalid"
16751 return v.equals(r)
16752}
16753
16754function verify(curve, hash, signature, Q) {
16755 // 1.4.2 H = Hash(M), already done by the user
16756 // 1.4.3 e = H
16757 var e = BigInteger.fromBuffer(hash)
16758 return verifyRaw(curve, e, signature, Q)
16759}
16760
16761/**
16762 * Recover a public key from a signature.
16763 *
16764 * See SEC 1: Elliptic Curve Cryptography, section 4.1.6, "Public
16765 * Key Recovery Operation".
16766 *
16767 * http://www.secg.org/download/aid-780/sec1-v2.pdf
16768 */
16769function recoverPubKey(curve, e, signature, i) {
16770 assert.strictEqual(i & 3, i, 'Recovery param is more than two bits')
16771
16772 var n = curve.n
16773 var G = curve.G
16774
16775 var r = signature.r
16776 var s = signature.s
16777
16778 assert(r.signum() > 0 && r.compareTo(n) < 0, 'Invalid r value')
16779 assert(s.signum() > 0 && s.compareTo(n) < 0, 'Invalid s value')
16780
16781 // A set LSB signifies that the y-coordinate is odd
16782 var isYOdd = i & 1
16783
16784 // The more significant bit specifies whether we should use the
16785 // first or second candidate key.
16786 var isSecondKey = i >> 1
16787
16788 // 1.1 Let x = r + jn
16789 var x = isSecondKey ? r.add(n) : r
16790 var R = curve.pointFromX(isYOdd, x)
16791
16792 // 1.4 Check that nR is at infinity
16793 var nR = R.multiply(n)
16794 assert(curve.isInfinity(nR), 'nR is not a valid curve point')
16795
16796 // Compute -e from e
16797 var eNeg = e.negate().mod(n)
16798
16799 // 1.6.1 Compute Q = r^-1 (sR - eG)
16800 // Q = r^-1 (sR + -eG)
16801 var rInv = r.modInverse(n)
16802
16803 var Q = R.multiplyTwo(s, G, eNeg).multiply(rInv)
16804 curve.validate(Q)
16805
16806 return Q
16807}
16808
16809/**
16810 * Calculate pubkey extraction parameter.
16811 *
16812 * When extracting a pubkey from a signature, we have to
16813 * distinguish four different cases. Rather than putting this
16814 * burden on the verifier, Bitcoin includes a 2-bit value with the
16815 * signature.
16816 *
16817 * This function simply tries all four cases and returns the value
16818 * that resulted in a successful pubkey recovery.
16819 */
16820function calcPubKeyRecoveryParam(curve, e, signature, Q) {
16821 for (var i = 0; i < 4; i++) {
16822 var Qprime = recoverPubKey(curve, e, signature, i)
16823
16824 // 1.6.2 Verify Q
16825 if (Qprime.equals(Q)) {
16826 return i
16827 }
16828 }
16829
16830 throw new Error('Unable to find valid recovery factor')
16831}
16832
16833module.exports = {
16834 calcPubKeyRecoveryParam: calcPubKeyRecoveryParam,
16835 deterministicGenerateK: deterministicGenerateK,
16836 recoverPubKey: recoverPubKey,
16837 sign: sign,
16838 verify: verify,
16839 verifyRaw: verifyRaw
16840}
16841
16842}).call(this,require("buffer").Buffer)
16843},{"./ecsignature":87,"./enforce_types":88,"./hash":89,"assert":1,"bigi":38,"buffer":5}],87:[function(require,module,exports){
16844(function (Buffer){
16845var assert = require('assert') // from https://github.com/bitcoinjs/bitcoinjs-lib
16846var enforceType = require('./enforce_types')
16847
16848var BigInteger = require('bigi')
16849
16850function ECSignature(r, s) {
16851 enforceType(BigInteger, r)
16852 enforceType(BigInteger, s)
16853
16854 this.r = r
16855 this.s = s
16856}
16857
16858// Import operations
16859ECSignature.parseCompact = function(buffer) {
16860 assert.equal(buffer.length, 65, 'Invalid signature length')
16861 var i = buffer.readUInt8(0) - 27
16862
16863 // At most 3 bits
16864 assert.equal(i, i & 7, 'Invalid signature parameter')
16865 var compressed = !!(i & 4)
16866
16867 // Recovery param only
16868 i = i & 3
16869
16870 var r = BigInteger.fromBuffer(buffer.slice(1, 33))
16871 var s = BigInteger.fromBuffer(buffer.slice(33))
16872
16873 return {
16874 compressed: compressed,
16875 i: i,
16876 signature: new ECSignature(r, s)
16877 }
16878}
16879
16880ECSignature.fromDER = function(buffer) {
16881 assert.equal(buffer.readUInt8(0), 0x30, 'Not a DER sequence')
16882 assert.equal(buffer.readUInt8(1), buffer.length - 2, 'Invalid sequence length')
16883 assert.equal(buffer.readUInt8(2), 0x02, 'Expected a DER integer')
16884
16885 var rLen = buffer.readUInt8(3)
16886 assert(rLen > 0, 'R length is zero')
16887
16888 var offset = 4 + rLen
16889 assert.equal(buffer.readUInt8(offset), 0x02, 'Expected a DER integer (2)')
16890
16891 var sLen = buffer.readUInt8(offset + 1)
16892 assert(sLen > 0, 'S length is zero')
16893
16894 var rB = buffer.slice(4, offset)
16895 var sB = buffer.slice(offset + 2)
16896 offset += 2 + sLen
16897
16898 if (rLen > 1 && rB.readUInt8(0) === 0x00) {
16899 assert(rB.readUInt8(1) & 0x80, 'R value excessively padded')
16900 }
16901
16902 if (sLen > 1 && sB.readUInt8(0) === 0x00) {
16903 assert(sB.readUInt8(1) & 0x80, 'S value excessively padded')
16904 }
16905
16906 assert.equal(offset, buffer.length, 'Invalid DER encoding')
16907 var r = BigInteger.fromDERInteger(rB)
16908 var s = BigInteger.fromDERInteger(sB)
16909
16910 assert(r.signum() >= 0, 'R value is negative')
16911 assert(s.signum() >= 0, 'S value is negative')
16912
16913 return new ECSignature(r, s)
16914}
16915
16916// FIXME: 0x00, 0x04, 0x80 are SIGHASH_* boundary constants, importing Transaction causes a circular dependency
16917ECSignature.parseScriptSignature = function(buffer) {
16918 var hashType = buffer.readUInt8(buffer.length - 1)
16919 var hashTypeMod = hashType & ~0x80
16920
16921 assert(hashTypeMod > 0x00 && hashTypeMod < 0x04, 'Invalid hashType')
16922
16923 return {
16924 signature: ECSignature.fromDER(buffer.slice(0, -1)),
16925 hashType: hashType
16926 }
16927}
16928
16929// Export operations
16930ECSignature.prototype.toCompact = function(i, compressed) {
16931 if (compressed) i += 4
16932 i += 27
16933
16934 var buffer = new Buffer(65)
16935 buffer.writeUInt8(i, 0)
16936
16937 this.r.toBuffer(32).copy(buffer, 1)
16938 this.s.toBuffer(32).copy(buffer, 33)
16939
16940 return buffer
16941}
16942
16943ECSignature.prototype.toDER = function() {
16944 var rBa = this.r.toDERInteger()
16945 var sBa = this.s.toDERInteger()
16946
16947 var sequence = []
16948
16949 // INTEGER
16950 sequence.push(0x02, rBa.length)
16951 sequence = sequence.concat(rBa)
16952
16953 // INTEGER
16954 sequence.push(0x02, sBa.length)
16955 sequence = sequence.concat(sBa)
16956
16957 // SEQUENCE
16958 sequence.unshift(0x30, sequence.length)
16959
16960 return new Buffer(sequence)
16961}
16962
16963ECSignature.prototype.toScriptSignature = function(hashType) {
16964 var hashTypeBuffer = new Buffer(1)
16965 hashTypeBuffer.writeUInt8(hashType, 0)
16966
16967 return Buffer.concat([this.toDER(), hashTypeBuffer])
16968}
16969
16970module.exports = ECSignature
16971
16972}).call(this,require("buffer").Buffer)
16973},{"./enforce_types":88,"assert":1,"bigi":38,"buffer":5}],88:[function(require,module,exports){
16974(function (Buffer){
16975module.exports = function enforce(type, value) { // Copied from https://github.com/bitcoinjs/bitcoinjs-lib
16976 switch (type) {
16977 case 'Array': {
16978 if (Array.isArray(value)) return
16979 break
16980 }
16981
16982 case 'Boolean': {
16983 if (typeof value === 'boolean') return
16984 break
16985 }
16986
16987 case 'Buffer': {
16988 if (Buffer.isBuffer(value)) return
16989 break
16990 }
16991
16992 case 'Number': {
16993 if (typeof value === 'number') return
16994 break
16995 }
16996
16997 case 'String': {
16998 if (typeof value === 'string') return
16999 break
17000 }
17001
17002 default: {
17003 if (getName(value.constructor) === getName(type)) return
17004 }
17005 }
17006
17007 throw new TypeError('Expected ' + (getName(type) || type) + ', got ' + value)
17008}
17009
17010function getName(fn) {
17011 // Why not fn.name: https://kangax.github.io/compat-table/es6/#function_name_property
17012 var match = fn.toString().match(/function (.*?)\(/)
17013 return match ? match[1] : null
17014}
17015
17016}).call(this,{"isBuffer":require("../../../.nvm/versions/node/v7.5.0/lib/node_modules/browserify/node_modules/is-buffer/index.js")})
17017},{"../../../.nvm/versions/node/v7.5.0/lib/node_modules/browserify/node_modules/is-buffer/index.js":10}],89:[function(require,module,exports){
17018const createHash = require('create-hash')
17019const createHmac = require('create-hmac')
17020
17021/** @arg {string|Buffer} data
17022 @arg {string} [digest = null] - 'hex', 'binary' or 'base64'
17023 @return {string|Buffer} - Buffer when digest is null, or string
17024*/
17025function sha1(data, encoding) {
17026 return createHash('sha1').update(data).digest(encoding)
17027}
17028
17029/** @arg {string|Buffer} data
17030 @arg {string} [digest = null] - 'hex', 'binary' or 'base64'
17031 @return {string|Buffer} - Buffer when digest is null, or string
17032*/
17033function sha256(data, encoding) {
17034 return createHash('sha256').update(data).digest(encoding)
17035}
17036
17037/** @arg {string|Buffer} data
17038 @arg {string} [digest = null] - 'hex', 'binary' or 'base64'
17039 @return {string|Buffer} - Buffer when digest is null, or string
17040*/
17041function sha512(data, encoding) {
17042 return createHash('sha512').update(data).digest(encoding)
17043}
17044
17045function HmacSHA256(buffer, secret) {
17046 return createHmac('sha256', secret).update(buffer).digest()
17047}
17048
17049function ripemd160(data) {
17050 return createHash('rmd160').update(data).digest()
17051}
17052
17053// function hash160(buffer) {
17054// return ripemd160(sha256(buffer))
17055// }
17056//
17057// function hash256(buffer) {
17058// return sha256(sha256(buffer))
17059// }
17060
17061//
17062// function HmacSHA512(buffer, secret) {
17063// return crypto.createHmac('sha512', secret).update(buffer).digest()
17064// }
17065
17066module.exports = {
17067 sha1: sha1,
17068 sha256: sha256,
17069 sha512: sha512,
17070 HmacSHA256: HmacSHA256,
17071 ripemd160: ripemd160
17072 // hash160: hash160,
17073 // hash256: hash256,
17074 // HmacSHA512: HmacSHA512
17075}
17076
17077},{"create-hash":59,"create-hmac":62}],90:[function(require,module,exports){
17078(function (Buffer){
17079const ecurve = require('ecurve');
17080const Point = ecurve.Point;
17081const secp256k1 = ecurve.getCurveByName('secp256k1');
17082const BigInteger = require('bigi');
17083const base58 = require('bs58');
17084const assert = require('assert');
17085const hash = require('./hash');
17086const PublicKey = require('./key_public');
17087const keyUtils = require('./key_utils');
17088
17089const G = secp256k1.G
17090const n = secp256k1.n
17091
17092class PrivateKey {
17093
17094 /**
17095 @private see static functions
17096 @param {BigInteger}
17097 */
17098 constructor(d) { this.d = d; }
17099
17100 static fromBuffer(buf) {
17101 if (!Buffer.isBuffer(buf)) {
17102 throw new Error("Expecting parameter to be a Buffer type");
17103 }
17104 if (32 !== buf.length) {
17105 console.log(`WARN: Expecting 32 bytes, instead got ${buf.length}, stack trace:`, new Error().stack);
17106 }
17107 if (buf.length === 0) {
17108 throw new Error("Empty buffer");
17109 }
17110 return new PrivateKey(BigInteger.fromBuffer(buf));
17111 }
17112
17113 /** @arg {string} seed - any length string. This is private, the same seed produces the same private key every time. */
17114 static fromSeed(seed) { // generate_private_key
17115 if (!(typeof seed === 'string')) {
17116 throw new Error('seed must be of type string');
17117 }
17118 return PrivateKey.fromBuffer(hash.sha256(seed));
17119 }
17120
17121 static isWif(text) {
17122 try {
17123 this.fromWif(text)
17124 return true
17125 } catch(e) {
17126 return false
17127 }
17128 }
17129
17130 /**
17131 @throws {AssertError|Error} parsing key
17132 @return {string} Wallet Import Format (still a secret, Not encrypted)
17133 */
17134 static fromWif(_private_wif) {
17135 var private_wif = new Buffer(base58.decode(_private_wif));
17136 var version = private_wif.readUInt8(0);
17137 assert.equal(0x80, version, `Expected version ${0x80}, instead got ${version}`);
17138 // checksum includes the version
17139 var private_key = private_wif.slice(0, -4);
17140 var checksum = private_wif.slice(-4);
17141 var new_checksum = hash.sha256(private_key);
17142 new_checksum = hash.sha256(new_checksum);
17143 new_checksum = new_checksum.slice(0, 4);
17144 if (checksum.toString() !== new_checksum.toString())
17145 throw new Error('Invalid WIF key (checksum miss-match)')
17146
17147 private_key = private_key.slice(1);
17148 return PrivateKey.fromBuffer(private_key);
17149 }
17150
17151 static getRandomKey() {
17152 return PrivateKey.fromBuffer(keyUtils.random32ByteBuffer());
17153 }
17154
17155 toWif() {
17156 var private_key = this.toBuffer();
17157 // checksum includes the version
17158 private_key = Buffer.concat([new Buffer([0x80]), private_key]);
17159 var checksum = hash.sha256(private_key);
17160 checksum = hash.sha256(checksum);
17161 checksum = checksum.slice(0, 4);
17162 var private_wif = Buffer.concat([private_key, checksum]);
17163 return base58.encode(private_wif);
17164 }
17165
17166 /** Alias for {@link toWif} */
17167 toString() {
17168 return this.toWif()
17169 }
17170
17171 /**
17172 @return {Point}
17173 */
17174 toPublicKeyPoint() {
17175 var Q;
17176 return Q = secp256k1.G.multiply(this.d);
17177 }
17178
17179 toPublic() {
17180 if (this.public_key) { return this.public_key; }
17181 return this.public_key = PublicKey.fromPoint(this.toPublicKeyPoint());
17182 }
17183
17184 toBuffer() {
17185 return this.d.toBuffer(32);
17186 }
17187
17188 /** ECIES */
17189 getSharedSecret(public_key) {
17190 public_key = toPublic(public_key)
17191 let KB = public_key.toUncompressed().toBuffer()
17192 let KBP = Point.fromAffine(
17193 secp256k1,
17194 BigInteger.fromBuffer( KB.slice( 1,33 )), // x
17195 BigInteger.fromBuffer( KB.slice( 33,65 )) // y
17196 )
17197 let r = this.toBuffer()
17198 let P = KBP.multiply(BigInteger.fromBuffer(r))
17199 let S = P.affineX.toBuffer({size: 32})
17200 // SHA512 used in ECIES
17201 return hash.sha512(S)
17202 }
17203
17204 // /** ECIES (does not always match the Point.fromAffine version above) */
17205 // getSharedSecret(public_key){
17206 // public_key = toPublic(public_key)
17207 // var P = public_key.Q.multiply( this.d );
17208 // var S = P.affineX.toBuffer({size: 32});
17209 // // ECIES, adds an extra sha512
17210 // return hash.sha512(S);
17211 // }
17212
17213 /** @throws {Error} - overflow of the key could not be derived */
17214 child( offset ) {
17215 offset = Buffer.concat([ this.toPublicKey().toBuffer(), offset ])
17216 offset = hash.sha256( offset )
17217 let c = BigInteger.fromBuffer(offset)
17218
17219 if (c.compareTo(n) >= 0)
17220 throw new Error("Child offset went out of bounds, try again")
17221
17222 let derived = this.d.add(c)//.mod(n)
17223
17224 if( derived.signum() === 0 )
17225 throw new Error("Child offset derived to an invalid key, try again")
17226
17227 return new PrivateKey( derived )
17228 }
17229
17230 // toByteBuffer() {
17231 // var b = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN);
17232 // this.appendByteBuffer(b);
17233 // return b.copy(0, b.offset);
17234 // }
17235
17236 static fromHex(hex) {
17237 return PrivateKey.fromBuffer(new Buffer(hex, 'hex'));
17238 }
17239
17240 toHex() {
17241 return this.toBuffer().toString('hex');
17242 }
17243
17244 toPublicKey() {
17245 return this.toPublic()
17246 }
17247
17248 /* </helper_functions> */
17249}
17250
17251module.exports = PrivateKey;
17252
17253const toPublic = data => data == null ? data :
17254 data.Q ? data : PublicKey.fromStringOrThrow(data)
17255
17256}).call(this,require("buffer").Buffer)
17257},{"./hash":89,"./key_public":91,"./key_utils":92,"assert":1,"bigi":38,"bs58":55,"buffer":5,"ecurve":66}],91:[function(require,module,exports){
17258(function (Buffer){
17259const BigInteger = require('bigi');
17260const ecurve = require('ecurve');
17261const secp256k1 = ecurve.getCurveByName('secp256k1');
17262const base58 = require('bs58');
17263const hash = require('./hash');
17264const config = require('./config');
17265const assert = require('assert');
17266
17267var G = secp256k1.G
17268var n = secp256k1.n
17269
17270class PublicKey {
17271
17272 /** @param {ecurve.Point} public key */
17273 constructor(Q) { this.Q = Q; }
17274
17275 static fromBinary(bin) {
17276 return PublicKey.fromBuffer(new Buffer(bin, 'binary'));
17277 }
17278
17279 static fromBuffer(buffer) {
17280 return new PublicKey(ecurve.Point.decodeFrom(secp256k1, buffer));
17281 }
17282
17283 toBuffer(compressed = this.Q.compressed) {
17284 return this.Q.getEncoded(compressed);
17285 }
17286
17287 static fromPoint(point) {
17288 return new PublicKey(point);
17289 }
17290
17291 toUncompressed() {
17292 var buf = this.Q.getEncoded(false);
17293 var point = ecurve.Point.decodeFrom(secp256k1, buf);
17294 return PublicKey.fromPoint(point);
17295 }
17296
17297 /** bts::blockchain::address (unique but not a full public key) */
17298 toBlockchainAddress() {
17299 var pub_buf = this.toBuffer();
17300 var pub_sha = hash.sha512(pub_buf);
17301 return hash.ripemd160(pub_sha);
17302 }
17303
17304 toString(address_prefix = config.address_prefix) {
17305 return this.toPublicKeyString(address_prefix)
17306 }
17307
17308 /**
17309 Full public key
17310 {return} string
17311 */
17312 toPublicKeyString(address_prefix = config.address_prefix) {
17313 if(this.pubdata) return address_prefix + this.pubdata
17314 const pub_buf = this.toBuffer();
17315 const checksum = hash.ripemd160(pub_buf);
17316 const addy = Buffer.concat([pub_buf, checksum.slice(0, 4)]);
17317 this.pubdata = base58.encode(addy)
17318 return address_prefix + this.pubdata;
17319 }
17320
17321 /**
17322 @arg {string} public_key - like STMXyz...
17323 @arg {string} address_prefix - like STM
17324 @return PublicKey or `null` (if the public_key string is invalid)
17325 @deprecated fromPublicKeyString (use fromString instead)
17326 */
17327 static fromString(public_key, address_prefix = config.address_prefix) {
17328 try {
17329 return PublicKey.fromStringOrThrow(public_key, address_prefix)
17330 } catch (e) {
17331 return null;
17332 }
17333 }
17334
17335 /**
17336 @arg {string} public_key - like STMXyz...
17337 @arg {string} address_prefix - like STM
17338 @throws {Error} if public key is invalid
17339 @return PublicKey
17340 */
17341 static fromStringOrThrow(public_key, address_prefix = config.address_prefix) {
17342 var prefix = public_key.slice(0, address_prefix.length);
17343 assert.equal(
17344 address_prefix, prefix,
17345 `Expecting key to begin with ${address_prefix}, instead got ${prefix}`);
17346 public_key = public_key.slice(address_prefix.length);
17347
17348 public_key = new Buffer(base58.decode(public_key), 'binary');
17349 var checksum = public_key.slice(-4);
17350 public_key = public_key.slice(0, -4);
17351 var new_checksum = hash.ripemd160(public_key);
17352 new_checksum = new_checksum.slice(0, 4);
17353 assert.deepEqual(checksum, new_checksum, 'Checksum did not match');
17354 return PublicKey.fromBuffer(public_key);
17355 }
17356
17357 toAddressString(address_prefix = config.address_prefix) {
17358 var pub_buf = this.toBuffer();
17359 var pub_sha = hash.sha512(pub_buf);
17360 var addy = hash.ripemd160(pub_sha);
17361 var checksum = hash.ripemd160(addy);
17362 addy = Buffer.concat([addy, checksum.slice(0, 4)]);
17363 return address_prefix + base58.encode(addy);
17364 }
17365
17366 toPtsAddy() {
17367 var pub_buf = this.toBuffer();
17368 var pub_sha = hash.sha256(pub_buf);
17369 var addy = hash.ripemd160(pub_sha);
17370 addy = Buffer.concat([new Buffer([0x38]), addy]); //version 56(decimal)
17371
17372 var checksum = hash.sha256(addy);
17373 checksum = hash.sha256(checksum);
17374
17375 addy = Buffer.concat([addy, checksum.slice(0, 4)]);
17376 return base58.encode(addy);
17377 }
17378
17379 child( offset ) {
17380
17381 assert(Buffer.isBuffer(offset), "Buffer required: offset")
17382 assert.equal(offset.length, 32, "offset length")
17383
17384 offset = Buffer.concat([ this.toBuffer(), offset ])
17385 offset = hash.sha256( offset )
17386
17387 let c = BigInteger.fromBuffer( offset )
17388
17389 if (c.compareTo(n) >= 0)
17390 throw new Error("Child offset went out of bounds, try again")
17391
17392
17393 let cG = G.multiply(c)
17394 let Qprime = this.Q.add(cG)
17395
17396 if( secp256k1.isInfinity(Qprime) )
17397 throw new Error("Child offset derived to an invalid key, try again")
17398
17399 return PublicKey.fromPoint(Qprime)
17400 }
17401
17402 // toByteBuffer() {
17403 // var b = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN);
17404 // this.appendByteBuffer(b);
17405 // return b.copy(0, b.offset);
17406 // }
17407
17408 static fromHex(hex) {
17409 return PublicKey.fromBuffer(new Buffer(hex, 'hex'));
17410 }
17411
17412 toHex() {
17413 return this.toBuffer().toString('hex');
17414 }
17415
17416 static fromStringHex(hex) {
17417 return PublicKey.fromString(new Buffer(hex, 'hex'));
17418 }
17419
17420 /* </HEX> */
17421}
17422
17423
17424module.exports = PublicKey;
17425
17426}).call(this,require("buffer").Buffer)
17427},{"./config":85,"./hash":89,"assert":1,"bigi":38,"bs58":55,"buffer":5,"ecurve":66}],92:[function(require,module,exports){
17428(function (Buffer){
17429
17430const secureRandom = require('secure-random');
17431const PrivateKey = require('./key_private');
17432const hash = require('./hash');
17433
17434module.exports = {
17435
17436 /** @return a random buffer obtained from the secure random number generator. Additional entropy is used. */
17437 random32ByteBuffer() {
17438 const hash_array = []
17439 hash_array.push(hash.sha256(cpuEntropy(128)))
17440 hash_array.push(secureRandom.randomBuffer(32))
17441 return hash.sha256(Buffer.concat(hash_array))
17442 },
17443
17444};
17445
17446/**
17447 A week random number generator can run out of entropy. This should ensure even the worst random number implementation will be reasonably safe.
17448
17449 @return {string} sequence bits gathered by measuring variations in the CPU speed during floating point operations. Apply a hash function to the string to resize.
17450*/
17451function cpuEntropy(bits) {
17452 let collected = ''
17453 let lastCount = null
17454 while(collected.length < bits) {
17455 const count = floatingPointCount()
17456 if(lastCount != null) {
17457 const delta = Math.abs(count - lastCount)
17458 if(delta < 128) {
17459 // console.log('skipping, low entropy', delta)
17460 continue
17461 }
17462 const bit = delta % 2
17463 collected += String(bit)
17464 }
17465 lastCount = count
17466 }
17467 return collected
17468}
17469
17470
17471function floatingPointCount() {
17472 const workMinMs = 7
17473 const d = Date.now()
17474 let i = 0, x = 0
17475 while (Date.now() < d + workMinMs + 1) {
17476 x = Math.sin(Math.sqrt(Math.log(++i + x)))
17477 }
17478 return i
17479}
17480
17481}).call(this,require("buffer").Buffer)
17482},{"./hash":89,"./key_private":90,"buffer":5,"secure-random":75}],93:[function(require,module,exports){
17483(function (Buffer){
17484var ecdsa = require('./ecdsa');
17485var hash = require('./hash');
17486var curve = require('ecurve').getCurveByName('secp256k1');
17487var assert = require('assert');
17488var BigInteger = require('bigi');
17489var PublicKey = require('./key_public');
17490var PrivateKey = require('./key_private');
17491
17492class Signature {
17493
17494 constructor(r1, s1, i1) {
17495 this.r = r1;
17496 this.s = s1;
17497 this.i = i1;
17498 assert.equal(this.r != null, true, 'Missing parameter');
17499 assert.equal(this.s != null, true, 'Missing parameter');
17500 assert.equal(this.i != null, true, 'Missing parameter');
17501 }
17502
17503 static fromBuffer(buf) {
17504 var i, r, s;
17505 assert.equal(buf.length, 65, 'Invalid signature length');
17506 i = buf.readUInt8(0);
17507 assert.equal(i - 27, i - 27 & 7, 'Invalid signature parameter');
17508 r = BigInteger.fromBuffer(buf.slice(1, 33));
17509 s = BigInteger.fromBuffer(buf.slice(33));
17510 return new Signature(r, s, i);
17511 };
17512
17513 toBuffer() {
17514 var buf;
17515 buf = new Buffer(65);
17516 buf.writeUInt8(this.i, 0);
17517 this.r.toBuffer(32).copy(buf, 1);
17518 this.s.toBuffer(32).copy(buf, 33);
17519 return buf;
17520 };
17521
17522 recoverPublicKeyFromBuffer(buffer) {
17523 return this.recoverPublicKey(hash.sha256(buffer));
17524 };
17525
17526 /**
17527 @return {PublicKey}
17528 */
17529 recoverPublicKey(sha256_buffer) {
17530 let Q, e, i;
17531 e = BigInteger.fromBuffer(sha256_buffer);
17532 i = this.i;
17533 i -= 27;
17534 i = i & 3;
17535 Q = ecdsa.recoverPubKey(curve, e, this, i);
17536 return PublicKey.fromPoint(Q);
17537 };
17538
17539
17540 /**
17541 @param {Buffer} buf
17542 @param {PrivateKey} private_key
17543 @return {Signature}
17544 */
17545 static signBuffer(buf, private_key) {
17546 var _hash = hash.sha256(buf);
17547 return Signature.signBufferSha256(_hash, private_key)
17548 }
17549
17550 /** Sign a buffer of exactally 32 bytes in size (sha256(text))
17551 @param {Buffer} buf - 32 bytes binary
17552 @param {PrivateKey} private_key
17553 @return {Signature}
17554 */
17555 static signBufferSha256(buf_sha256, private_key) {
17556 if( buf_sha256.length !== 32 || ! Buffer.isBuffer(buf_sha256) )
17557 throw new Error("buf_sha256: 32 byte buffer requred")
17558 private_key = toPrivateObj(private_key)
17559 assert(private_key, 'private_key required')
17560
17561 var der, e, ecsignature, i, lenR, lenS, nonce;
17562 i = null;
17563 nonce = 0;
17564 e = BigInteger.fromBuffer(buf_sha256);
17565 while (true) {
17566 ecsignature = ecdsa.sign(curve, buf_sha256, private_key.d, nonce++);
17567 der = ecsignature.toDER();
17568 lenR = der[3];
17569 lenS = der[5 + lenR];
17570 if (lenR === 32 && lenS === 32) {
17571 i = ecdsa.calcPubKeyRecoveryParam(curve, e, ecsignature, private_key.toPublicKey().Q);
17572 i += 4; // compressed
17573 i += 27; // compact // 24 or 27 :( forcing odd-y 2nd key candidate)
17574 break;
17575 }
17576 if (nonce % 10 === 0) {
17577 console.log("WARN: " + nonce + " attempts to find canonical signature");
17578 }
17579 }
17580 return new Signature(ecsignature.r, ecsignature.s, i);
17581 };
17582
17583 static sign(string, private_key) {
17584 return Signature.signBuffer(new Buffer(string), private_key);
17585 };
17586
17587
17588 /**
17589 @param {Buffer} un-hashed
17590 @param {./PublicKey}
17591 @return {boolean}
17592 */
17593 verifyBuffer(buf, public_key) {
17594 var _hash = hash.sha256(buf);
17595 return this.verifyHash(_hash, public_key);
17596 };
17597
17598 verifyHash(hash, public_key) {
17599 assert.equal(hash.length, 32, "A SHA 256 should be 32 bytes long, instead got " + hash.length);
17600 return ecdsa.verify(curve, hash, {
17601 r: this.r,
17602 s: this.s
17603 }, public_key.Q);
17604 };
17605
17606
17607 // toByteBuffer() {
17608 // var b;
17609 // b = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN);
17610 // this.appendByteBuffer(b);
17611 // return b.copy(0, b.offset);
17612 // };
17613
17614 static fromHex(hex) {
17615 return Signature.fromBuffer(new Buffer(hex, "hex"));
17616 };
17617
17618 toHex() {
17619 return this.toBuffer().toString("hex");
17620 };
17621
17622 static signHex(hex, private_key) {
17623 var buf;
17624 buf = new Buffer(hex, 'hex');
17625 return Signature.signBuffer(buf, private_key);
17626 };
17627
17628 verifyHex(hex, public_key) {
17629 var buf;
17630 buf = new Buffer(hex, 'hex');
17631 return this.verifyBuffer(buf, public_key);
17632 };
17633
17634}
17635const toPrivateObj = o => (o ? o.d ? o : PrivateKey.fromWif(o) : o/*null or undefined*/)
17636module.exports = Signature;
17637
17638}).call(this,require("buffer").Buffer)
17639},{"./ecdsa":86,"./hash":89,"./key_private":90,"./key_public":91,"assert":1,"bigi":38,"buffer":5,"ecurve":66}]},{},[34])(34)
17640});
\No newline at end of file