Skip to content

Instantly share code, notes, and snippets.

@jamesliu96
Created December 23, 2021 10:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamesliu96/1d8ac07f9c34a01f9acbfd91f03d26aa to your computer and use it in GitHub Desktop.
Save jamesliu96/1d8ac07f9c34a01f9acbfd91f03d26aa to your computer and use it in GitHub Desktop.
class BlobReader {
public static toBytes = (ab: ArrayBuffer) => new Uint8Array(ab);
public static EOF = new Error('EOF');
public static LOCK = new Error('LOCK');
private _remain!: Blob;
private _offset = 0;
private _end = false;
private _mutex = false;
public constructor(public blob: Blob) {
this._check();
}
public async read(buffer: Uint8Array) {
if (this._mutex) throw BlobReader.LOCK;
this._check();
if (this._end) throw BlobReader.EOF;
if (buffer instanceof ArrayBuffer) buffer = BlobReader.toBytes(buffer);
const chunk = this._remain.slice(0, buffer.length);
this._lock();
try {
buffer.set(BlobReader.toBytes(await chunk.arrayBuffer()));
} catch (e) {
this._unlock();
throw e;
}
this._unlock();
this._offset += chunk.size;
}
private _check() {
this._remain = this.blob.slice(this._offset);
if (!this._remain.size) this._end = true;
}
private _lock() {
this._mutex = true;
}
private _unlock() {
this._mutex = false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment