Skip to content

Instantly share code, notes, and snippets.

@tmr232
Created April 2, 2015 11:30
Show Gist options
  • Save tmr232/1557756a02aae4ebcc92 to your computer and use it in GitHub Desktop.
Save tmr232/1557756a02aae4ebcc92 to your computer and use it in GitHub Desktop.
Construct Suggestion - Ordered Keyword Arguments
from easy_construct import cs, struct, Container
MyStruct = struct("MyStruct",
_0=cs.Magic("EZConstruct"),
variable=cs.UBInt32,
another_var=cs.UBInt16,
_1=cs.Padding(0x4),
array=cs.Bytes(13),
_2=cs.Magic("MagicEndsHere"),
)
sample_data = 'EZConstruct\xde\xad\xbe\xef\x137\x00\x00\x00\x00Hello, World!MagicEndsHere'
if __name__ == '__main__':
print MyStruct.parse(sample_data)
import operator
import construct
from construct import this, Container
class ConstructGetter(object):
def __init__(self):
self._index = 0
def __getattr__(self, name):
cons = getattr(construct, name)
proxy = ConstructProxy(cons, self._index)
self._index += 1
return proxy
class ConstructProxy(object):
def __init__(self, cons, index):
self._cons = cons
self._index = index
self._args = []
self._kwargs = {}
self._value = None
def __call__(self, *args, **kwargs):
self._args = args
self._kwargs = kwargs
return self
def is_name_significant(self, name):
if name:
return (name[0] != "_") or (not name[1:].isdigit())
return False
def get(self, name):
if self._value is None:
if self.is_name_significant(name):
self._value = self._cons(name, *self._args, **self._kwargs)
else:
self._value = self._cons(*self._args, **self._kwargs)
return self._value
def __cmp__(self, other):
return cmp(self._index, other._index)
def __getattr__(self, name):
return getattr(self.get(None), name)
cs = ConstructGetter()
def subcons(**members):
members = members.items()
members = sorted(members, key=operator.itemgetter(1))
members = [value.get(name) for name, value in members]
return members
def struct(name, **members):
return construct.Struct(name, *subcons(**members))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment