def SeqOfOne(name, *args, **kw): """a sequence of one element. only the first element is meaningful, the rest are discarded * name - the name of the sequence * args - subconstructs * kw - any keyword arguments to Sequence """ return IndexingAdapter(Sequence(name, *args, **kw), index=0)
def SeqOfOne(name, *args, **kw): r"""A sequence of one element. only the first element is meaningful, the rest are discarded :param name: the name of the sequence :param \*args: subconstructs :param \*\*kw: any keyword arguments to Sequence """ return IndexingAdapter(Sequence(name, *args, **kw), index=0)
def PrefixedArray(subcon, length_field=UBInt8("length")): """an array prefixed by a length field. * subcon - the subcon to be repeated * length_field - a construct returning an integer """ return LengthValueAdapter( Sequence(subcon.name, length_field, Array(lambda ctx: ctx[length_field.name], subcon), nested=False))
def PrefixedArray(subcon, length_field=UBInt8("length")): """An array prefixed by a length field. :param subcon: the subcon to be repeated :param length_field: a construct returning an integer """ def _length(ctx): if issubclass(ctx.__class__, (list, tuple)): return len(ctx) return ctx[length_field.name] return LengthValueAdapter( Sequence(subcon.name, length_field, Array(_length, subcon), nested=False))
def PascalString(name, length_field=UBInt8("length"), encoding=None): r""" A length-prefixed string. ``PascalString`` is named after the string types of Pascal, which are length-prefixed. Lisp strings also follow this convention. The length field will appear in the same ``Container`` as the ``PascalString``, with the given name. :param name: name :param length_field: a field which will store the length of the string :param encoding: encoding (e.g. "utf8") or None for no encoding Example:: >>> foo = PascalString("foo") >>> foo.parse("\x05hello") 'hello' >>> foo.build("hello world") '\x0bhello world' >>> >>> foo = PascalString("foo", length_field = UBInt16("length")) >>> foo.parse("\x00\x05hello") 'hello' >>> foo.build("hello") '\x00\x05hello' """ return StringAdapter( LengthValueAdapter( Sequence( name, length_field, Field("data", lambda ctx: ctx[length_field.name]), )), encoding=encoding, )