rfc1982_serial_number.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. while not (start < finish): # sic: serial numbers are not (quite) integers
  31. start += ((Serial.modulus >> 1) - 1)
  32. yield start
  33. def main():
  34. from argparse import ArgumentParser
  35. ap = ArgumentParser()
  36. ap.add_argument("start", type = Serial)
  37. ap.add_argument("finish", type = Serial)
  38. args = ap.parse_args()
  39. print(f"Start at {args.start!s}")
  40. if args.start < args.finish:
  41. print("No step needed")
  42. else:
  43. for wrap in find_intermediate(args.start, args.finish):
  44. print(f"Step via {wrap!s}")
  45. print(f"End at {args.finish!s}")
  46. if __name__ == "__main__":
  47. main()