1. def rsyncdelta(bufstream, remotesignatures, blocksize=4096):
  2.     remote_weak, remote_strong = remotesignatures
  3.     match = True
  4.     matchblock = -1
  5.     deltaqueue = collections.deque()
  6.  
  7.     while True:
  8.         if match and bufstream is not None:
  9.             window = collections.deque(bytes(bufstream.read(blocksize)))
  10.             checksum, a, b = weakchecksum(window)
  11.  
  12.         try:
  13.             matchblock = remote_weak.index(checksum, matchblock + 1)
  14.             stronghash = hashlib.md5(bytes(window)).hexdigest()
  15.  
  16.             if remote_strong[matchblock] == stronghash:
  17.                 match = True
  18.                 deltaqueue.append(matchblock)
  19.  
  20.                 if bufstream.closed:
  21.                     break
  22.                 continue
  23.  
  24.         except ValueError:
  25.             match = False
  26.             try:
  27.                 if bufstream:
  28.                     newbyte = ord(bufstream.read(1))
  29.                     window.append(newbyte)
  30.             except TypeError:
  31.                 newbyte = 0
  32.                 tailsize = bufstream.tell() % blocksize
  33.                 bufstream = None
  34.  
  35.             if bufstream is None and len(window) <= tailsize:
  36.                 deltaqueue.append(window)
  37.                 break
  38.  
  39.             oldbyte = window.popleft()
  40.             checksum, a, b = rollingchecksum(oldbyte, newbyte, a, b, blocksize)
  41.             #assert checksum == weakchecksum(window)[0]
  42.  
  43.             try:
  44.                 deltaqueue[-1].append(oldbyte)
  45.             except (AttributeError, IndexError):
  46.                 deltaqueue.append([oldbyte])
  47.  
  48.     deltastructure = [blocksize]
  49.     for element in deltaqueue:
  50.         if isinstance(element, int):
  51.             deltastructure.append(element)
  52.         elif element:
  53.             deltastructure.append(bytes(element))
  54.  
  55.     return deltastructure