diff --git a/src/mono/wasm/runtime/http.ts b/src/mono/wasm/runtime/http.ts index 7404cefcb304ea..22d93a1a8af068 100644 --- a/src/mono/wasm/runtime/http.ts +++ b/src/mono/wasm/runtime/http.ts @@ -104,38 +104,37 @@ export async function http_wasm_get_streamed_response_bytes(res: ResponseExtensi // the bufferPtr is pinned by the caller const view = new Span(bufferPtr, bufferLength, MemoryViewType.Byte); return wrap_as_cancelable_promise(async () => { - if (!res.__chunk && res.body) { + if (!res.body) { + return 0; + } + + if (!res.__reader) { res.__reader = res.body.getReader(); + } + + if (!res.__chunk) { res.__chunk = await res.__reader.read(); res.__source_offset = 0; } - let target_offset = 0; - let bytes_read = 0; - // loop until end of browser stream or end of C# buffer - while (res.__reader && res.__chunk && !res.__chunk.done) { - const remaining_source = res.__chunk.value.byteLength - res.__source_offset; - if (remaining_source === 0) { - res.__chunk = await res.__reader.read(); - res.__source_offset = 0; - continue;// are we done yet - } - - const remaining_target = view.byteLength - target_offset; - const bytes_copied = Math.min(remaining_source, remaining_target); - const source_view = res.__chunk.value.subarray(res.__source_offset, res.__source_offset + bytes_copied); - - // copy available bytes - view.set(source_view, target_offset); - target_offset += bytes_copied; - bytes_read += bytes_copied; - res.__source_offset += bytes_copied; - - if (target_offset == view.byteLength) { - return bytes_read; - } + if (res.__chunk.done) { + return 0; } - return bytes_read; + + const remaining_source = res.__chunk.value.byteLength - res.__source_offset; + + if (remaining_source === 0) { + res.__chunk = await res.__reader.read(); + res.__source_offset = 0; + return 0; + } + + const bytes_copied = Math.min(remaining_source, view.byteLength); + const source_view = res.__chunk.value.subarray(res.__source_offset, bytes_copied); + view.set(source_view, 0); + res.__source_offset += bytes_copied; + + return bytes_copied; }); }