UNPKG

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