示例#1
0
 def test_order(self):
     o = OrderedSet()
     o.push('1')
     o.push('1')
     o.push('2')
     o.push('1')
     self.assertEqual(o, ['2', '1'])
示例#2
0
 def __init__(self, rangeLower, rangeUpper, ksize):
     self.range = (rangeLower, rangeUpper)
     self.nodes = OrderedDict()
     self.replacementNodes = OrderedSet()
     self.touchLastUpdated()
     self.ksize = ksize
示例#3
0
class KBucket(object):
    def __init__(self, rangeLower, rangeUpper, ksize):
        self.range = (rangeLower, rangeUpper)
        self.nodes = OrderedDict()
        self.replacementNodes = OrderedSet()
        self.touchLastUpdated()
        self.ksize = ksize

    def touchLastUpdated(self):
        self.lastUpdated = time.time()

    def getNodes(self):
        return self.nodes.values()

    def split(self):
        midpoint = (self.range[0] + self.range[1]) / 2
        one = KBucket(self.range[0], midpoint, self.ksize)
        two = KBucket(midpoint + 1, self.range[1], self.ksize)
        for node in self.nodes.values():
            bucket = one if node.long_id <= midpoint else two
            bucket.nodes[node.id] = node
        return (one, two)

    def removeNode(self, node):
        if node.id not in self.nodes:
            return

        # delete node, and see if we can add a replacement
        del self.nodes[node.id]
        if len(self.replacementNodes) > 0:
            newnode = self.replacementNodes.pop()
            self.nodes[newnode.id] = newnode

    def hasInRange(self, node):
        return self.range[0] <= node.long_id <= self.range[1]

    def isNewNode(self, node):
        return node.id not in self.nodes

    def addNode(self, node):
        """
        Add a C{Node} to the C{KBucket}.  Return True if successful,
        False if the bucket is full.

        If the bucket is full, keep track of node in a replacement list,
        per section 4.1 of the paper.
        """
        if node.id in self.nodes:
            del self.nodes[node.id]
            self.nodes[node.id] = node
        elif len(self) < self.ksize:
            self.nodes[node.id] = node
        else:
            self.replacementNodes.push(node)
            return False
        return True

    def depth(self):
        sp = sharedPrefix([n.id for n in self.nodes.values()])
        return len(sp)

    def head(self):
        return self.nodes.values()[0]

    def __getitem__(self, id):
        return self.nodes.get(id, None)

    def __len__(self):
        return len(self.nodes)