dataview.js (2402B)
1 function typeName(typedArrayCtor) { 2 return typedArrayCtor.name.slice(0, -"Array".length); 3 } 4 5 const nativeIsLittleEndian = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1; 6 7 function toEndianess(type, v, littleEndian) { 8 // Disable Ion compilation to call the native, non-inlined DataView functions. 9 with ({}); // no-ion 10 assertEq(inIon() !== true, true); 11 12 let dv = new DataView(new ArrayBuffer(type.BYTES_PER_ELEMENT)); 13 14 let name = typeName(type); 15 dv[`set${name}`](0, v, nativeIsLittleEndian); 16 return dv[`get${name}`](0, littleEndian); 17 } 18 19 function toLittleEndian(type, v) { 20 return toEndianess(type, v, true); 21 } 22 23 function toBigEndian(type, v) { 24 return toEndianess(type, v, false); 25 } 26 27 // Shared test data for various DataView tests. 28 function createTestData() { 29 const tests = [ 30 { 31 type: Int8Array, 32 values: [-128, -127, -2, -1, 0, 1, 2, 126, 127], 33 }, 34 { 35 type: Uint8Array, 36 values: [0, 1, 2, 126, 127, 128, 254, 255], 37 }, 38 { 39 type: Int16Array, 40 values: [-32768, -32767, -2, -1, 0, 1, 2, 32766, 32767], 41 }, 42 { 43 type: Uint16Array, 44 values: [0, 1, 2, 32766, 32767, 32768, 65534, 65535], 45 }, 46 { 47 type: Int32Array, 48 values: [-2147483648, -2147483647, -2, -1, 0, 1, 2, 2147483646, 2147483647], 49 }, 50 { 51 type: Uint32Array, 52 values: [0, 1, 2, 2147483646, 2147483647], // Representable as Int32 53 }, 54 { 55 type: Uint32Array, 56 values: [0, 1, 2, 2147483646, 2147483647, 2147483648, 4294967294, 4294967295], 57 }, 58 { 59 type: Float16Array, 60 values: [-NaN, -Infinity, -0.5, -0, +0, 0.5, Infinity, NaN], 61 }, 62 { 63 type: Float32Array, 64 values: [-NaN, -Infinity, -0.5, -0, +0, 0.5, Infinity, NaN], 65 }, 66 { 67 type: Float64Array, 68 values: [-NaN, -Infinity, -0.5, -0, +0, 0.5, Infinity, NaN], 69 }, 70 { 71 type: BigInt64Array, 72 values: [-9223372036854775808n, -9223372036854775807n, -2n, -1n, 0n, 1n, 2n, 9223372036854775806n, 9223372036854775807n], 73 }, 74 { 75 type: BigUint64Array, 76 values: [0n, 1n, 2n, 9223372036854775806n, 9223372036854775807n, 9223372036854775808n, 18446744073709551614n, 18446744073709551615n], 77 }, 78 ]; 79 80 tests.forEach(data => { 81 data.littleEndian = data.values.map(v => toLittleEndian(data.type, v)); 82 data.bigEndian = data.values.map(v => toBigEndian(data.type, v)); 83 }); 84 85 return tests; 86 }