rfc1982_serial_number.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #!/usr/bin/env python3
  2. class Serial:
  3. modulus = 2 ** 32
  4. def __init__(self, val):
  5. self._val = int(val)
  6. if self._val < 0 or self._val >= self.modulus:
  7. raise ValueError
  8. def __add__(self, val):
  9. val = int(val)
  10. if val < 0 or val > (self.modulus - 1) >> 1:
  11. raise ValueError
  12. return type(self)((self._val + val) & (self.modulus - 1))
  13. def __le__(self, other):
  14. return (self.modulus - int(self) + int(other)) & (self.modulus >> 1) == 0
  15. def __ge__(self, other):
  16. return (self.modulus + int(self) - int(other)) & (self.modulus >> 1) == 0
  17. def __eq__(self, other):
  18. return int(self) == int(other)
  19. def __ne__(self, other):
  20. return int(self) != int(other)
  21. def __lt__(self, other):
  22. return self != other and self <= other
  23. def __gt__(self, other):
  24. return self != other and self >= other
  25. def __int__(self):
  26. return self._val
  27. def __str__(self):
  28. return f"{int(self):{len(str(self.modulus))}d}"
  29. def find_intermediate(start, finish):
  30. if start < finish:
  31. return None
  32. else:
  33. wrap = start + ((Serial.modulus >> 1) - 2)
  34. assert start < wrap and wrap < finish
  35. return wrap
  36. def main():
  37. from argparse import ArgumentParser
  38. ap = ArgumentParser()
  39. ap.add_argument("start", type = Serial)
  40. ap.add_argument("finish", type = Serial)
  41. args = ap.parse_args()
  42. wrap = find_intermediate(args.start, args.finish)
  43. print(f"Start at {args.start!s}")
  44. if wrap is None:
  45. print("No step needed")
  46. else:
  47. print(f"Step via {wrap!s}")
  48. print(f"End at {args.finish!s}")
  49. if __name__ == "__main__":
  50. main()