Kaynağa Gözat

Simpler implementation without KRE's whacky conditionals

Rob Austein 7 ay önce
ebeveyn
işleme
1ddfdff6a7
1 değiştirilmiş dosya ile 19 ekleme ve 13 silme
  1. 19 13
      rfc1982_serial_number.py

+ 19 - 13
rfc1982_serial_number.py

@@ -2,17 +2,21 @@
 
 class Serial:
 
+    _modulus = 2 ** 32
+    _bitmask = _modulus - 1
+    _signbit = _modulus >> 1
+
     def __init__(self, val):
-        self._val = int(val) % 2**32
+        self._val = int(val) & self._bitmask
 
-    def __int__(self):
-        return self._val
+    def __add__(self, val):
+        return self.__class__(self._val + int(val))
 
-    def __str__(self):
-        return str(int(self))
+    def __le__(self, other):
+        return (self._modulus - int(self) + int(other)) & self._signbit == 0
 
-    def __add__(self, val):
-        return Serial(self._val + int(val))
+    def __ge__(self, other):
+        return (self._modulus + int(self) - int(other)) & self._signbit == 0
 
     def __eq__(self, other):
         return int(self) == int(other)
@@ -21,14 +25,16 @@ class Serial:
         return int(self) != int(other)
 
     def __lt__(self, other):
-        return self != other and (
-            (int(self) < int(other) and int(other) - int(self)  < 2**31) or
-            (int(self) > int(other) and int(self)  - int(other) > 2**31))
+        return self != other and self <= other
 
     def __gt__(self, other):
-        return self != other and (
-            (int(self) < int(other) and int(other) - int(self)  > 2**31) or
-            (int(self) > int(other) and int(self)  - int(other) < 2**31))
+        return self != other and self >= other
+
+    def __int__(self):
+        return self._val
+
+    def __str__(self):
+        return str(int(self))
 
 if __name__ == "__main__":
     from random import randint