annotate CSP2/CSP2_env/env-d9b9114564458d9d-741b3de822f2aaca6c6caa4325c4afce/lib/python3.8/site-packages/idna/intranges.py @ 69:33d812a61356

planemo upload commit 2e9511a184a1ca667c7be0c6321a36dc4e3d116d
author jpayne
date Tue, 18 Mar 2025 17:55:14 -0400
parents
children
rev   line source
jpayne@69 1 """
jpayne@69 2 Given a list of integers, made up of (hopefully) a small number of long runs
jpayne@69 3 of consecutive integers, compute a representation of the form
jpayne@69 4 ((start1, end1), (start2, end2) ...). Then answer the question "was x present
jpayne@69 5 in the original list?" in time O(log(# runs)).
jpayne@69 6 """
jpayne@69 7
jpayne@69 8 import bisect
jpayne@69 9 from typing import List, Tuple
jpayne@69 10
jpayne@69 11
jpayne@69 12 def intranges_from_list(list_: List[int]) -> Tuple[int, ...]:
jpayne@69 13 """Represent a list of integers as a sequence of ranges:
jpayne@69 14 ((start_0, end_0), (start_1, end_1), ...), such that the original
jpayne@69 15 integers are exactly those x such that start_i <= x < end_i for some i.
jpayne@69 16
jpayne@69 17 Ranges are encoded as single integers (start << 32 | end), not as tuples.
jpayne@69 18 """
jpayne@69 19
jpayne@69 20 sorted_list = sorted(list_)
jpayne@69 21 ranges = []
jpayne@69 22 last_write = -1
jpayne@69 23 for i in range(len(sorted_list)):
jpayne@69 24 if i + 1 < len(sorted_list):
jpayne@69 25 if sorted_list[i] == sorted_list[i + 1] - 1:
jpayne@69 26 continue
jpayne@69 27 current_range = sorted_list[last_write + 1 : i + 1]
jpayne@69 28 ranges.append(_encode_range(current_range[0], current_range[-1] + 1))
jpayne@69 29 last_write = i
jpayne@69 30
jpayne@69 31 return tuple(ranges)
jpayne@69 32
jpayne@69 33
jpayne@69 34 def _encode_range(start: int, end: int) -> int:
jpayne@69 35 return (start << 32) | end
jpayne@69 36
jpayne@69 37
jpayne@69 38 def _decode_range(r: int) -> Tuple[int, int]:
jpayne@69 39 return (r >> 32), (r & ((1 << 32) - 1))
jpayne@69 40
jpayne@69 41
jpayne@69 42 def intranges_contain(int_: int, ranges: Tuple[int, ...]) -> bool:
jpayne@69 43 """Determine if `int_` falls into one of the ranges in `ranges`."""
jpayne@69 44 tuple_ = _encode_range(int_, 0)
jpayne@69 45 pos = bisect.bisect_left(ranges, tuple_)
jpayne@69 46 # we could be immediately ahead of a tuple (start, end)
jpayne@69 47 # with start < int_ <= end
jpayne@69 48 if pos > 0:
jpayne@69 49 left, right = _decode_range(ranges[pos - 1])
jpayne@69 50 if left <= int_ < right:
jpayne@69 51 return True
jpayne@69 52 # or we could be immediately behind a tuple (int_, end)
jpayne@69 53 if pos < len(ranges):
jpayne@69 54 left, _ = _decode_range(ranges[pos])
jpayne@69 55 if left == int_:
jpayne@69 56 return True
jpayne@69 57 return False