1 |
|
2 |
|
3 | var toString = Object.prototype.toString
|
4 |
|
5 | var isModern = (
|
6 | typeof Buffer !== 'undefined' &&
|
7 | typeof Buffer.alloc === 'function' &&
|
8 | typeof Buffer.allocUnsafe === 'function' &&
|
9 | typeof Buffer.from === 'function'
|
10 | )
|
11 |
|
12 | function isArrayBuffer (input) {
|
13 | return toString.call(input).slice(8, -1) === 'ArrayBuffer'
|
14 | }
|
15 |
|
16 | function fromArrayBuffer (obj, byteOffset, length) {
|
17 | byteOffset >>>= 0
|
18 |
|
19 | var maxLength = obj.byteLength - byteOffset
|
20 |
|
21 | if (maxLength < 0) {
|
22 | throw new RangeError("'offset' is out of bounds")
|
23 | }
|
24 |
|
25 | if (length === undefined) {
|
26 | length = maxLength
|
27 | } else {
|
28 | length >>>= 0
|
29 |
|
30 | if (length > maxLength) {
|
31 | throw new RangeError("'length' is out of bounds")
|
32 | }
|
33 | }
|
34 |
|
35 | return isModern
|
36 | ? Buffer.from(obj.slice(byteOffset, byteOffset + length))
|
37 | : new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length)))
|
38 | }
|
39 |
|
40 | function fromString (string, encoding) {
|
41 | if (typeof encoding !== 'string' || encoding === '') {
|
42 | encoding = 'utf8'
|
43 | }
|
44 |
|
45 | if (!Buffer.isEncoding(encoding)) {
|
46 | throw new TypeError('"encoding" must be a valid string encoding')
|
47 | }
|
48 |
|
49 | return isModern
|
50 | ? Buffer.from(string, encoding)
|
51 | : new Buffer(string, encoding)
|
52 | }
|
53 |
|
54 | function bufferFrom (value, encodingOrOffset, length) {
|
55 | if (typeof value === 'number') {
|
56 | throw new TypeError('"value" argument must not be a number')
|
57 | }
|
58 |
|
59 | if (isArrayBuffer(value)) {
|
60 | return fromArrayBuffer(value, encodingOrOffset, length)
|
61 | }
|
62 |
|
63 | if (typeof value === 'string') {
|
64 | return fromString(value, encodingOrOffset)
|
65 | }
|
66 |
|
67 | return isModern
|
68 | ? Buffer.from(value)
|
69 | : new Buffer(value)
|
70 | }
|
71 |
|
72 | module.exports = bufferFrom
|