@@ -16,7 +16,14 @@ var isView = ArrayBuffer.isView || function isView(obj) {
1616var useUint8Array = typeof Uint8Array !== 'undefined' ;
1717var useArrayBuffer = typeof ArrayBuffer !== 'undefined'
1818 && typeof Uint8Array !== 'undefined' ;
19- var useFromArrayBuffer = useArrayBuffer && ( Buffer . prototype instanceof Uint8Array || Buffer . TYPED_ARRAY_SUPPORT ) ;
19+ // Check if we're on a big-endian system
20+ var isBigEndian = ( function ( ) {
21+ var buffer = new ArrayBuffer ( 2 ) ;
22+ new DataView ( buffer ) . setInt16 ( 0 , 256 , true ) ; // little-endian
23+ return new Int16Array ( buffer ) [ 0 ] !== 256 ;
24+ } ) ( ) ;
25+
26+ var useFromArrayBuffer = useArrayBuffer && ( Buffer . prototype instanceof Uint8Array || Buffer . TYPED_ARRAY_SUPPORT ) && ! isBigEndian ;
2027
2128module . exports = function toBuffer ( data , encoding ) {
2229 if ( Buffer . isBuffer ( data ) ) {
@@ -54,7 +61,40 @@ module.exports = function toBuffer(data, encoding) {
5461 }
5562
5663 // Convert to Uint8Array bytes and then to Buffer
57- var uint8 = data instanceof Uint8Array ? data : new Uint8Array ( data . buffer , data . byteOffset , data . byteLength ) ;
64+ var uint8 ;
65+ if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
66+ // These are already byte arrays, no endianness issues
67+ uint8 = new Uint8Array ( data . buffer , data . byteOffset , data . byteLength ) ;
68+ } else {
69+ // For multi-byte TypedArrays, ensure consistent little-endian byte order
70+ // Read element values directly and write them in little-endian format
71+ var elemSize = data . BYTES_PER_ELEMENT ;
72+ var elemCount = data . length ;
73+ uint8 = new Uint8Array ( data . byteLength ) ;
74+ var outputView = new DataView ( uint8 . buffer ) ;
75+
76+ // Copy each element value, writing in little-endian format
77+ for ( var j = 0 ; j < elemCount ; j ++ ) {
78+ var offset = j * elemSize ;
79+ var value = data [ j ] ; // Get the actual element value
80+
81+ // Write the value in little-endian format based on size
82+ if ( elemSize === 1 ) {
83+ // 8-bit values have no endianness
84+ outputView . setUint8 ( offset , value ) ;
85+ } else if ( elemSize === 2 ) {
86+ // 16-bit values - write as little-endian
87+ outputView . setUint16 ( offset , value , true ) ;
88+ } else if ( elemSize === 4 ) {
89+ // 32-bit values - write as little-endian
90+ outputView . setUint32 ( offset , value , true ) ;
91+ } else if ( elemSize === 8 ) {
92+ // 64-bit values - write as little-endian
93+ outputView . setBigUint64 ( offset , value , true ) ;
94+ }
95+ }
96+ }
97+
5898 var result = Buffer . from ( uint8 ) ;
5999
60100 /*
0 commit comments