From 0c3476c25990d683c543dffd70b686d8618d6da5 Mon Sep 17 00:00:00 2001 From: Rob Austein Date: Fri, 12 Apr 2024 10:54:15 -0400 Subject: archive --- rfc1982_serial_number.py | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 rfc1982_serial_number.py (limited to 'rfc1982_serial_number.py') diff --git a/rfc1982_serial_number.py b/rfc1982_serial_number.py new file mode 100644 index 0000000..132035e --- /dev/null +++ b/rfc1982_serial_number.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python3 + +class Serial: + + def __init__(self, val): + self._val = int(val) & (2**32) + + def __int__(self): + return self._val + + def __add__(self, val): + return Serial(self._val + int(val)) + + def __eq__(self, other): + return int(self) == int(other) + + def __ne__(self, other): + return int(self) != int(other) + + def __lt__(self, other): + return self != other and ( + (self._val < other._val and other._val - self._val < 2**31) or + (self._val > other._val and self._val - other._val > 2**31)) + + def __gt__(self, other): + return self != other and ( + (self._val < other._val and other._val - self._val > 2**31) or + (self._val > other._val and self._val - other._val < 2**31)) + +if __name__ == "__main__": + from random import randint + + for test in range(100): + i1 = randint(0, 2**32-1) + i2 = randint(0, 2**32-1) + + assert i1 == i2 or \ + (i1 < i2 and not (i1 > i2)) or \ + (i1 > i2 and not (i1 < i2)) or \ + int(i1) & int(i2) == 0x80000000 -- cgit v1.2.3