license import { env , util } from '@tensorflow/tfjs-core' ; import { FileElement } from '../types' ; import { ByteChunkIterator } from './byte_chunk_iterator' ; export interface FileChunkIteratorOptions { /** The byte offset at which to begin reading the File or Blob. Default 0. */ offset ? : number ; /** The number of bytes to read at a time. Default 1MB. */ chunkSize ? : number ; } param file param options returns export class FileChunkIterator extends ByteChunkIterator { offset : number ; chunkSize : number ; constructor ( protected file , protected options = { } ) { super ( ) ; util . assert ( ( file instanceof Uint8Array ) || ( env ( ) . get ( 'IS_BROWSER' ) ? ( file instanceof File || file instanceof Blob ) : false ) , ( ) => 'FileChunkIterator only supports File, Blob and Uint8Array ' + 'right now.' ) ; this . offset = options . offset || 0 ; this . chunkSize = options . chunkSize || 1024 * 1024 ; } summary ( ) { return `FileChunks ${ this . file }` ; } async next ( ) { if ( this . offset >= ( ( this . file instanceof Uint8Array ) ? this . file . byteLength : this . file . size ) ) { return { value : null , done : true } ; } const chunk = new Promise < Uint8Array > ( ( resolve , reject ) => { const end = this . offset + this . chunkSize ; if ( this . file instanceof Uint8Array ) { resolve ( new Uint8Array ( this . file . slice ( this . offset , end ) ) ) ; } else { const fileReader = new FileReader ( ) ; fileReader . onload = ( event ) => { let data = fileReader . result ; if ( data instanceof ArrayBuffer ) { data = new Uint8Array ( data ) ; } if ( ! ( data instanceof Uint8Array ) ) { return reject ( new TypeError ( 'FileReader returned unknown type.' ) ) ; } resolve ( data ) ; } ; fileReader . onabort = ( event ) => { return reject ( new Error ( 'Aborted' ) ) ; } ; fileReader . onerror = ( event ) => { return reject ( new Error ( event . type ) ) ; } ; const slice = this . file . slice ( this . offset , end ) ; fileReader . readAsArrayBuffer ( slice ) ; } this . offset = end ; } ) ; return { value : ( await chunk ) , done : false } ; } }