Pastebin launched a little side project called HostCabi.net, check it out ;-)Don't like ads? PRO users don't see any ads ;-)
Guest

Simple Netstring

By: a guest on Jan 8th, 2013  |  syntax: Python  |  size: 0.77 KB  |  hits: 33  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  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