byte-rw
Version:
Byte reader/writer for buffers and streams in typescript/javascript
35 lines (34 loc) • 1.18 kB
JavaScript
import { DataViewByteWriter } from "./writer.js";
export class DataViewByteWriterChunked extends DataViewByteWriter {
constructor(littleEndian, defaultChunkSize = 4096) {
super(new DataView(new ArrayBuffer(defaultChunkSize)), littleEndian);
this.defaultChunkSize = defaultChunkSize;
}
complete() {
if (this._isComplete)
return;
const toSave = this._byteOffset;
const saved = this.save();
if (saved != toSave)
throw new Error("not all queued bytes could be saved");
this._dataview = new DataView(new ArrayBuffer(0));
this._byteOffset = 0;
super.complete();
}
tryEnsureAvailable(bytes) {
if (this._isComplete)
return 0;
if (this._bytesRemaining < bytes) {
const saved = this.save();
if (saved !== this._byteOffset) {
this._isComplete = true;
return 0;
}
else {
this._dataview = new DataView(new ArrayBuffer(Math.max(bytes, this.defaultChunkSize)));
this._byteOffset = 0;
}
}
return bytes;
}
}