bisearch.py 812 B

1234567891011121314151617181920212223242526272829
  1. """Binary search function for Unicode interval tables."""
  2. from __future__ import annotations
  3. def bisearch(ucs: int, table: tuple[tuple[int, int], ...]) -> int:
  4. """
  5. Binary search in interval table.
  6. :param ucs: Ordinal value of unicode character.
  7. :param table: Tuple of starting and ending ranges of ordinal values,
  8. in form of ``((start, end), ...)``.
  9. :returns: 1 if ordinal value ucs is found within lookup table, else 0.
  10. """
  11. lbound = 0
  12. ubound = len(table) - 1
  13. if ucs < table[0][0] or ucs > table[ubound][1]:
  14. return 0
  15. while ubound >= lbound:
  16. mid = (lbound + ubound) // 2
  17. if ucs > table[mid][1]:
  18. lbound = mid + 1
  19. elif ucs < table[mid][0]:
  20. ubound = mid - 1
  21. else:
  22. return 1
  23. return 0