UNPKG

@obsidize/tar-browserify

Version:

Browser-based tar utility for packing and unpacking tar files (stream-capable)

77 lines (76 loc) 2.77 kB
import { __awaiter } from "tslib"; 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(mInput, options = {}) { this.mInput = mInput; this.mOffset = 0; 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.mByteLength; } get currentOffset() { return this.mOffset; } /** * Must be called before next(), otherwise the iteration * will terminate immediately. */ initialize() { return __awaiter(this, void 0, void 0, function* () { this.mByteLength = yield this.input.byteLength(); this.mOffset = 0; }); } tryNext() { var _a; return __awaiter(this, void 0, void 0, function* () { const result = yield this.next(); return ((_a = result === null || result === void 0 ? void 0 : result.value) === null || _a === void 0 ? void 0 : _a.buffer) ? result.value.buffer : null; }); } /** * Grab the next `blockSize` chunk of data from the input. * See `AsyncIterableIterator` for more info. */ next() { return __awaiter(this, void 0, void 0, function* () { const source = this.input; const offset = this.mOffset; const length = this.mByteLength; const canAdvanceOffset = TarUtility.isNumber(length) && offset < length; if (canAdvanceOffset) { const targetLength = Math.min(this.blockSize, length - offset); const buffer = yield source.read(offset, targetLength); this.mOffset += targetLength; return { done: false, value: { source, buffer, offset } }; } return { done: true, value: null }; }); } }