Is it safe to decode an UTF8-string that has been hacked into arbitrary byte-chunks to string (chunk-wise)?
Also, what about an arbitrary encoding ?
Context is this method:
async getFileAsync(fileName: string, encoding: string):string
{
const textDecoder = new TextDecoder(encoding);
const response = await fetch(fileName);
console.log(response.ok);
console.log(response.status);
console.log(response.statusText);
// let responseBuffer:ArrayBuffer = await response.arrayBuffer();
// let text:string = textDecoder.decode(responseBuffer);
// https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/getReader
const reader = response.body.getReader();
let result:ReadableStreamReadResult<Uint8Array>;
let chunks:Uint8Array[] = [];
// due to done, this is unlike C#:
// byte[] buffer = new byte[32768];
// int read;
// while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
// {
// output.Write (buffer, 0, read);
// }
do
{
result = await reader.read();
chunks.push(result.value);
// would this be safe ?
let partN = textDecoder.decode(result.value);
// chunks.push(partN);
console.log("result: ", result.value, partN);
} while(!result.done)
let chunkLength:number = chunks.reduce(
function(a, b)
{
return a + (b||[]).length;
}
, 0
);
let mergedArray = new Uint8Array(chunkLength);
let currentPosition = 0;
for(let i = 0; i < chunks.length; ++i)
{
mergedArray.set(chunks[i],currentPosition);
currentPosition += (chunks[i]||[]).length;
} // Next i
let file:string = textDecoder.decode(mergedArray);
// let file:string = chunks.join('');
return file;
} // End Function getFileAsync
Now what I'm wondering is, if it's safe considering an arbitrary encoding, to do this:
result = await reader.read();
// would this be safe ?
chunks.push(textDecoder.decode(result.value));
And by "safe" I mean will it result in the overall string being correctly decoded?
My guess is that it's not, but I guess I just want somebody to confirm that.
I figured when I have to wait until the end to merge the chunked array, I can just as well call
let responseBuffer:ArrayBuffer = await response.arrayBuffer();
let text:string = textDecoder.decode(responseBuffer);
instead.