@obsidize/tar-browserify
Version:
Browser-based tar utility for packing and unpacking tar files (stream-capable)
61 lines (60 loc) • 2.15 kB
JavaScript
import { InMemoryAsyncUint8Array } from './async-uint8-array';
import { Constants } from './constants';
import { TarUtility } from './tar-utility';
function sanitizeOptions(options) {
return Object.assign({
blockSize: Constants.SECTOR_SIZE * 16, // 8Kb
}, options);
}
const MIN_BLOCK_SIZE = Constants.SECTOR_SIZE;
const MAX_BLOCK_SIZE = Constants.SECTOR_SIZE * 10000;
/**
* Generalized abstraction for pulling in raw octet data, whether its
* over the network or from disk or in memory.
*
* This is designed to reduce general complexity / fragmentation
* when parsing out tar sectors by forcing every input type to adhere to
* the same streaming interface.
*/
export class AsyncUint8ArrayIterator {
constructor(input, options = {}) {
this.mOffset = 0;
this.mInput = TarUtility.isUint8Array(input) ? new InMemoryAsyncUint8Array(input) : input;
let { blockSize } = sanitizeOptions(options);
blockSize = TarUtility.clamp(blockSize, MIN_BLOCK_SIZE, MAX_BLOCK_SIZE);
blockSize = TarUtility.roundUpSectorOffset(blockSize);
this.blockSize = blockSize;
}
[Symbol.asyncIterator]() {
return this;
}
get input() {
return this.mInput;
}
get byteLength() {
return this.mInput.byteLength;
}
get currentOffset() {
return this.mOffset;
}
async tryNext() {
const result = await this.next();
return result?.value?.buffer ?? null;
}
/**
* Grab the next `blockSize` chunk of data from the input.
* See `AsyncIterableIterator` for more info.
*/
async next() {
const source = this.input;
const offset = this.currentOffset;
const length = this.byteLength;
if (offset >= length) {
return { done: true, value: null };
}
const targetLength = Math.min(this.blockSize, length - offset);
const buffer = await source.read(offset, targetLength);
this.mOffset += targetLength;
return { done: false, value: { source, buffer, offset } };
}
}