1 ## Copyright 2002-2003 Andrew Loewenstern, All Rights Reserved
2 # see LICENSE.txt for license information
4 """Some utitlity functions for use in apt-p2p's khashmir DHT."""
6 from twisted.trial import unittest
9 """Given a list of khashmir instances, finds min, max, and average number of nodes in tables."""
14 for bucket in buckets:
18 c = count(node.table.buckets)
27 return {'min':min, 'max':max, 'avg':avg}
30 """Extract the contact info from a compact node representation.
33 @param s: the compact representation
35 @return: the node ID, IP address and port to contact the node on
36 @raise ValueError: if the compact representation doesn't exist
41 host = '.'.join([str(ord(i)) for i in s[20:24]])
42 port = (ord(s[24]) << 8) | ord(s[25])
43 return {'id': id, 'host': host, 'port': port}
45 def compact(id, host, port):
46 """Create a compact representation of node contact info.
49 @param id: the node ID
51 @param host: the IP address of the node
53 @param port: the port number to contact the node on
55 @return: the compact representation
56 @raise ValueError: if the compact representation doesn't exist
59 s = id + ''.join([chr(int(i)) for i in host.split('.')]) + \
60 chr((port & 0xFF00) >> 8) + chr(port & 0xFF)
66 """Format a byte size for reading by the user.
69 @param s: the number of bytes
71 @return: the formatted size with appropriate units
78 r = str(int((s/1024.0)*100.0)/100.0) + 'KiB'
80 r = str(int((s/1024.0)*10.0)/10.0) + 'KiB'
82 r = str(int(s/1024)) + 'KiB'
84 r = str(int((s/1048576.0)*100.0)/100.0) + 'MiB'
85 elif (s < 107374182L):
86 r = str(int((s/1048576.0)*10.0)/10.0) + 'MiB'
87 elif (s < 1073741824L):
88 r = str(int(s/1048576)) + 'MiB'
89 elif (s < 1099511627776L):
90 r = str(int((s/1073741824.0)*100.0)/100.0) + 'GiB'
92 r = str(int((s/1099511627776.0)*100.0)/100.0) + 'TiB'
95 class TestUtil(unittest.TestCase):
96 """Tests for the utilities."""
99 myid = '\xca\xec\xb8\x0c\x00\xe7\x07\xf8~])\x8f\x9d\xe5_B\xff\x1a\xc4!'
100 host = '165.234.1.34'
103 def test_compact(self):
104 d = uncompact(compact(self.myid, self.host, self.port))
105 self.failUnlessEqual(d['id'], self.myid)
106 self.failUnlessEqual(d['host'], self.host)
107 self.failUnlessEqual(d['port'], self.port)