X-Git-Url: https://git.mxchange.org/?p=quix0rs-apt-p2p.git;a=blobdiff_plain;f=apt_p2p_Khashmir%2Futil.py;h=dba9d8b82bebdf4e233e50a7fc8ee03b723db2b3;hp=52b6e9794ce9f40a2431b1518242a553ed271865;hb=1e5de6cdc6ce1df1ca985e45d15c4e10931aaf38;hpb=7b1167d8ce780312d3689c9309c7e9c64060c085 diff --git a/apt_p2p_Khashmir/util.py b/apt_p2p_Khashmir/util.py index 52b6e97..dba9d8b 100644 --- a/apt_p2p_Khashmir/util.py +++ b/apt_p2p_Khashmir/util.py @@ -1,10 +1,10 @@ -## Copyright 2002-2003 Andrew Loewenstern, All Rights Reserved -# see LICENSE.txt for license information """Some utitlity functions for use in apt-p2p's khashmir DHT.""" from twisted.trial import unittest +from khash import HASH_LENGTH + def bucket_stats(l): """Given a list of khashmir instances, finds min, max, and average number of nodes in tables.""" max = avg = 0 @@ -12,7 +12,7 @@ def bucket_stats(l): def count(buckets): c = 0 for bucket in buckets: - c = c + len(bucket.l) + c = c + bucket.len() return c for node in l: c = count(node.table.buckets) @@ -35,11 +35,11 @@ def uncompact(s): @return: the node ID, IP address and port to contact the node on @raise ValueError: if the compact representation doesn't exist """ - if (len(s) != 26): + if (len(s) != HASH_LENGTH+6): raise ValueError - id = s[:20] - host = '.'.join([str(ord(i)) for i in s[20:24]]) - port = (ord(s[24]) << 8) | ord(s[25]) + id = s[:HASH_LENGTH] + host = '.'.join([str(ord(i)) for i in s[HASH_LENGTH:(HASH_LENGTH+4)]]) + port = (ord(s[HASH_LENGTH+4]) << 8) | ord(s[HASH_LENGTH+5]) return {'id': id, 'host': host, 'port': port} def compact(id, host, port): @@ -62,6 +62,40 @@ def compact(id, host, port): raise ValueError return s +def byte_format(s): + """Format a byte size for reading by the user. + + @type s: C{long} + @param s: the number of bytes + @rtype: C{string} + @return: the formatted size with appropriate units + """ + if (s < 1): + r = str(int(s*1000.0)/1000.0) + 'B' + elif (s < 10): + r = str(int(s*100.0)/100.0) + 'B' + elif (s < 102): + r = str(int(s*10.0)/10.0) + 'B' + elif (s < 1024): + r = str(int(s)) + 'B' + elif (s < 10485): + r = str(int((s/1024.0)*100.0)/100.0) + 'KiB' + elif (s < 104857): + r = str(int((s/1024.0)*10.0)/10.0) + 'KiB' + elif (s < 1048576): + r = str(int(s/1024)) + 'KiB' + elif (s < 10737418L): + r = str(int((s/1048576.0)*100.0)/100.0) + 'MiB' + elif (s < 107374182L): + r = str(int((s/1048576.0)*10.0)/10.0) + 'MiB' + elif (s < 1073741824L): + r = str(int(s/1048576)) + 'MiB' + elif (s < 1099511627776L): + r = str(int((s/1073741824.0)*100.0)/100.0) + 'GiB' + else: + r = str(int((s/1099511627776.0)*100.0)/100.0) + 'TiB' + return(r) + class TestUtil(unittest.TestCase): """Tests for the utilities."""