rfc1982_serial_number.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #!/usr/bin/env python3
  2. class Serial:
  3. def __init__(self, val):
  4. self._val = int(val) % 2**32
  5. def __int__(self):
  6. return self._val
  7. def __str__(self):
  8. return str(int(self))
  9. def __add__(self, val):
  10. return Serial(self._val + int(val))
  11. def __eq__(self, other):
  12. return int(self) == int(other)
  13. def __ne__(self, other):
  14. return int(self) != int(other)
  15. def __lt__(self, other):
  16. return self != other and (
  17. (int(self) < int(other) and int(other) - int(self) < 2**31) or
  18. (int(self) > int(other) and int(self) - int(other) > 2**31))
  19. def __gt__(self, other):
  20. return self != other and (
  21. (int(self) < int(other) and int(other) - int(self) > 2**31) or
  22. (int(self) > int(other) and int(self) - int(other) < 2**31))
  23. if __name__ == "__main__":
  24. from random import randint
  25. for test in range(100):
  26. i1 = Serial(randint(0, 2**32-1))
  27. i2 = Serial(randint(0, 2**32-1))
  28. assert i1 == i2 or \
  29. (i1 < i2 and not (i1 > i2)) or \
  30. (i1 > i2 and not (i1 < i2)) or \
  31. int(i1) & int(i2) == 0x80000000
  32. if i1 == i2:
  33. print(f"{int(i1):10d} == {int(i2):10d}, how did that happen?")
  34. elif i1 < i2:
  35. print(f"{int(i1):10d} => {int(i2):10d}, can do it in one jump")
  36. else:
  37. i3 = i1 + (2**31 - 2)
  38. print(f"{int(i1):10d} => {int(i2):10d}, need to wrap, i3 value {i3}")
  39. assert i1 < i3 and i3 < i2