/ src / iterator.ts
iterator.ts
 1  import { StreamSearch, type Token } from "./search.js";
 2  
 3  export class IteratorStreamSearch {
 4  	private _search: StreamSearch;
 5  
 6  	public constructor(
 7  		needle: Uint8Array | string,
 8  		private _iter: AsyncIterable<Uint8Array>,
 9  	) {
10  		this._search = new StreamSearch(needle);
11  	}
12  
13  	public async *[Symbol.asyncIterator](): AsyncIterableIterator<Token> {
14  		const it = this._iter[Symbol.asyncIterator]();
15  		while (true) {
16  			let result: IteratorResult<Uint8Array>;
17  			try {
18  				result = await it.next();
19  			} catch (error) {
20  				if (it.throw) {
21  					result = await it.throw(error);
22  				} else {
23  					throw error;
24  				}
25  			}
26  
27  			if (result.done) {
28  				break;
29  			}
30  
31  			yield* this._search.feed(result.value);
32  		}
33  
34  		const tail = this._search.end();
35  		if (tail.length) {
36  			yield tail;
37  		}
38  	}
39  }