1 ## Copyright 2002 Andrew Loewenstern, All Rights Reserved
7 """20 bit hash, big-endian -> long python integer"""
9 return long(hstr.encode('hex'), 16)
12 """long int -> 20-character string"""
18 str = str.decode('hex')
19 return (20 - len(str)) *'\x00' + str
22 """distance between two 160-bit hashes expressed as 20-character strings"""
23 return intify(a) ^ intify(b)
27 """returns a new pseudorandom globally unique ID string"""
30 h.update(chr(whrandom.randrange(0,256)))
33 def newIDInRange(min, max):
34 return stringify(randRange(min,max))
36 def randRange(min, max):
37 return min + intify(newID()) % (max - min)
43 class NewID(unittest.TestCase):
45 self.assertEqual(len(newID()), 20)
46 def testHundreds(self):
50 class Intify(unittest.TestCase):
51 known = [('\0' * 20, 0),
52 ('\xff' * 20, 2L**160 - 1),
55 for str, value in self.known:
56 self.assertEqual(intify(str), value)
57 def testEndianessOnce(self):
59 while h[-1] == '\xff':
61 k = h[:-1] + chr(ord(h[-1]) + 1)
62 self.assertEqual(intify(k) - intify(h), 1)
63 def testEndianessLots(self):
65 self.testEndianessOnce()
67 class Disantance(unittest.TestCase):
69 (("\0" * 20, "\xff" * 20), 2**160L -1),
70 ((sha("foo").digest(), sha("foo").digest()), 0),
71 ((sha("bar").digest(), sha("bar").digest()), 0)
74 for pair, dist in self.known:
75 self.assertEqual(distance(pair[0], pair[1]), dist)
76 def testCommutitive(self):
78 x, y, z = newID(), newID(), newID()
79 self.assertEqual(distance(x,y) ^ distance(y, z), distance(x, z))
81 class RandRange(unittest.TestCase):
87 self.assertEqual(a <= c < b, 1, "output out of range %d %d %d" % (b, c, a))
90 assert b <= c < a, "output out of range %d %d %d" % (b, c, a)
92 def testOneHundredTimes(self):
98 if __name__ == '__main__':