Skip to content
Snippets Groups Projects
epidemic.py 837 B
Newer Older
  • Learn to ignore specific revisions
  • Jarrod Pas's avatar
    Jarrod Pas committed
    from collections import defaultdict
    
    
    from .base import Router
    
    Jarrod Pas's avatar
    Jarrod Pas committed
    
    
    class EpidemicRouter(Router):
        def __init__(self, node, **kwargs):
            super().__init__(node, **kwargs)
    
            # maps a packet to a set of nodes that the packet has been sent to
            self.sent = defaultdict(set)
    
        def __call__(self, packet):
            # get list of currently encountered nodes that do not have the packet
            targets = [
                met
                for met in self.node.links
                if met not in self.sent[packet]
            ]
    
            # update set of nodes a packet was sent to
            self.sent[packet].update(targets)
    
            # return list of nodes to send packet to
            # (targets, remove from buffer, reason)
            if targets:
                return targets, 'epidemic', False
            else:
                return None, None, False
    
    Jarrod Pas's avatar
    Jarrod Pas committed