Rob Austein 7 kuukautta sitten
vanhempi
commit
b134449fa9
1 muutettua tiedostoa jossa 10 lisäystä ja 13 poistoa
  1. 10 13
      rfc1982_serial_number.py

+ 10 - 13
rfc1982_serial_number.py

@@ -4,25 +4,22 @@ class Serial:
 
     modulus = 2 ** 32
 
-    @property
-    def bitmask(self):
-        return self.modulus - 1
-
-    @property
-    def signbit(self):
-        return self.modulus >> 1
-
     def __init__(self, val):
-        self._val = int(val) & self.bitmask
+        self._val = int(val)
+        if self._val < 0 or self._val >= self.modulus:
+            raise ValueError
 
     def __add__(self, val):
-        return type(self)(self._val + int(val))
+        val = int(val)
+        if val < 0 or val > (self.modulus - 1) >> 1:
+            raise ValueError
+        return type(self)((self._val + val) & (self.modulus - 1))
 
     def __le__(self, other):
-        return (self.modulus - int(self) + int(other)) & self.signbit == 0
+        return (self.modulus - int(self) + int(other)) & (self.modulus >> 1) == 0
 
     def __ge__(self, other):
-        return (self.modulus + int(self) - int(other)) & self.signbit == 0
+        return (self.modulus + int(self) - int(other)) & (self.modulus >> 1) == 0
 
     def __eq__(self, other):
         return int(self) == int(other)
@@ -53,7 +50,7 @@ def step(start, finish):
 if __name__ == "__main__":
     from random import randint
 
-    for test in range(100):
+    for test in range(10000):
         i1 = Serial(randint(0, Serial.modulus - 1))
         i2 = Serial(randint(0, Serial.modulus - 1))