Ensure id is unique in set of ids. Append '_1', '_2'... if not `counters` is an optional cache which maps a base id to the highest `n` for which `base_1` through `base_n` are all known to be in `ids`. When the same cache is passed along with the same `ids` on every call, a repeated id
(id: str, ids: MutableSet[str], counters: dict[str, int] | None = None)
| 55 | |
| 56 | |
| 57 | def unique(id: str, ids: MutableSet[str], counters: dict[str, int] | None = None) -> str: |
| 58 | """ Ensure id is unique in set of ids. Append '_1', '_2'... if not |
| 59 | |
| 60 | `counters` is an optional cache which maps a base id to the highest `n` for which |
| 61 | `base_1` through `base_n` are all known to be in `ids`. When the same cache is passed |
| 62 | along with the same `ids` on every call, a repeated id skips past the suffixes which |
| 63 | earlier calls already found to be taken rather than checking each of them again. |
| 64 | """ |
| 65 | if id in ids or not id: |
| 66 | m = IDCOUNT_RE.match(id) |
| 67 | if m: |
| 68 | base, count = m.group(1), int(m.group(2)) |
| 69 | else: |
| 70 | base, count = id, 0 |
| 71 | skip = False |
| 72 | if counters is not None: |
| 73 | known = counters.get(base, 0) |
| 74 | # Only skip ahead when this id falls within the run of suffixes known to be |
| 75 | # taken, or is the next one after it, as any later suffix may still be free. |
| 76 | if count <= known or id == f'{base}_{known + 1}': |
| 77 | skip = True |
| 78 | count = max(count, known) |
| 79 | count += 1 |
| 80 | while f'{base}_{count}' in ids: |
| 81 | count += 1 |
| 82 | id = f'{base}_{count}' |
| 83 | if skip: |
| 84 | # Every suffix from `base_1` through the new id is now known to be taken. |
| 85 | counters[base] = count |
| 86 | ids.add(id) |
| 87 | return id |
| 88 | |
| 89 | |
| 90 | @deprecated('Use `render_inner_html` and `striptags` instead.') |