mirror of
https://github.com/Abdess/retroarch_system.git
synced 2026-11-23 10:07:48 -06:00
core.lines.LineIndex answers the line of an offset by binary search. mame_parser and fbneo_parser counted the newlines before each match, O(n) per set, and csharp_source kept its own copy of the index. arcade_parent_importer reads a profile's repository slug through core.upstream.parse_repo and refuses a source that is not on GitHub, the only forge its fetches reach.
28 lines
837 B
Python
28 lines
837 B
Python
"""Line numbers of offsets in a text, read from one index of line starts."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import bisect
|
|
|
|
|
|
class LineIndex:
|
|
"""1-based line of any offset of *text*, by binary search.
|
|
|
|
Counting the newlines before each match is O(n) per lookup: a parser
|
|
that reports the line of every match of a file reads it once here.
|
|
"""
|
|
|
|
def __init__(self, text: str) -> None:
|
|
self._starts = [0]
|
|
position = text.find("\n")
|
|
while position != -1:
|
|
self._starts.append(position + 1)
|
|
position = text.find("\n", position + 1)
|
|
|
|
def line(self, offset: int) -> int:
|
|
return bisect.bisect_right(self._starts, offset)
|
|
|
|
def start(self, line: int) -> int:
|
|
"""Offset of the first character of a 1-based line."""
|
|
return self._starts[line - 1]
|