diff options
author | Bob Ippolito <bob@redivi.com> | 2006-05-24 15:32:06 (GMT) |
---|---|---|
committer | Bob Ippolito <bob@redivi.com> | 2006-05-24 15:32:06 (GMT) |
commit | eb62127842a04817a6fc3bedba4e7478e561279d (patch) | |
tree | 71befa7f281b21738bebab2bff2c354c277e2379 /Lib | |
parent | d5e0dc51cf1e570e8ad06ddc78e9f9b15f0f3c3c (diff) | |
download | cpython-eb62127842a04817a6fc3bedba4e7478e561279d.zip cpython-eb62127842a04817a6fc3bedba4e7478e561279d.tar.gz cpython-eb62127842a04817a6fc3bedba4e7478e561279d.tar.bz2 |
refactor unpack, add unpack_from
Diffstat (limited to 'Lib')
-rw-r--r-- | Lib/struct.py | 12 | ||||
-rw-r--r-- | Lib/test/test_struct.py | 41 |
2 files changed, 53 insertions, 0 deletions
diff --git a/Lib/struct.py b/Lib/struct.py index ee5ddc2..648e39c 100644 --- a/Lib/struct.py +++ b/Lib/struct.py @@ -73,3 +73,15 @@ def unpack(fmt, s): except KeyError: o = _compile(fmt) return o.unpack(s) + +def unpack_from(fmt, buf, offset=0): + """ + Unpack the buffer, containing packed C structure data, according to + fmt starting at offset. Requires len(buffer[offset:]) >= calcsize(fmt). + See struct.__doc__ for more on format strings. + """ + try: + o = _cache[fmt] + except KeyError: + o = _compile(fmt) + return o.unpack_from(buf, offset)
\ No newline at end of file diff --git a/Lib/test/test_struct.py b/Lib/test/test_struct.py index 9332466..40fbde1 100644 --- a/Lib/test/test_struct.py +++ b/Lib/test/test_struct.py @@ -437,3 +437,44 @@ def test_705836(): TestFailed("expected OverflowError") test_705836() + +def test_unpack_from(): + test_string = 'abcd01234' + fmt = '4s' + s = struct.Struct(fmt) + for cls in (str, buffer): + data = cls(test_string) + assert s.unpack_from(data) == ('abcd',) + assert s.unpack_from(data, 2) == ('cd01',) + assert s.unpack_from(data, 4) == ('0123',) + for i in xrange(6): + assert s.unpack_from(data, i) == (data[i:i+4],) + for i in xrange(6, len(test_string) + 1): + simple_err(s.unpack_from, data, i) + for cls in (str, buffer): + data = cls(test_string) + assert struct.unpack_from(fmt, data) == ('abcd',) + assert struct.unpack_from(fmt, data, 2) == ('cd01',) + assert struct.unpack_from(fmt, data, 4) == ('0123',) + for i in xrange(6): + assert struct.unpack_from(fmt, data, i) == (data[i:i+4],) + for i in xrange(6, len(test_string) + 1): + simple_err(struct.unpack_from, fmt, data, i) + +test_unpack_from() + +def test_1229380(): + for endian in ('', '>', '<'): + for cls in (int, long): + for fmt in ('B', 'H', 'I', 'L'): + any_err(struct.pack, endian + fmt, cls(-1)) + + any_err(struct.pack, endian + 'B', cls(300)) + any_err(struct.pack, endian + 'H', cls(70000)) + + any_err(struct.pack, endian + 'I', sys.maxint * 4L) + any_err(struct.pack, endian + 'L', sys.maxint * 4L) + +if 0: + # TODO: bug #1229380 + test_1229380() |