Advertisement
Guest User

Simple Netstring

a guest
Jan 8th, 2013
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.77 KB | None | 0 0
  1. from cStringIO import StringIO                                                  
  2. import struct
  3.  
  4. HEADER_FMT = '!L'
  5. HEADER_SIZE = 4
  6.  
  7. class NSBuffer(object):
  8.     def __init__(self):
  9.         self.buf = StringIO()
  10.  
  11.     def write(self, s):
  12.         self.buf.write(s)
  13.  
  14.     def extract(self):
  15.         v = self.buf.getvalue()
  16.         res = []
  17.         while len(v) >= HEADER_SIZE:
  18.             l, = struct.unpack(HEADER_FMT, v[:HEADER_SIZE])
  19.             truncated = v[HEADER_SIZE:]
  20.             if len(truncated) >= l:
  21.                 res.append(truncated[:l])
  22.                 v = truncated[l:]
  23.             else:
  24.                 break
  25.         self.buf = StringIO()
  26.         self.buf.write(v)
  27.         return res
  28.  
  29. def ns_encode(s):
  30.     return struct.pack(HEADER_FMT, len(s)) + s
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement