protocol-example /

Full commit
from inspect import currentframe
import struct

def mktoken(name, types):
    """Create a token"""
    return Token(types['java'], name, fmt=types['ctypes'], 
                 simple=not types['java'] == "String")

def typedef(type_spec):
    """Function that creates a type function,
    which associates a name with a type specification"""
    def type_fn(name):
        """Inject the type definition type_def into 
        the calling scope with the given name"""
        frame = currentframe().f_back
        frame.f_locals[name] =  mktoken(name, type_spec)       
        del frame
    return type_fn

i64 = typedef({'ctypes': 'q', 'java': 'long'})
i16 = typedef({'ctypes': 'h', 'java': 'short'})
string = typedef({'ctypes': 'x', 'java': 'String'})

class Token(object):
    """Represents one or more tokens"""
    simple = True

    def __init__(self, javaname, name, fmt="x", simple=True):
        self.simple = simple
        self.fmt = fmt
        self.javaname = javaname = name
        self.pattern_size = struct.calcsize(self.fmt)

    def parse(self, buf):
        if self.simple:
            values = struct.unpack("!%s" % (self.fmt), 
            return { values[0]}
            strlen = struct.unpack("!h",[:2])[0]
            str_ = struct.unpack("!%ss" % (strlen,),[2:2+strlen])[0]
            return { str_} 
    def __str__(self):
        type_ = "simple" if self.simple else "string"
        return "%s token with format %s" % (type_, self.fmt)
class Buffer(object):
    """Class to hold a message buffer. Each token will
    consume parts of the buffer as it parses the message"""
    def __init__(self, data): = data  
class Message(object):
    """A message, knows how to parse data"""
    def __init__(self, msgname, msgdesc, msgtype, *tokens):
        self.tokens = tokens
        self.__doc__ = msgdesc
        self.parsers = self.tokens = msgname
        self.type = hex(msgtype) #for java
    def parse(self, data):
        buf = Buffer(data[1:]) #remove type byte
        result = {'type':}
        for res in [x.parse(buf) for x in self.parsers]:            
        assert len( == 0
        return result