Created
December 23, 2021 10:02
-
-
Save jamesliu96/1d8ac07f9c34a01f9acbfd91f03d26aa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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