in packages/selector/src/text/seeker.ts [259:310]
private _readOrSeekToChunk(
read: false,
target: TChunk,
offset?: number,
): void;
private _readOrSeekToChunk(
read: boolean,
target: TChunk,
offset = 0,
): string | void {
const oldPosition = this.position;
let result = '';
// Walk to the requested chunk.
if (!this.chunker.precedesCurrentChunk(target)) {
// Search forwards.
while (!chunkEquals(this.currentChunk, target)) {
const [data, nextChunk] = this._readToNextChunk();
if (read) result += data;
if (nextChunk === null) throw new RangeError(E_END);
}
} else {
// Search backwards.
while (!chunkEquals(this.currentChunk, target)) {
const [data, previousChunk] = this._readToPreviousChunk();
if (read) result = data + result;
if (previousChunk === null) throw new RangeError(E_END);
}
}
// Now we know where the chunk is, walk to the requested offset.
// Note we might have started inside the chunk, and the offset could even
// point at a position before or after the chunk.
const targetPosition = this.currentChunkPosition + offset;
if (!read) {
this.seekTo(targetPosition);
} else {
if (targetPosition >= this.position) {
// Read further until the target.
result += this.readTo(targetPosition);
} else if (targetPosition >= oldPosition) {
// We passed by our target position: step back.
this.seekTo(targetPosition);
result = result.slice(0, targetPosition - oldPosition);
} else {
// The target precedes our starting position: read backwards from there.
this.seekTo(oldPosition);
result = this.readTo(targetPosition);
}
return result;
}
}