Install

NetStruct runs on Python 2.6+. Python 3 should work as
well, but is currently untested.

Differences from struct

NetStruct has two differences from struct.

First, it defaults to using network byte-order, rather than native byte-order,
on the assumption that you’ll be using it to send data over the network and,
thus, it’s saving you time.

Additionally, the generated strings don’t have any padding when using
non-native byte-order.

Second, NetStruct supports a new formatting character, the dollar sign ($).
The dollar sign represents a variable-length string, encoded with its length
preceeding the string itself. To accomplish this, the formatting character
directly before the dollar sign is assumed to represent the string’s length.

But wait, you say. How am I supposed to provide a long enough string to
unpack the data when I can’t possibly know the length ahead of time?
Simply put, you can know the length.

>>> it = netstruct.iter_unpack("ih$5b")
>>> it.next()
11

The iter_unpack function returns an iterator. Each time you call that
iterator’s .next() or .send() methods, it can return one of two values. Either
it’ll return the number of bytes it wants you to read next, or it’ll return
the completed object.

There. I’ve sent enough data, so it returned the completed list of the
unpacked data. At this point, I can take my data, and do whatever it is I want
with it.

But wait! I just sent too much data to that iterator, and now I’ve lost some
of my string, haven’t I? That’s not a problem either. You can call the iterator
one final time and it will return the unconsumed remainder of the data.

>>> it.next()
' more'

It’s just that simple. Of course, not everyone likes iterators, even if they
are quicker and less memory intensive than a class instance. NetStruct is
prepared, with its Unpacker class and obj_unpack. Let’s try that last
example one more time.