@@ -12,13 +12,28 @@ const ADDRESS_SIZE = 10
1212export default class Trix {
1313 private decoder = new TextDecoder ( 'utf8' )
1414 private indexCache ?: readonly ( readonly [ string , number ] ) [ ]
15+ private ixFileSize ?: number
1516
1617 constructor (
1718 public ixxFile : GenericFilehandle ,
1819 public ixFile : GenericFilehandle ,
1920 public maxResults = 20 ,
2021 ) { }
2122
23+ private async getIxFileSize ( opts ?: { signal ?: AbortSignal } ) {
24+ if ( this . ixFileSize !== undefined ) {
25+ return this . ixFileSize
26+ }
27+ try {
28+ // @ts -expect-error
29+ const stat = await this . ixFile . stat ( opts )
30+ this . ixFileSize = stat . size
31+ return this . ixFileSize
32+ } catch {
33+ return undefined
34+ }
35+ }
36+
2237 async search ( searchString : string , opts ?: { signal ?: AbortSignal } ) {
2338 let resultArr = [ ] as [ string , string ] [ ]
2439 const searchWords = searchString . split ( ' ' )
@@ -30,6 +45,7 @@ export default class Trix {
3045 const res = await this . getBuffer ( searchWord , opts )
3146
3247 let { end, buffer } = res
48+ const { fileSize } = res
3349 let done = false
3450 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
3551 while ( ! done ) {
@@ -68,13 +84,22 @@ export default class Trix {
6884 break
6985 }
7086
71- // fetch more data
72- const res2 = await this . ixFile . read ( CHUNK_SIZE , end , opts )
87+ // avoid reading past end of file
88+ if ( fileSize !== undefined && end >= fileSize ) {
89+ break
90+ }
91+
92+ // fetch more data, clamping to file size if known
93+ let bytesToRead = CHUNK_SIZE
94+ if ( fileSize !== undefined ) {
95+ bytesToRead = Math . min ( CHUNK_SIZE , fileSize - end )
96+ }
97+ const res2 = await this . ixFile . read ( bytesToRead , end , opts )
7398 if ( res2 . length === 0 ) {
7499 break
75100 }
76101 buffer = concatUint8Array ( [ buffer , res2 ] )
77- end += CHUNK_SIZE
102+ end += res2 . length
78103 }
79104 }
80105
@@ -116,7 +141,12 @@ export default class Trix {
116141 }
117142 }
118143
144+ const fileSize = await this . getIxFileSize ( opts )
145+ if ( fileSize !== undefined ) {
146+ end = Math . min ( end , fileSize )
147+ }
148+
119149 const buffer = await this . ixFile . read ( end - start , start , opts )
120- return { buffer, end }
150+ return { buffer, end, fileSize }
121151 }
122152}
0 commit comments