| 1355 | // Pack headers, padding and small body chunks into slabs; pass large chunks |
| 1356 | // through without copying. Flushed slab regions are never overwritten. |
| 1357 | class Encoder { |
| 1358 | private slab = new Uint8Array(0) |
| 1359 | // Start of the bytes in `slab` that have not been flushed, and their end |
| 1360 | private start = 0 |
| 1361 | private offset = 0 |
| 1362 | private chunks: Array<Uint8Array> = [] |
| 1363 | buffered = 0 |
| 1364 | // The entry whose body is being written, and the body bytes written so far |
| 1365 | private header: Header | undefined |
| 1366 | private written = 0 |
| 1367 | |
| 1368 | begin(header: Header): void { |
| 1369 | encodeHeader(header, this.alloc) |
| 1370 | this.header = header |
| 1371 | this.written = 0 |
| 1372 | } |
| 1373 | |
| 1374 | body(chunk: Uint8Array): void { |
| 1375 | const header = this.header! |
| 1376 | this.written += chunk.length |
| 1377 | if (this.written > header.size) { |
| 1378 | throw sizeMismatch(header, this.written) |
| 1379 | } |
| 1380 | if (chunk.length < COPY_LIMIT) { |
| 1381 | // `reserve` can start a new slab, so it must run before `slab` is read |
| 1382 | const offset = this.reserve(chunk.length) |
| 1383 | this.slab.set(chunk, offset) |
| 1384 | return |
| 1385 | } |
| 1386 | this.cut() |
| 1387 | this.chunks.push(chunk) |
| 1388 | this.buffered += chunk.length |
| 1389 | } |
| 1390 | |
| 1391 | end(): void { |
| 1392 | const header = this.header! |
| 1393 | this.header = undefined |
| 1394 | if (this.written !== header.size) { |
| 1395 | throw sizeMismatch(header, this.written) |
| 1396 | } |
| 1397 | this.reserve(padding(header.size)) |
| 1398 | } |
| 1399 | |
| 1400 | finish(): void { |
| 1401 | this.reserve(BLOCK * 2) |
| 1402 | } |
| 1403 | |
| 1404 | flush(): Arr.NonEmptyArray<Uint8Array> { |
| 1405 | this.cut() |
| 1406 | const chunks = this.chunks as Arr.NonEmptyArray<Uint8Array> |
| 1407 | this.chunks = [] |
| 1408 | this.buffered = 0 |
| 1409 | return chunks |
| 1410 | } |
| 1411 | |
| 1412 | // Ends the current run of slab bytes as a chunk |
| 1413 | private cut(): void { |
| 1414 | if (this.offset > this.start) { |