Skip to content

Commit dc7aeaf

Browse files
committed
Simplify
1 parent 520d772 commit dc7aeaf

File tree

1 file changed

+22
-16
lines changed

1 file changed

+22
-16
lines changed

src/remoteFile.ts

Lines changed: 22 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,22 @@ export function toLocale(n: number) {
2020
function r(s: number) {
2121
return toLocale(Number.parseFloat(s.toPrecision(3)))
2222
}
23+
function sum(array: Uint8Array[]) {
24+
let sum = 0
25+
for (const entry of array) {
26+
sum += entry.length
27+
}
28+
return sum
29+
}
30+
function concatUint8Array(args: Uint8Array[]) {
31+
const mergedArray = new Uint8Array(sum(args))
32+
let offset = 0
33+
for (const entry of args) {
34+
mergedArray.set(entry, offset)
35+
offset += entry.length
36+
}
37+
return mergedArray
38+
}
2339
export function getProgressDisplayStr(current: number, total: number) {
2440
if (Math.floor(total / 1_000_000) > 0) {
2541
return `${r(current / 1_000_000)}/${r(total / 1_000_000)}Mb`
@@ -222,7 +238,7 @@ export default class RemoteFile implements GenericFilehandle {
222238
const contentLength = res.headers.get('content-length')
223239
const totalBytes = contentLength ? parseInt(contentLength, 10) : undefined
224240

225-
if (statusCallback && res.body) {
241+
if (statusCallback && res.body && totalBytes) {
226242
const reader = res.body.getReader()
227243
const chunks: Uint8Array[] = []
228244
let receivedBytes = 0
@@ -238,28 +254,18 @@ export default class RemoteFile implements GenericFilehandle {
238254
chunks.push(value)
239255
receivedBytes += value.length
240256

241-
if (statusCallback && totalBytes) {
242-
statusCallback(
243-
`Downloading ${getProgressDisplayStr(receivedBytes, totalBytes)}`,
244-
)
245-
}
246-
}
247-
248-
// Concatenate chunks
249-
const chunksAll = new Uint8Array(receivedBytes)
250-
let position = 0
251-
for (const chunk of chunks) {
252-
chunksAll.set(chunk, position)
253-
position += chunk.length
257+
statusCallback(
258+
`Downloading ${getProgressDisplayStr(receivedBytes, totalBytes)}`,
259+
)
254260
}
255261

256262
if (encoding === 'utf8') {
257263
const decoder = new TextDecoder('utf-8')
258-
return decoder.decode(chunksAll)
264+
return decoder.decode(concatUint8Array(chunks))
259265
} else if (encoding) {
260266
throw new Error(`unsupported encoding: ${encoding}`)
261267
} else {
262-
return chunksAll
268+
return concatUint8Array(chunks)
263269
}
264270
} else {
265271
// If no statusCallback, use the simpler approach

0 commit comments

Comments
 (0)