Path: blob/master/venv/Lib/site-packages/idna/intranges.py
811 views
"""1Given a list of integers, made up of (hopefully) a small number of long runs2of consecutive integers, compute a representation of the form3((start1, end1), (start2, end2) ...). Then answer the question "was x present4in the original list?" in time O(log(# runs)).5"""67import bisect89def intranges_from_list(list_):10"""Represent a list of integers as a sequence of ranges:11((start_0, end_0), (start_1, end_1), ...), such that the original12integers are exactly those x such that start_i <= x < end_i for some i.1314Ranges are encoded as single integers (start << 32 | end), not as tuples.15"""1617sorted_list = sorted(list_)18ranges = []19last_write = -120for i in range(len(sorted_list)):21if i+1 < len(sorted_list):22if sorted_list[i] == sorted_list[i+1]-1:23continue24current_range = sorted_list[last_write+1:i+1]25ranges.append(_encode_range(current_range[0], current_range[-1] + 1))26last_write = i2728return tuple(ranges)2930def _encode_range(start, end):31return (start << 32) | end3233def _decode_range(r):34return (r >> 32), (r & ((1 << 32) - 1))353637def intranges_contain(int_, ranges):38"""Determine if `int_` falls into one of the ranges in `ranges`."""39tuple_ = _encode_range(int_, 0)40pos = bisect.bisect_left(ranges, tuple_)41# we could be immediately ahead of a tuple (start, end)42# with start < int_ <= end43if pos > 0:44left, right = _decode_range(ranges[pos-1])45if left <= int_ < right:46return True47# or we could be immediately behind a tuple (int_, end)48if pos < len(ranges):49left, _ = _decode_range(ranges[pos])50if left == int_:51return True52return False535455