@@ -6,8 +6,8 @@ var isArray = require('isarray');
6
6
var useUint8Array = typeof Uint8Array !== 'undefined' ;
7
7
var useArrayBuffer = typeof ArrayBuffer !== 'undefined'
8
8
&& typeof Uint8Array !== 'undefined'
9
- && ArrayBuffer . isView
10
- && ( Buffer . prototype instanceof Uint8Array || Buffer . TYPED_ARRAY_SUPPORT ) ;
9
+ && ArrayBuffer . isView ;
10
+ var useFromArrayBuffer = useArrayBuffer && ( Buffer . prototype instanceof Uint8Array || Buffer . TYPED_ARRAY_SUPPORT ) ;
11
11
12
12
module . exports = function toBuffer ( data , encoding ) {
13
13
/*
@@ -18,7 +18,6 @@ module.exports = function toBuffer(data, encoding) {
18
18
return data ;
19
19
}
20
20
21
- // Convert strings to Buffer
22
21
if ( typeof data === 'string' ) {
23
22
return Buffer . from ( data , encoding ) ;
24
23
}
@@ -33,13 +32,28 @@ module.exports = function toBuffer(data, encoding) {
33
32
return Buffer . alloc ( 0 ) ;
34
33
}
35
34
36
- var res = Buffer . from ( data . buffer , data . byteOffset , data . byteLength ) ;
35
+ // When Buffer is based on Uint8Array, we can just construct it from ArrayBuffer
36
+ if ( useFromArrayBuffer ) {
37
+ var res = Buffer . from ( data . buffer , data . byteOffset , data . byteLength ) ;
38
+ /*
39
+ * Recheck result size, as offset/length doesn't work on Node.js <5.10
40
+ * We just go to Uint8Array case if this fails
41
+ */
42
+ if ( res . byteLength === data . byteLength ) {
43
+ return res ;
44
+ }
45
+ }
46
+
47
+ // Convert to Uint8Array bytes and then to Buffer
48
+ var uint8 = data instanceof Uint8Array ? data : new Uint8Array ( data . buffer , data . byteOffset , data . byteLength ) ;
49
+ var result = Buffer . from ( uint8 ) ;
50
+
37
51
/*
38
- * Recheck result size, as offset/length doesn't work on Node.js <5.10
39
- * We just go to Uint8Array case if this fails
52
+ * Let's recheck that conversion succeeded
53
+ * We have .length but not .byteLength when useFromArrayBuffer is false
40
54
*/
41
- if ( res . byteLength === data . byteLength ) {
42
- return res ;
55
+ if ( result . length === data . byteLength ) {
56
+ return result ;
43
57
}
44
58
}
45
59
0 commit comments