Skip to content

Commit 2f8fc9f

Browse files
committed
only read necessary data
1 parent e716795 commit 2f8fc9f

File tree

1 file changed

+12
-4
lines changed

1 file changed

+12
-4
lines changed

packages/hub/src/utils/XetBlob.ts

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -158,8 +158,13 @@ export class XetBlob extends Blob {
158158
// Refetch the token if it's expired
159159
connParams = await getAccessToken(this.repoId, this.accessToken, this.fetch, this.hubUrl);
160160

161-
async function* readData(reconstructionInfo: ReconstructionInfo, customFetch: typeof fetch) {
161+
async function* readData(reconstructionInfo: ReconstructionInfo, customFetch: typeof fetch, maxBytes: number) {
162+
let totalBytesRead = 0;
163+
162164
for (const term of reconstructionInfo.terms) {
165+
if (totalBytesRead >= maxBytes) {
166+
break;
167+
}
163168
const fetchInfo = reconstructionInfo.fetch_info[term.hash].find(
164169
(info) => info.range.start <= term.range.start && info.range.end >= term.range.end
165170
);
@@ -195,11 +200,11 @@ export class XetBlob extends Blob {
195200

196201
let leftoverBytes: Uint8Array | undefined = undefined;
197202

198-
readChunks: while (!done) {
203+
readChunks: while (!done && totalBytesRead < maxBytes) {
199204
const result = await reader.read();
200205
done = result.done;
201206
if (result.value) {
202-
while (1) {
207+
while (totalBytesRead < maxBytes) {
203208
if (bytesToSkip) {
204209
if (bytesToSkip >= result.value.length) {
205210
bytesToSkip -= result.value.length;
@@ -211,10 +216,12 @@ export class XetBlob extends Blob {
211216
if (bytesToRead >= result.value.length) {
212217
yield result.value;
213218
bytesToRead -= result.value.length;
219+
totalBytesRead += result.value.length;
214220
continue readChunks;
215221
}
216222
yield result.value.slice(0, bytesToRead);
217223
result.value = result.value.slice(bytesToRead);
224+
totalBytesRead += bytesToRead;
218225
bytesToRead = 0;
219226
}
220227
if (leftoverBytes) {
@@ -263,6 +270,7 @@ export class XetBlob extends Blob {
263270
} else {
264271
bytesToRead = chunkHeader.uncompressed_length;
265272
}
273+
bytesToRead = Math.min(bytesToRead, maxBytes - totalBytesRead);
266274
chunksToRead--;
267275
continue;
268276
}
@@ -274,7 +282,7 @@ export class XetBlob extends Blob {
274282
}
275283
}
276284

277-
const iterator = readData(reconstructionInfo, this.fetch);
285+
const iterator = readData(reconstructionInfo, this.fetch, this.end - this.start);
278286

279287
// todo: when Chrome/Safari support it, use ReadableStream.from(readData)
280288
return new ReadableStream<Uint8Array>(

0 commit comments

Comments
 (0)