1 ## Copyright 2002-2003 Andrew Loewenstern, All Rights Reserved
2 # see LICENSE.txt for license information
8 """20 bit hash, big-endian -> long python integer"""
10 return long(hstr.encode('hex'), 16)
13 """long int -> 20-character string"""
19 str = str.decode('hex')
20 return (20 - len(str)) *'\x00' + str
23 """distance between two 160-bit hashes expressed as 20-character strings"""
24 return intify(a) ^ intify(b)
28 """returns a new pseudorandom globally unique ID string"""
33 def newIDInRange(min, max):
34 return stringify(randRange(min,max))
36 def randRange(min, max):
37 return min + intify(newID()) % (max - min)
40 return randRange(-2**30, 2**30)
45 class NewID(unittest.TestCase):
47 self.assertEqual(len(newID()), 20)
48 def testHundreds(self):
52 class Intify(unittest.TestCase):
53 known = [('\0' * 20, 0),
54 ('\xff' * 20, 2L**160 - 1),
57 for str, value in self.known:
58 self.assertEqual(intify(str), value)
59 def testEndianessOnce(self):
61 while h[-1] == '\xff':
63 k = h[:-1] + chr(ord(h[-1]) + 1)
64 self.assertEqual(intify(k) - intify(h), 1)
65 def testEndianessLots(self):
67 self.testEndianessOnce()
69 class Disantance(unittest.TestCase):
71 (("\0" * 20, "\xff" * 20), 2**160L -1),
72 ((sha("foo").digest(), sha("foo").digest()), 0),
73 ((sha("bar").digest(), sha("bar").digest()), 0)
76 for pair, dist in self.known:
77 self.assertEqual(distance(pair[0], pair[1]), dist)
78 def testCommutitive(self):
80 x, y, z = newID(), newID(), newID()
81 self.assertEqual(distance(x,y) ^ distance(y, z), distance(x, z))
83 class RandRange(unittest.TestCase):
89 self.assertEqual(a <= c < b, 1, "output out of range %d %d %d" % (b, c, a))
92 assert b <= c < a, "output out of range %d %d %d" % (b, c, a)
94 def testOneHundredTimes(self):
100 if __name__ == '__main__':