common.js (1244B)
1 // Compare two Uint8Arrays. 2 function compareArrays(actual, expected) { 3 assert_true(actual instanceof Uint8Array, 'actual is Uint8Array'); 4 assert_true(expected instanceof Uint8Array, 'expected is Uint8Array'); 5 assert_equals(actual.byteLength, expected.byteLength, 'lengths equal'); 6 for (let i = 0; i < expected.byteLength; ++i) 7 assert_equals(actual[i], expected[i], `Mismatch at position ${i}.`); 8 } 9 10 // Reads from |reader| until at least |targetLength| is read or the stream is 11 // closed. The data is returned as a combined Uint8Array. 12 async function readWithLength(reader, targetLength) { 13 const chunks = []; 14 let actualLength = 0; 15 16 while (true) { 17 let {value, done} = await reader.read(); 18 chunks.push(value); 19 actualLength += value.byteLength; 20 21 if (actualLength >= targetLength || done) { 22 // It would be better to allocate |buffer| up front with the number of 23 // of bytes expected but this is the best that can be done without a 24 // BYOB reader to control the amount of data read. 25 const buffer = new Uint8Array(actualLength); 26 chunks.reduce((offset, chunk) => { 27 buffer.set(chunk, offset); 28 return offset + chunk.byteLength; 29 }, 0); 30 return buffer; 31 } 32 } 33 }