Something went wrong. Try again.
yet another localization library
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556/** a zero-based UTF-16 range, inclusive at `start` and exclusive at `end`. */export interface Span { end: number; start: number;}
/** maps UTF-16 offsets in transformed text back to its source. */export interface OffsetMap { /** source offset past the derived text. */ end: number; /** UTF-16 length of the derived text. */ length: number; /** ordered by `derived`, starting at 0; empty for empty text. */ runs: readonly OffsetRun[];}
/** a mapping from `derived` to the next run, or the end of the derived text. */export interface OffsetRun { /** derived offset where the run starts. */ derived: number; /** * exclusive end of a source escape. every code unit in this run maps to the whole escape. * omit for a one-to-one mapping of consecutive code units. */ escapeEnd?: number; /** source offset of the run's first code unit. */ source: number;}
const unitSpan = (map: OffsetMap, offset: number): Span => { let run = map.runs[0]; for (const candidate of map.runs) { if (candidate.derived > offset) { break; } run = candidate; } if (run.escapeEnd !== undefined) { return { end: run.escapeEnd, start: run.source }; } const start = run.source + offset - run.derived; return { end: start + 1, start };};
/** * map a derived span to its source, including whole escape sequences. * @param map the offset map of the derived text * @param span a span within the derived text; clamped to its bounds * @returns the span within the source */export const mapSpan = (map: OffsetMap, span: Span): Span => { const start = span.start >= map.length ? map.end : unitSpan(map, Math.max(span.start, 0)).start; const end = Math.min(span.end, map.length); return { end: end > span.start ? Math.max(unitSpan(map, end - 1).end, start) : start, start };};