blob: 92a3abbdbd58ae275861a03db8df750c6e739fc4 [file] [log] [blame]
Yang Guo4fd355c2019-09-19 10:59:03 +02001/*!
2 * The buffer module from node.js, for the browser.
3 *
4 * @author Feross Aboukhadijeh <https://feross.org>
5 * @license MIT
6 */
7/* eslint-disable no-proto */
8
9'use strict'
10
11var base64 = require('base64-js')
12var ieee754 = require('ieee754')
Lorne Mitchelldb3885d2019-10-24 21:53:01 +000013var customInspectSymbol = typeof Symbol === 'function' ? Symbol.for('nodejs.util.inspect.custom') : null
Yang Guo4fd355c2019-09-19 10:59:03 +020014
15exports.Buffer = Buffer
16exports.SlowBuffer = SlowBuffer
17exports.INSPECT_MAX_BYTES = 50
18
19var K_MAX_LENGTH = 0x7fffffff
20exports.kMaxLength = K_MAX_LENGTH
21
22/**
23 * If `Buffer.TYPED_ARRAY_SUPPORT`:
24 * === true Use Uint8Array implementation (fastest)
25 * === false Print warning and recommend using `buffer` v4.x which has an Object
26 * implementation (most compatible, even IE6)
27 *
28 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
29 * Opera 11.6+, iOS 4.2+.
30 *
31 * We report that the browser does not support typed arrays if the are not subclassable
32 * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
33 * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
34 * for __proto__ and has a buggy typed array implementation.
35 */
36Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
37
38if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
39 typeof console.error === 'function') {
40 console.error(
41 'This browser lacks typed array (Uint8Array) support which is required by ' +
42 '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
43 )
44}
45
46function typedArraySupport () {
47 // Can typed array instances can be augmented?
48 try {
49 var arr = new Uint8Array(1)
50 var proto = { foo: function () { return 42 } }
51 Object.setPrototypeOf(proto, Uint8Array.prototype)
52 Object.setPrototypeOf(arr, proto)
53 return arr.foo() === 42
54 } catch (e) {
55 return false
56 }
57}
58
59Object.defineProperty(Buffer.prototype, 'parent', {
60 enumerable: true,
61 get: function () {
62 if (!Buffer.isBuffer(this)) return undefined
63 return this.buffer
64 }
65})
66
67Object.defineProperty(Buffer.prototype, 'offset', {
68 enumerable: true,
69 get: function () {
70 if (!Buffer.isBuffer(this)) return undefined
71 return this.byteOffset
72 }
73})
74
75function createBuffer (length) {
76 if (length > K_MAX_LENGTH) {
77 throw new RangeError('The value "' + length + '" is invalid for option "size"')
78 }
79 // Return an augmented `Uint8Array` instance
80 var buf = new Uint8Array(length)
81 Object.setPrototypeOf(buf, Buffer.prototype)
82 return buf
83}
84
85/**
86 * The Buffer constructor returns instances of `Uint8Array` that have their
87 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
88 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
89 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
90 * returns a single octet.
91 *
92 * The `Uint8Array` prototype remains unmodified.
93 */
94
95function Buffer (arg, encodingOrOffset, length) {
96 // Common case.
97 if (typeof arg === 'number') {
98 if (typeof encodingOrOffset === 'string') {
99 throw new TypeError(
100 'The "string" argument must be of type string. Received type number'
101 )
102 }
103 return allocUnsafe(arg)
104 }
105 return from(arg, encodingOrOffset, length)
106}
107
108// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
109if (typeof Symbol !== 'undefined' && Symbol.species != null &&
110 Buffer[Symbol.species] === Buffer) {
111 Object.defineProperty(Buffer, Symbol.species, {
112 value: null,
113 configurable: true,
114 enumerable: false,
115 writable: false
116 })
117}
118
119Buffer.poolSize = 8192 // not used by this implementation
120
121function from (value, encodingOrOffset, length) {
122 if (typeof value === 'string') {
123 return fromString(value, encodingOrOffset)
124 }
125
126 if (ArrayBuffer.isView(value)) {
127 return fromArrayLike(value)
128 }
129
130 if (value == null) {
131 throw new TypeError(
132 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
133 'or Array-like Object. Received type ' + (typeof value)
134 )
135 }
136
137 if (isInstance(value, ArrayBuffer) ||
138 (value && isInstance(value.buffer, ArrayBuffer))) {
139 return fromArrayBuffer(value, encodingOrOffset, length)
140 }
141
142 if (typeof value === 'number') {
143 throw new TypeError(
144 'The "value" argument must not be of type number. Received type number'
145 )
146 }
147
148 var valueOf = value.valueOf && value.valueOf()
149 if (valueOf != null && valueOf !== value) {
150 return Buffer.from(valueOf, encodingOrOffset, length)
151 }
152
153 var b = fromObject(value)
154 if (b) return b
155
156 if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
157 typeof value[Symbol.toPrimitive] === 'function') {
158 return Buffer.from(
159 value[Symbol.toPrimitive]('string'), encodingOrOffset, length
160 )
161 }
162
163 throw new TypeError(
164 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
165 'or Array-like Object. Received type ' + (typeof value)
166 )
167}
168
169/**
170 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
171 * if value is a number.
172 * Buffer.from(str[, encoding])
173 * Buffer.from(array)
174 * Buffer.from(buffer)
175 * Buffer.from(arrayBuffer[, byteOffset[, length]])
176 **/
177Buffer.from = function (value, encodingOrOffset, length) {
178 return from(value, encodingOrOffset, length)
179}
180
181// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
182// https://github.com/feross/buffer/pull/148
183Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype)
184Object.setPrototypeOf(Buffer, Uint8Array)
185
186function assertSize (size) {
187 if (typeof size !== 'number') {
188 throw new TypeError('"size" argument must be of type number')
189 } else if (size < 0) {
190 throw new RangeError('The value "' + size + '" is invalid for option "size"')
191 }
192}
193
194function alloc (size, fill, encoding) {
195 assertSize(size)
196 if (size <= 0) {
197 return createBuffer(size)
198 }
199 if (fill !== undefined) {
200 // Only pay attention to encoding if it's a string. This
201 // prevents accidentally sending in a number that would
202 // be interpretted as a start offset.
203 return typeof encoding === 'string'
204 ? createBuffer(size).fill(fill, encoding)
205 : createBuffer(size).fill(fill)
206 }
207 return createBuffer(size)
208}
209
210/**
211 * Creates a new filled Buffer instance.
212 * alloc(size[, fill[, encoding]])
213 **/
214Buffer.alloc = function (size, fill, encoding) {
215 return alloc(size, fill, encoding)
216}
217
218function allocUnsafe (size) {
219 assertSize(size)
220 return createBuffer(size < 0 ? 0 : checked(size) | 0)
221}
222
223/**
224 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
225 * */
226Buffer.allocUnsafe = function (size) {
227 return allocUnsafe(size)
228}
229/**
230 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
231 */
232Buffer.allocUnsafeSlow = function (size) {
233 return allocUnsafe(size)
234}
235
236function fromString (string, encoding) {
237 if (typeof encoding !== 'string' || encoding === '') {
238 encoding = 'utf8'
239 }
240
241 if (!Buffer.isEncoding(encoding)) {
242 throw new TypeError('Unknown encoding: ' + encoding)
243 }
244
245 var length = byteLength(string, encoding) | 0
246 var buf = createBuffer(length)
247
248 var actual = buf.write(string, encoding)
249
250 if (actual !== length) {
251 // Writing a hex string, for example, that contains invalid characters will
252 // cause everything after the first invalid character to be ignored. (e.g.
253 // 'abxxcd' will be treated as 'ab')
254 buf = buf.slice(0, actual)
255 }
256
257 return buf
258}
259
260function fromArrayLike (array) {
261 var length = array.length < 0 ? 0 : checked(array.length) | 0
262 var buf = createBuffer(length)
263 for (var i = 0; i < length; i += 1) {
264 buf[i] = array[i] & 255
265 }
266 return buf
267}
268
269function fromArrayBuffer (array, byteOffset, length) {
270 if (byteOffset < 0 || array.byteLength < byteOffset) {
271 throw new RangeError('"offset" is outside of buffer bounds')
272 }
273
274 if (array.byteLength < byteOffset + (length || 0)) {
275 throw new RangeError('"length" is outside of buffer bounds')
276 }
277
278 var buf
279 if (byteOffset === undefined && length === undefined) {
280 buf = new Uint8Array(array)
281 } else if (length === undefined) {
282 buf = new Uint8Array(array, byteOffset)
283 } else {
284 buf = new Uint8Array(array, byteOffset, length)
285 }
286
287 // Return an augmented `Uint8Array` instance
288 Object.setPrototypeOf(buf, Buffer.prototype)
289
290 return buf
291}
292
293function fromObject (obj) {
294 if (Buffer.isBuffer(obj)) {
295 var len = checked(obj.length) | 0
296 var buf = createBuffer(len)
297
298 if (buf.length === 0) {
299 return buf
300 }
301
302 obj.copy(buf, 0, 0, len)
303 return buf
304 }
305
306 if (obj.length !== undefined) {
307 if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
308 return createBuffer(0)
309 }
310 return fromArrayLike(obj)
311 }
312
313 if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
314 return fromArrayLike(obj.data)
315 }
316}
317
318function checked (length) {
319 // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
320 // length is NaN (which is otherwise coerced to zero.)
321 if (length >= K_MAX_LENGTH) {
322 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
323 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
324 }
325 return length | 0
326}
327
328function SlowBuffer (length) {
329 if (+length != length) { // eslint-disable-line eqeqeq
330 length = 0
331 }
332 return Buffer.alloc(+length)
333}
334
335Buffer.isBuffer = function isBuffer (b) {
336 return b != null && b._isBuffer === true &&
337 b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
338}
339
340Buffer.compare = function compare (a, b) {
341 if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
342 if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
343 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
344 throw new TypeError(
345 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
346 )
347 }
348
349 if (a === b) return 0
350
351 var x = a.length
352 var y = b.length
353
354 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
355 if (a[i] !== b[i]) {
356 x = a[i]
357 y = b[i]
358 break
359 }
360 }
361
362 if (x < y) return -1
363 if (y < x) return 1
364 return 0
365}
366
367Buffer.isEncoding = function isEncoding (encoding) {
368 switch (String(encoding).toLowerCase()) {
369 case 'hex':
370 case 'utf8':
371 case 'utf-8':
372 case 'ascii':
373 case 'latin1':
374 case 'binary':
375 case 'base64':
376 case 'ucs2':
377 case 'ucs-2':
378 case 'utf16le':
379 case 'utf-16le':
380 return true
381 default:
382 return false
383 }
384}
385
386Buffer.concat = function concat (list, length) {
387 if (!Array.isArray(list)) {
388 throw new TypeError('"list" argument must be an Array of Buffers')
389 }
390
391 if (list.length === 0) {
392 return Buffer.alloc(0)
393 }
394
395 var i
396 if (length === undefined) {
397 length = 0
398 for (i = 0; i < list.length; ++i) {
399 length += list[i].length
400 }
401 }
402
403 var buffer = Buffer.allocUnsafe(length)
404 var pos = 0
405 for (i = 0; i < list.length; ++i) {
406 var buf = list[i]
407 if (isInstance(buf, Uint8Array)) {
408 buf = Buffer.from(buf)
409 }
410 if (!Buffer.isBuffer(buf)) {
411 throw new TypeError('"list" argument must be an Array of Buffers')
412 }
413 buf.copy(buffer, pos)
414 pos += buf.length
415 }
416 return buffer
417}
418
419function byteLength (string, encoding) {
420 if (Buffer.isBuffer(string)) {
421 return string.length
422 }
423 if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
424 return string.byteLength
425 }
426 if (typeof string !== 'string') {
427 throw new TypeError(
428 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
429 'Received type ' + typeof string
430 )
431 }
432
433 var len = string.length
434 var mustMatch = (arguments.length > 2 && arguments[2] === true)
435 if (!mustMatch && len === 0) return 0
436
437 // Use a for loop to avoid recursion
438 var loweredCase = false
439 for (;;) {
440 switch (encoding) {
441 case 'ascii':
442 case 'latin1':
443 case 'binary':
444 return len
445 case 'utf8':
446 case 'utf-8':
447 return utf8ToBytes(string).length
448 case 'ucs2':
449 case 'ucs-2':
450 case 'utf16le':
451 case 'utf-16le':
452 return len * 2
453 case 'hex':
454 return len >>> 1
455 case 'base64':
456 return base64ToBytes(string).length
457 default:
458 if (loweredCase) {
459 return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
460 }
461 encoding = ('' + encoding).toLowerCase()
462 loweredCase = true
463 }
464 }
465}
466Buffer.byteLength = byteLength
467
468function slowToString (encoding, start, end) {
469 var loweredCase = false
470
471 // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
472 // property of a typed array.
473
474 // This behaves neither like String nor Uint8Array in that we set start/end
475 // to their upper/lower bounds if the value passed is out of range.
476 // undefined is handled specially as per ECMA-262 6th Edition,
477 // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
478 if (start === undefined || start < 0) {
479 start = 0
480 }
481 // Return early if start > this.length. Done here to prevent potential uint32
482 // coercion fail below.
483 if (start > this.length) {
484 return ''
485 }
486
487 if (end === undefined || end > this.length) {
488 end = this.length
489 }
490
491 if (end <= 0) {
492 return ''
493 }
494
495 // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
496 end >>>= 0
497 start >>>= 0
498
499 if (end <= start) {
500 return ''
501 }
502
503 if (!encoding) encoding = 'utf8'
504
505 while (true) {
506 switch (encoding) {
507 case 'hex':
508 return hexSlice(this, start, end)
509
510 case 'utf8':
511 case 'utf-8':
512 return utf8Slice(this, start, end)
513
514 case 'ascii':
515 return asciiSlice(this, start, end)
516
517 case 'latin1':
518 case 'binary':
519 return latin1Slice(this, start, end)
520
521 case 'base64':
522 return base64Slice(this, start, end)
523
524 case 'ucs2':
525 case 'ucs-2':
526 case 'utf16le':
527 case 'utf-16le':
528 return utf16leSlice(this, start, end)
529
530 default:
531 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
532 encoding = (encoding + '').toLowerCase()
533 loweredCase = true
534 }
535 }
536}
537
538// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
539// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
540// reliably in a browserify context because there could be multiple different
541// copies of the 'buffer' package in use. This method works even for Buffer
542// instances that were created from another copy of the `buffer` package.
543// See: https://github.com/feross/buffer/issues/154
544Buffer.prototype._isBuffer = true
545
546function swap (b, n, m) {
547 var i = b[n]
548 b[n] = b[m]
549 b[m] = i
550}
551
552Buffer.prototype.swap16 = function swap16 () {
553 var len = this.length
554 if (len % 2 !== 0) {
555 throw new RangeError('Buffer size must be a multiple of 16-bits')
556 }
557 for (var i = 0; i < len; i += 2) {
558 swap(this, i, i + 1)
559 }
560 return this
561}
562
563Buffer.prototype.swap32 = function swap32 () {
564 var len = this.length
565 if (len % 4 !== 0) {
566 throw new RangeError('Buffer size must be a multiple of 32-bits')
567 }
568 for (var i = 0; i < len; i += 4) {
569 swap(this, i, i + 3)
570 swap(this, i + 1, i + 2)
571 }
572 return this
573}
574
575Buffer.prototype.swap64 = function swap64 () {
576 var len = this.length
577 if (len % 8 !== 0) {
578 throw new RangeError('Buffer size must be a multiple of 64-bits')
579 }
580 for (var i = 0; i < len; i += 8) {
581 swap(this, i, i + 7)
582 swap(this, i + 1, i + 6)
583 swap(this, i + 2, i + 5)
584 swap(this, i + 3, i + 4)
585 }
586 return this
587}
588
589Buffer.prototype.toString = function toString () {
590 var length = this.length
591 if (length === 0) return ''
592 if (arguments.length === 0) return utf8Slice(this, 0, length)
593 return slowToString.apply(this, arguments)
594}
595
596Buffer.prototype.toLocaleString = Buffer.prototype.toString
597
598Buffer.prototype.equals = function equals (b) {
599 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
600 if (this === b) return true
601 return Buffer.compare(this, b) === 0
602}
603
604Buffer.prototype.inspect = function inspect () {
605 var str = ''
606 var max = exports.INSPECT_MAX_BYTES
607 str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
608 if (this.length > max) str += ' ... '
609 return '<Buffer ' + str + '>'
610}
611if (customInspectSymbol) {
612 Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect
613}
614
615Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
616 if (isInstance(target, Uint8Array)) {
617 target = Buffer.from(target, target.offset, target.byteLength)
618 }
619 if (!Buffer.isBuffer(target)) {
620 throw new TypeError(
621 'The "target" argument must be one of type Buffer or Uint8Array. ' +
622 'Received type ' + (typeof target)
623 )
624 }
625
626 if (start === undefined) {
627 start = 0
628 }
629 if (end === undefined) {
630 end = target ? target.length : 0
631 }
632 if (thisStart === undefined) {
633 thisStart = 0
634 }
635 if (thisEnd === undefined) {
636 thisEnd = this.length
637 }
638
639 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
640 throw new RangeError('out of range index')
641 }
642
643 if (thisStart >= thisEnd && start >= end) {
644 return 0
645 }
646 if (thisStart >= thisEnd) {
647 return -1
648 }
649 if (start >= end) {
650 return 1
651 }
652
653 start >>>= 0
654 end >>>= 0
655 thisStart >>>= 0
656 thisEnd >>>= 0
657
658 if (this === target) return 0
659
660 var x = thisEnd - thisStart
661 var y = end - start
662 var len = Math.min(x, y)
663
664 var thisCopy = this.slice(thisStart, thisEnd)
665 var targetCopy = target.slice(start, end)
666
667 for (var i = 0; i < len; ++i) {
668 if (thisCopy[i] !== targetCopy[i]) {
669 x = thisCopy[i]
670 y = targetCopy[i]
671 break
672 }
673 }
674
675 if (x < y) return -1
676 if (y < x) return 1
677 return 0
678}
679
680// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
681// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
682//
683// Arguments:
684// - buffer - a Buffer to search
685// - val - a string, Buffer, or number
686// - byteOffset - an index into `buffer`; will be clamped to an int32
687// - encoding - an optional encoding, relevant is val is a string
688// - dir - true for indexOf, false for lastIndexOf
689function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
690 // Empty buffer means no match
691 if (buffer.length === 0) return -1
692
693 // Normalize byteOffset
694 if (typeof byteOffset === 'string') {
695 encoding = byteOffset
696 byteOffset = 0
697 } else if (byteOffset > 0x7fffffff) {
698 byteOffset = 0x7fffffff
699 } else if (byteOffset < -0x80000000) {
700 byteOffset = -0x80000000
701 }
702 byteOffset = +byteOffset // Coerce to Number.
703 if (numberIsNaN(byteOffset)) {
704 // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
705 byteOffset = dir ? 0 : (buffer.length - 1)
706 }
707
708 // Normalize byteOffset: negative offsets start from the end of the buffer
709 if (byteOffset < 0) byteOffset = buffer.length + byteOffset
710 if (byteOffset >= buffer.length) {
711 if (dir) return -1
712 else byteOffset = buffer.length - 1
713 } else if (byteOffset < 0) {
714 if (dir) byteOffset = 0
715 else return -1
716 }
717
718 // Normalize val
719 if (typeof val === 'string') {
720 val = Buffer.from(val, encoding)
721 }
722
723 // Finally, search either indexOf (if dir is true) or lastIndexOf
724 if (Buffer.isBuffer(val)) {
725 // Special case: looking for empty string/buffer always fails
726 if (val.length === 0) {
727 return -1
728 }
729 return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
730 } else if (typeof val === 'number') {
731 val = val & 0xFF // Search for a byte value [0-255]
732 if (typeof Uint8Array.prototype.indexOf === 'function') {
733 if (dir) {
734 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
735 } else {
736 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
737 }
738 }
739 return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)
740 }
741
742 throw new TypeError('val must be string, number or Buffer')
743}
744
745function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
746 var indexSize = 1
747 var arrLength = arr.length
748 var valLength = val.length
749
750 if (encoding !== undefined) {
751 encoding = String(encoding).toLowerCase()
752 if (encoding === 'ucs2' || encoding === 'ucs-2' ||
753 encoding === 'utf16le' || encoding === 'utf-16le') {
754 if (arr.length < 2 || val.length < 2) {
755 return -1
756 }
757 indexSize = 2
758 arrLength /= 2
759 valLength /= 2
760 byteOffset /= 2
761 }
762 }
763
764 function read (buf, i) {
765 if (indexSize === 1) {
766 return buf[i]
767 } else {
768 return buf.readUInt16BE(i * indexSize)
769 }
770 }
771
772 var i
773 if (dir) {
774 var foundIndex = -1
775 for (i = byteOffset; i < arrLength; i++) {
776 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
777 if (foundIndex === -1) foundIndex = i
778 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
779 } else {
780 if (foundIndex !== -1) i -= i - foundIndex
781 foundIndex = -1
782 }
783 }
784 } else {
785 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
786 for (i = byteOffset; i >= 0; i--) {
787 var found = true
788 for (var j = 0; j < valLength; j++) {
789 if (read(arr, i + j) !== read(val, j)) {
790 found = false
791 break
792 }
793 }
794 if (found) return i
795 }
796 }
797
798 return -1
799}
800
801Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
802 return this.indexOf(val, byteOffset, encoding) !== -1
803}
804
805Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
806 return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
807}
808
809Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
810 return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
811}
812
813function hexWrite (buf, string, offset, length) {
814 offset = Number(offset) || 0
815 var remaining = buf.length - offset
816 if (!length) {
817 length = remaining
818 } else {
819 length = Number(length)
820 if (length > remaining) {
821 length = remaining
822 }
823 }
824
825 var strLen = string.length
826
827 if (length > strLen / 2) {
828 length = strLen / 2
829 }
830 for (var i = 0; i < length; ++i) {
831 var parsed = parseInt(string.substr(i * 2, 2), 16)
832 if (numberIsNaN(parsed)) return i
833 buf[offset + i] = parsed
834 }
835 return i
836}
837
838function utf8Write (buf, string, offset, length) {
839 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
840}
841
842function asciiWrite (buf, string, offset, length) {
843 return blitBuffer(asciiToBytes(string), buf, offset, length)
844}
845
846function latin1Write (buf, string, offset, length) {
847 return asciiWrite(buf, string, offset, length)
848}
849
850function base64Write (buf, string, offset, length) {
851 return blitBuffer(base64ToBytes(string), buf, offset, length)
852}
853
854function ucs2Write (buf, string, offset, length) {
855 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
856}
857
858Buffer.prototype.write = function write (string, offset, length, encoding) {
859 // Buffer#write(string)
860 if (offset === undefined) {
861 encoding = 'utf8'
862 length = this.length
863 offset = 0
864 // Buffer#write(string, encoding)
865 } else if (length === undefined && typeof offset === 'string') {
866 encoding = offset
867 length = this.length
868 offset = 0
869 // Buffer#write(string, offset[, length][, encoding])
870 } else if (isFinite(offset)) {
871 offset = offset >>> 0
872 if (isFinite(length)) {
873 length = length >>> 0
874 if (encoding === undefined) encoding = 'utf8'
875 } else {
876 encoding = length
877 length = undefined
878 }
879 } else {
880 throw new Error(
881 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
882 )
883 }
884
885 var remaining = this.length - offset
886 if (length === undefined || length > remaining) length = remaining
887
888 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
889 throw new RangeError('Attempt to write outside buffer bounds')
890 }
891
892 if (!encoding) encoding = 'utf8'
893
894 var loweredCase = false
895 for (;;) {
896 switch (encoding) {
897 case 'hex':
898 return hexWrite(this, string, offset, length)
899
900 case 'utf8':
901 case 'utf-8':
902 return utf8Write(this, string, offset, length)
903
904 case 'ascii':
905 return asciiWrite(this, string, offset, length)
906
907 case 'latin1':
908 case 'binary':
909 return latin1Write(this, string, offset, length)
910
911 case 'base64':
912 // Warning: maxLength not taken into account in base64Write
913 return base64Write(this, string, offset, length)
914
915 case 'ucs2':
916 case 'ucs-2':
917 case 'utf16le':
918 case 'utf-16le':
919 return ucs2Write(this, string, offset, length)
920
921 default:
922 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
923 encoding = ('' + encoding).toLowerCase()
924 loweredCase = true
925 }
926 }
927}
928
929Buffer.prototype.toJSON = function toJSON () {
930 return {
931 type: 'Buffer',
932 data: Array.prototype.slice.call(this._arr || this, 0)
933 }
934}
935
936function base64Slice (buf, start, end) {
937 if (start === 0 && end === buf.length) {
938 return base64.fromByteArray(buf)
939 } else {
940 return base64.fromByteArray(buf.slice(start, end))
941 }
942}
943
944function utf8Slice (buf, start, end) {
945 end = Math.min(buf.length, end)
946 var res = []
947
948 var i = start
949 while (i < end) {
950 var firstByte = buf[i]
951 var codePoint = null
952 var bytesPerSequence = (firstByte > 0xEF) ? 4
953 : (firstByte > 0xDF) ? 3
954 : (firstByte > 0xBF) ? 2
955 : 1
956
957 if (i + bytesPerSequence <= end) {
958 var secondByte, thirdByte, fourthByte, tempCodePoint
959
960 switch (bytesPerSequence) {
961 case 1:
962 if (firstByte < 0x80) {
963 codePoint = firstByte
964 }
965 break
966 case 2:
967 secondByte = buf[i + 1]
968 if ((secondByte & 0xC0) === 0x80) {
969 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
970 if (tempCodePoint > 0x7F) {
971 codePoint = tempCodePoint
972 }
973 }
974 break
975 case 3:
976 secondByte = buf[i + 1]
977 thirdByte = buf[i + 2]
978 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
979 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
980 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
981 codePoint = tempCodePoint
982 }
983 }
984 break
985 case 4:
986 secondByte = buf[i + 1]
987 thirdByte = buf[i + 2]
988 fourthByte = buf[i + 3]
989 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
990 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
991 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
992 codePoint = tempCodePoint
993 }
994 }
995 }
996 }
997
998 if (codePoint === null) {
999 // we did not generate a valid codePoint so insert a
1000 // replacement char (U+FFFD) and advance only 1 byte
1001 codePoint = 0xFFFD
1002 bytesPerSequence = 1
1003 } else if (codePoint > 0xFFFF) {
1004 // encode to utf16 (surrogate pair dance)
1005 codePoint -= 0x10000
1006 res.push(codePoint >>> 10 & 0x3FF | 0xD800)
1007 codePoint = 0xDC00 | codePoint & 0x3FF
1008 }
1009
1010 res.push(codePoint)
1011 i += bytesPerSequence
1012 }
1013
1014 return decodeCodePointsArray(res)
1015}
1016
1017// Based on http://stackoverflow.com/a/22747272/680742, the browser with
1018// the lowest limit is Chrome, with 0x10000 args.
1019// We go 1 magnitude less, for safety
1020var MAX_ARGUMENTS_LENGTH = 0x1000
1021
1022function decodeCodePointsArray (codePoints) {
1023 var len = codePoints.length
1024 if (len <= MAX_ARGUMENTS_LENGTH) {
1025 return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
1026 }
1027
1028 // Decode in chunks to avoid "call stack size exceeded".
1029 var res = ''
1030 var i = 0
1031 while (i < len) {
1032 res += String.fromCharCode.apply(
1033 String,
1034 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
1035 )
1036 }
1037 return res
1038}
1039
1040function asciiSlice (buf, start, end) {
1041 var ret = ''
1042 end = Math.min(buf.length, end)
1043
1044 for (var i = start; i < end; ++i) {
1045 ret += String.fromCharCode(buf[i] & 0x7F)
1046 }
1047 return ret
1048}
1049
1050function latin1Slice (buf, start, end) {
1051 var ret = ''
1052 end = Math.min(buf.length, end)
1053
1054 for (var i = start; i < end; ++i) {
1055 ret += String.fromCharCode(buf[i])
1056 }
1057 return ret
1058}
1059
1060function hexSlice (buf, start, end) {
1061 var len = buf.length
1062
1063 if (!start || start < 0) start = 0
1064 if (!end || end < 0 || end > len) end = len
1065
1066 var out = ''
1067 for (var i = start; i < end; ++i) {
Lorne Mitchelldb3885d2019-10-24 21:53:01 +00001068 out += toHex(buf[i])
Yang Guo4fd355c2019-09-19 10:59:03 +02001069 }
1070 return out
1071}
1072
1073function utf16leSlice (buf, start, end) {
1074 var bytes = buf.slice(start, end)
1075 var res = ''
1076 for (var i = 0; i < bytes.length; i += 2) {
1077 res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
1078 }
1079 return res
1080}
1081
1082Buffer.prototype.slice = function slice (start, end) {
1083 var len = this.length
1084 start = ~~start
1085 end = end === undefined ? len : ~~end
1086
1087 if (start < 0) {
1088 start += len
1089 if (start < 0) start = 0
1090 } else if (start > len) {
1091 start = len
1092 }
1093
1094 if (end < 0) {
1095 end += len
1096 if (end < 0) end = 0
1097 } else if (end > len) {
1098 end = len
1099 }
1100
1101 if (end < start) end = start
1102
1103 var newBuf = this.subarray(start, end)
1104 // Return an augmented `Uint8Array` instance
1105 Object.setPrototypeOf(newBuf, Buffer.prototype)
1106
1107 return newBuf
1108}
1109
1110/*
1111 * Need to make sure that buffer isn't trying to write out of bounds.
1112 */
1113function checkOffset (offset, ext, length) {
1114 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
1115 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
1116}
1117
1118Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
1119 offset = offset >>> 0
1120 byteLength = byteLength >>> 0
1121 if (!noAssert) checkOffset(offset, byteLength, this.length)
1122
1123 var val = this[offset]
1124 var mul = 1
1125 var i = 0
1126 while (++i < byteLength && (mul *= 0x100)) {
1127 val += this[offset + i] * mul
1128 }
1129
1130 return val
1131}
1132
1133Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
1134 offset = offset >>> 0
1135 byteLength = byteLength >>> 0
1136 if (!noAssert) {
1137 checkOffset(offset, byteLength, this.length)
1138 }
1139
1140 var val = this[offset + --byteLength]
1141 var mul = 1
1142 while (byteLength > 0 && (mul *= 0x100)) {
1143 val += this[offset + --byteLength] * mul
1144 }
1145
1146 return val
1147}
1148
1149Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
1150 offset = offset >>> 0
1151 if (!noAssert) checkOffset(offset, 1, this.length)
1152 return this[offset]
1153}
1154
1155Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
1156 offset = offset >>> 0
1157 if (!noAssert) checkOffset(offset, 2, this.length)
1158 return this[offset] | (this[offset + 1] << 8)
1159}
1160
1161Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
1162 offset = offset >>> 0
1163 if (!noAssert) checkOffset(offset, 2, this.length)
1164 return (this[offset] << 8) | this[offset + 1]
1165}
1166
1167Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
1168 offset = offset >>> 0
1169 if (!noAssert) checkOffset(offset, 4, this.length)
1170
1171 return ((this[offset]) |
1172 (this[offset + 1] << 8) |
1173 (this[offset + 2] << 16)) +
1174 (this[offset + 3] * 0x1000000)
1175}
1176
1177Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
1178 offset = offset >>> 0
1179 if (!noAssert) checkOffset(offset, 4, this.length)
1180
1181 return (this[offset] * 0x1000000) +
1182 ((this[offset + 1] << 16) |
1183 (this[offset + 2] << 8) |
1184 this[offset + 3])
1185}
1186
1187Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
1188 offset = offset >>> 0
1189 byteLength = byteLength >>> 0
1190 if (!noAssert) checkOffset(offset, byteLength, this.length)
1191
1192 var val = this[offset]
1193 var mul = 1
1194 var i = 0
1195 while (++i < byteLength && (mul *= 0x100)) {
1196 val += this[offset + i] * mul
1197 }
1198 mul *= 0x80
1199
1200 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
1201
1202 return val
1203}
1204
1205Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
1206 offset = offset >>> 0
1207 byteLength = byteLength >>> 0
1208 if (!noAssert) checkOffset(offset, byteLength, this.length)
1209
1210 var i = byteLength
1211 var mul = 1
1212 var val = this[offset + --i]
1213 while (i > 0 && (mul *= 0x100)) {
1214 val += this[offset + --i] * mul
1215 }
1216 mul *= 0x80
1217
1218 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
1219
1220 return val
1221}
1222
1223Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
1224 offset = offset >>> 0
1225 if (!noAssert) checkOffset(offset, 1, this.length)
1226 if (!(this[offset] & 0x80)) return (this[offset])
1227 return ((0xff - this[offset] + 1) * -1)
1228}
1229
1230Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
1231 offset = offset >>> 0
1232 if (!noAssert) checkOffset(offset, 2, this.length)
1233 var val = this[offset] | (this[offset + 1] << 8)
1234 return (val & 0x8000) ? val | 0xFFFF0000 : val
1235}
1236
1237Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
1238 offset = offset >>> 0
1239 if (!noAssert) checkOffset(offset, 2, this.length)
1240 var val = this[offset + 1] | (this[offset] << 8)
1241 return (val & 0x8000) ? val | 0xFFFF0000 : val
1242}
1243
1244Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
1245 offset = offset >>> 0
1246 if (!noAssert) checkOffset(offset, 4, this.length)
1247
1248 return (this[offset]) |
1249 (this[offset + 1] << 8) |
1250 (this[offset + 2] << 16) |
1251 (this[offset + 3] << 24)
1252}
1253
1254Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
1255 offset = offset >>> 0
1256 if (!noAssert) checkOffset(offset, 4, this.length)
1257
1258 return (this[offset] << 24) |
1259 (this[offset + 1] << 16) |
1260 (this[offset + 2] << 8) |
1261 (this[offset + 3])
1262}
1263
1264Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
1265 offset = offset >>> 0
1266 if (!noAssert) checkOffset(offset, 4, this.length)
1267 return ieee754.read(this, offset, true, 23, 4)
1268}
1269
1270Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
1271 offset = offset >>> 0
1272 if (!noAssert) checkOffset(offset, 4, this.length)
1273 return ieee754.read(this, offset, false, 23, 4)
1274}
1275
1276Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
1277 offset = offset >>> 0
1278 if (!noAssert) checkOffset(offset, 8, this.length)
1279 return ieee754.read(this, offset, true, 52, 8)
1280}
1281
1282Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
1283 offset = offset >>> 0
1284 if (!noAssert) checkOffset(offset, 8, this.length)
1285 return ieee754.read(this, offset, false, 52, 8)
1286}
1287
1288function checkInt (buf, value, offset, ext, max, min) {
1289 if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
1290 if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
1291 if (offset + ext > buf.length) throw new RangeError('Index out of range')
1292}
1293
1294Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
1295 value = +value
1296 offset = offset >>> 0
1297 byteLength = byteLength >>> 0
1298 if (!noAssert) {
1299 var maxBytes = Math.pow(2, 8 * byteLength) - 1
1300 checkInt(this, value, offset, byteLength, maxBytes, 0)
1301 }
1302
1303 var mul = 1
1304 var i = 0
1305 this[offset] = value & 0xFF
1306 while (++i < byteLength && (mul *= 0x100)) {
1307 this[offset + i] = (value / mul) & 0xFF
1308 }
1309
1310 return offset + byteLength
1311}
1312
1313Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
1314 value = +value
1315 offset = offset >>> 0
1316 byteLength = byteLength >>> 0
1317 if (!noAssert) {
1318 var maxBytes = Math.pow(2, 8 * byteLength) - 1
1319 checkInt(this, value, offset, byteLength, maxBytes, 0)
1320 }
1321
1322 var i = byteLength - 1
1323 var mul = 1
1324 this[offset + i] = value & 0xFF
1325 while (--i >= 0 && (mul *= 0x100)) {
1326 this[offset + i] = (value / mul) & 0xFF
1327 }
1328
1329 return offset + byteLength
1330}
1331
1332Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
1333 value = +value
1334 offset = offset >>> 0
1335 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
1336 this[offset] = (value & 0xff)
1337 return offset + 1
1338}
1339
1340Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
1341 value = +value
1342 offset = offset >>> 0
1343 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
1344 this[offset] = (value & 0xff)
1345 this[offset + 1] = (value >>> 8)
1346 return offset + 2
1347}
1348
1349Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
1350 value = +value
1351 offset = offset >>> 0
1352 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
1353 this[offset] = (value >>> 8)
1354 this[offset + 1] = (value & 0xff)
1355 return offset + 2
1356}
1357
1358Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
1359 value = +value
1360 offset = offset >>> 0
1361 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
1362 this[offset + 3] = (value >>> 24)
1363 this[offset + 2] = (value >>> 16)
1364 this[offset + 1] = (value >>> 8)
1365 this[offset] = (value & 0xff)
1366 return offset + 4
1367}
1368
1369Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
1370 value = +value
1371 offset = offset >>> 0
1372 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
1373 this[offset] = (value >>> 24)
1374 this[offset + 1] = (value >>> 16)
1375 this[offset + 2] = (value >>> 8)
1376 this[offset + 3] = (value & 0xff)
1377 return offset + 4
1378}
1379
1380Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
1381 value = +value
1382 offset = offset >>> 0
1383 if (!noAssert) {
1384 var limit = Math.pow(2, (8 * byteLength) - 1)
1385
1386 checkInt(this, value, offset, byteLength, limit - 1, -limit)
1387 }
1388
1389 var i = 0
1390 var mul = 1
1391 var sub = 0
1392 this[offset] = value & 0xFF
1393 while (++i < byteLength && (mul *= 0x100)) {
1394 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
1395 sub = 1
1396 }
1397 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
1398 }
1399
1400 return offset + byteLength
1401}
1402
1403Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
1404 value = +value
1405 offset = offset >>> 0
1406 if (!noAssert) {
1407 var limit = Math.pow(2, (8 * byteLength) - 1)
1408
1409 checkInt(this, value, offset, byteLength, limit - 1, -limit)
1410 }
1411
1412 var i = byteLength - 1
1413 var mul = 1
1414 var sub = 0
1415 this[offset + i] = value & 0xFF
1416 while (--i >= 0 && (mul *= 0x100)) {
1417 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
1418 sub = 1
1419 }
1420 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
1421 }
1422
1423 return offset + byteLength
1424}
1425
1426Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
1427 value = +value
1428 offset = offset >>> 0
1429 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
1430 if (value < 0) value = 0xff + value + 1
1431 this[offset] = (value & 0xff)
1432 return offset + 1
1433}
1434
1435Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
1436 value = +value
1437 offset = offset >>> 0
1438 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
1439 this[offset] = (value & 0xff)
1440 this[offset + 1] = (value >>> 8)
1441 return offset + 2
1442}
1443
1444Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
1445 value = +value
1446 offset = offset >>> 0
1447 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
1448 this[offset] = (value >>> 8)
1449 this[offset + 1] = (value & 0xff)
1450 return offset + 2
1451}
1452
1453Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
1454 value = +value
1455 offset = offset >>> 0
1456 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
1457 this[offset] = (value & 0xff)
1458 this[offset + 1] = (value >>> 8)
1459 this[offset + 2] = (value >>> 16)
1460 this[offset + 3] = (value >>> 24)
1461 return offset + 4
1462}
1463
1464Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
1465 value = +value
1466 offset = offset >>> 0
1467 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
1468 if (value < 0) value = 0xffffffff + value + 1
1469 this[offset] = (value >>> 24)
1470 this[offset + 1] = (value >>> 16)
1471 this[offset + 2] = (value >>> 8)
1472 this[offset + 3] = (value & 0xff)
1473 return offset + 4
1474}
1475
1476function checkIEEE754 (buf, value, offset, ext, max, min) {
1477 if (offset + ext > buf.length) throw new RangeError('Index out of range')
1478 if (offset < 0) throw new RangeError('Index out of range')
1479}
1480
1481function writeFloat (buf, value, offset, littleEndian, noAssert) {
1482 value = +value
1483 offset = offset >>> 0
1484 if (!noAssert) {
1485 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
1486 }
1487 ieee754.write(buf, value, offset, littleEndian, 23, 4)
1488 return offset + 4
1489}
1490
1491Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
1492 return writeFloat(this, value, offset, true, noAssert)
1493}
1494
1495Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
1496 return writeFloat(this, value, offset, false, noAssert)
1497}
1498
1499function writeDouble (buf, value, offset, littleEndian, noAssert) {
1500 value = +value
1501 offset = offset >>> 0
1502 if (!noAssert) {
1503 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
1504 }
1505 ieee754.write(buf, value, offset, littleEndian, 52, 8)
1506 return offset + 8
1507}
1508
1509Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
1510 return writeDouble(this, value, offset, true, noAssert)
1511}
1512
1513Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
1514 return writeDouble(this, value, offset, false, noAssert)
1515}
1516
1517// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
1518Buffer.prototype.copy = function copy (target, targetStart, start, end) {
1519 if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
1520 if (!start) start = 0
1521 if (!end && end !== 0) end = this.length
1522 if (targetStart >= target.length) targetStart = target.length
1523 if (!targetStart) targetStart = 0
1524 if (end > 0 && end < start) end = start
1525
1526 // Copy 0 bytes; we're done
1527 if (end === start) return 0
1528 if (target.length === 0 || this.length === 0) return 0
1529
1530 // Fatal error conditions
1531 if (targetStart < 0) {
1532 throw new RangeError('targetStart out of bounds')
1533 }
1534 if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
1535 if (end < 0) throw new RangeError('sourceEnd out of bounds')
1536
1537 // Are we oob?
1538 if (end > this.length) end = this.length
1539 if (target.length - targetStart < end - start) {
1540 end = target.length - targetStart + start
1541 }
1542
1543 var len = end - start
1544
1545 if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
1546 // Use built-in when available, missing from IE11
1547 this.copyWithin(targetStart, start, end)
1548 } else if (this === target && start < targetStart && targetStart < end) {
1549 // descending copy from end
1550 for (var i = len - 1; i >= 0; --i) {
1551 target[i + targetStart] = this[i + start]
1552 }
1553 } else {
1554 Uint8Array.prototype.set.call(
1555 target,
1556 this.subarray(start, end),
1557 targetStart
1558 )
1559 }
1560
1561 return len
1562}
1563
1564// Usage:
1565// buffer.fill(number[, offset[, end]])
1566// buffer.fill(buffer[, offset[, end]])
1567// buffer.fill(string[, offset[, end]][, encoding])
1568Buffer.prototype.fill = function fill (val, start, end, encoding) {
1569 // Handle string cases:
1570 if (typeof val === 'string') {
1571 if (typeof start === 'string') {
1572 encoding = start
1573 start = 0
1574 end = this.length
1575 } else if (typeof end === 'string') {
1576 encoding = end
1577 end = this.length
1578 }
1579 if (encoding !== undefined && typeof encoding !== 'string') {
1580 throw new TypeError('encoding must be a string')
1581 }
1582 if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
1583 throw new TypeError('Unknown encoding: ' + encoding)
1584 }
1585 if (val.length === 1) {
1586 var code = val.charCodeAt(0)
1587 if ((encoding === 'utf8' && code < 128) ||
1588 encoding === 'latin1') {
1589 // Fast path: If `val` fits into a single byte, use that numeric value.
1590 val = code
1591 }
1592 }
1593 } else if (typeof val === 'number') {
1594 val = val & 255
1595 }
1596
1597 // Invalid ranges are not set to a default, so can range check early.
1598 if (start < 0 || this.length < start || this.length < end) {
1599 throw new RangeError('Out of range index')
1600 }
1601
1602 if (end <= start) {
1603 return this
1604 }
1605
1606 start = start >>> 0
1607 end = end === undefined ? this.length : end >>> 0
1608
1609 if (!val) val = 0
1610
1611 var i
1612 if (typeof val === 'number') {
1613 for (i = start; i < end; ++i) {
1614 this[i] = val
1615 }
1616 } else {
1617 var bytes = Buffer.isBuffer(val)
1618 ? val
1619 : Buffer.from(val, encoding)
1620 var len = bytes.length
1621 if (len === 0) {
1622 throw new TypeError('The value "' + val +
1623 '" is invalid for argument "value"')
1624 }
1625 for (i = 0; i < end - start; ++i) {
1626 this[i + start] = bytes[i % len]
1627 }
1628 }
1629
1630 return this
1631}
1632
1633// HELPER FUNCTIONS
1634// ================
1635
1636var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
1637
1638function base64clean (str) {
1639 // Node takes equal signs as end of the Base64 encoding
1640 str = str.split('=')[0]
1641 // Node strips out invalid characters like \n and \t from the string, base64-js does not
1642 str = str.trim().replace(INVALID_BASE64_RE, '')
1643 // Node converts strings with length < 2 to ''
1644 if (str.length < 2) return ''
1645 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
1646 while (str.length % 4 !== 0) {
1647 str = str + '='
1648 }
1649 return str
1650}
1651
Lorne Mitchelldb3885d2019-10-24 21:53:01 +00001652function toHex (n) {
1653 if (n < 16) return '0' + n.toString(16)
1654 return n.toString(16)
1655}
1656
Yang Guo4fd355c2019-09-19 10:59:03 +02001657function utf8ToBytes (string, units) {
1658 units = units || Infinity
1659 var codePoint
1660 var length = string.length
1661 var leadSurrogate = null
1662 var bytes = []
1663
1664 for (var i = 0; i < length; ++i) {
1665 codePoint = string.charCodeAt(i)
1666
1667 // is surrogate component
1668 if (codePoint > 0xD7FF && codePoint < 0xE000) {
1669 // last char was a lead
1670 if (!leadSurrogate) {
1671 // no lead yet
1672 if (codePoint > 0xDBFF) {
1673 // unexpected trail
1674 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
1675 continue
1676 } else if (i + 1 === length) {
1677 // unpaired lead
1678 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
1679 continue
1680 }
1681
1682 // valid lead
1683 leadSurrogate = codePoint
1684
1685 continue
1686 }
1687
1688 // 2 leads in a row
1689 if (codePoint < 0xDC00) {
1690 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
1691 leadSurrogate = codePoint
1692 continue
1693 }
1694
1695 // valid surrogate pair
1696 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
1697 } else if (leadSurrogate) {
1698 // valid bmp char, but last char was a lead
1699 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
1700 }
1701
1702 leadSurrogate = null
1703
1704 // encode utf8
1705 if (codePoint < 0x80) {
1706 if ((units -= 1) < 0) break
1707 bytes.push(codePoint)
1708 } else if (codePoint < 0x800) {
1709 if ((units -= 2) < 0) break
1710 bytes.push(
1711 codePoint >> 0x6 | 0xC0,
1712 codePoint & 0x3F | 0x80
1713 )
1714 } else if (codePoint < 0x10000) {
1715 if ((units -= 3) < 0) break
1716 bytes.push(
1717 codePoint >> 0xC | 0xE0,
1718 codePoint >> 0x6 & 0x3F | 0x80,
1719 codePoint & 0x3F | 0x80
1720 )
1721 } else if (codePoint < 0x110000) {
1722 if ((units -= 4) < 0) break
1723 bytes.push(
1724 codePoint >> 0x12 | 0xF0,
1725 codePoint >> 0xC & 0x3F | 0x80,
1726 codePoint >> 0x6 & 0x3F | 0x80,
1727 codePoint & 0x3F | 0x80
1728 )
1729 } else {
1730 throw new Error('Invalid code point')
1731 }
1732 }
1733
1734 return bytes
1735}
1736
1737function asciiToBytes (str) {
1738 var byteArray = []
1739 for (var i = 0; i < str.length; ++i) {
1740 // Node's code seems to be doing this and not & 0x7F..
1741 byteArray.push(str.charCodeAt(i) & 0xFF)
1742 }
1743 return byteArray
1744}
1745
1746function utf16leToBytes (str, units) {
1747 var c, hi, lo
1748 var byteArray = []
1749 for (var i = 0; i < str.length; ++i) {
1750 if ((units -= 2) < 0) break
1751
1752 c = str.charCodeAt(i)
1753 hi = c >> 8
1754 lo = c % 256
1755 byteArray.push(lo)
1756 byteArray.push(hi)
1757 }
1758
1759 return byteArray
1760}
1761
1762function base64ToBytes (str) {
1763 return base64.toByteArray(base64clean(str))
1764}
1765
1766function blitBuffer (src, dst, offset, length) {
1767 for (var i = 0; i < length; ++i) {
1768 if ((i + offset >= dst.length) || (i >= src.length)) break
1769 dst[i + offset] = src[i]
1770 }
1771 return i
1772}
1773
1774// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
1775// the `instanceof` check but they should be treated as of that type.
1776// See: https://github.com/feross/buffer/issues/166
1777function isInstance (obj, type) {
1778 return obj instanceof type ||
1779 (obj != null && obj.constructor != null && obj.constructor.name != null &&
1780 obj.constructor.name === type.name)
1781}
1782function numberIsNaN (obj) {
1783 // For IE11 support
1784 return obj !== obj // eslint-disable-line no-self-compare
1785}