@@ -6,8 +6,8 @@ var isArray = require('isarray');
66var useUint8Array = typeof Uint8Array !== 'undefined' ;
77var useArrayBuffer = typeof ArrayBuffer !== 'undefined'
88 && 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 ) ;
1111
1212module . exports = function toBuffer ( data , encoding ) {
1313 /*
@@ -18,7 +18,6 @@ module.exports = function toBuffer(data, encoding) {
1818 return data ;
1919 }
2020
21- // Convert strings to Buffer
2221 if ( typeof data === 'string' ) {
2322 return Buffer . from ( data , encoding ) ;
2423 }
@@ -33,13 +32,28 @@ module.exports = function toBuffer(data, encoding) {
3332 return Buffer . alloc ( 0 ) ;
3433 }
3534
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+
3751 /*
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
4054 */
41- if ( res . byteLength === data . byteLength ) {
42- return res ;
55+ if ( result . length === data . byteLength ) {
56+ return result ;
4357 }
4458 }
4559
0 commit comments