rfc1982_serial_number.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #!/usr/bin/env python3
  2. class Serial:
  3. modulus = 2 ** 32
  4. @property
  5. def bitmask(self):
  6. return self.modulus - 1
  7. @property
  8. def signbit(self):
  9. return self.modulus >> 1
  10. def __init__(self, val):
  11. self._val = int(val) & self.bitmask
  12. def __add__(self, val):
  13. return type(self)(self._val + int(val))
  14. def __le__(self, other):
  15. return (self.modulus - int(self) + int(other)) & self.signbit == 0
  16. def __ge__(self, other):
  17. return (self.modulus + int(self) - int(other)) & self.signbit == 0
  18. def __eq__(self, other):
  19. return int(self) == int(other)
  20. def __ne__(self, other):
  21. return int(self) != int(other)
  22. def __lt__(self, other):
  23. return self != other and self <= other
  24. def __gt__(self, other):
  25. return self != other and self >= other
  26. def __int__(self):
  27. return self._val
  28. def __str__(self):
  29. return f"{int(self):{len(str(self.modulus))}d}"
  30. def step(start, finish):
  31. if start < finish:
  32. return start, finish
  33. else:
  34. midpoint = start + ((Serial.modulus >> 1) - 2)
  35. assert start < midpoint and midpoint < finish
  36. return start, midpoint, finish
  37. if __name__ == "__main__":
  38. from random import randint
  39. for test in range(100):
  40. i1 = Serial(randint(0, Serial.modulus - 1))
  41. i2 = Serial(randint(0, Serial.modulus - 1))
  42. assert i1 == i2 or \
  43. (i1 < i2 and not (i1 > i2)) or \
  44. (i1 > i2 and not (i1 < i2)) or \
  45. int(i1) & int(i2) == Serial.modulus >> 1
  46. print(f"{i1} => {i2}: {', '.join(str(s) for s in step(i1, i2))}")