"""Core text replacement logic.""" def prepare_pairs(pairs: list[tuple[str, str]]) -> list[tuple[str, str]]: """Order the pairs so the longest value1 comes first. `replace_line` relies on this ordering to select the longest match at each position, which makes the result deterministic when configuration values overlap (for example "b" and "bb"). Preparing the pairs once here keeps that cost out of the per-line loop. """ return sorted(pairs, key=lambda pair: len(pair[0]), reverse=True) def replace_line(line: str, pairs: list[tuple[str, str]]) -> tuple[str, int]: """Replace all non-overlapping matches in the line. At each position the first matching value1 wins, so `pairs` must be ordered by `prepare_pairs` for the longest match to be selected. Returns the changed line and the number of symbols replaced. """ result = [] replaced_symbols = 0 position = 0 # Terminates because every branch below advances `position`, which # holds only while no value1 is empty. `load_config` rejects those. while position < len(line): match = None for value1, value2 in pairs: if line.startswith(value1, position): match = (value1, value2) break if match is None: result.append(line[position]) position += 1 continue value1, value2 = match result.append(value2) replaced_symbols += len(value1) position += len(value1) return "".join(result), replaced_symbols