From 98cff5320a993dffa0dbc9950b6c9fd4bd9dc802 Mon Sep 17 00:00:00 2001 From: Lucy Phipps Date: Sun, 24 Jun 2018 18:00:22 +0100 Subject: [PATCH] unpack_from is faster than unpack of slice --- src/PIL/BlpImagePlugin.py | 16 ++++++++-------- src/PIL/Jpeg2KImagePlugin.py | 8 ++++---- src/PIL/MspImagePlugin.py | 2 +- src/PIL/_binary.py | 14 +++++++------- 4 files changed, 20 insertions(+), 20 deletions(-) diff --git a/src/PIL/BlpImagePlugin.py b/src/PIL/BlpImagePlugin.py index ec358db3b..9b1a99ae1 100644 --- a/src/PIL/BlpImagePlugin.py +++ b/src/PIL/BlpImagePlugin.py @@ -65,7 +65,7 @@ def decode_dxt1(data, alpha=False): for block in range(blocks): # Decode next 8-byte block. idx = block * 8 - color0, color1, bits = struct.unpack("HHIIIIIIIIH', siz[:38]) + = struct.unpack_from('>HHIIIIIIIIH', siz) ssiz = [None]*csiz xrsiz = [None]*csiz yrsiz = [None]*csiz for i in range(csiz): ssiz[i], xrsiz[i], yrsiz[i] \ - = struct.unpack('>BBB', siz[36 + 3 * i:39 + 3 * i]) + = struct.unpack_from('>BBB', siz, 36 + 3 * i) size = (xsiz - xosiz, ysiz - yosiz) if csiz == 1: @@ -114,9 +114,9 @@ def _parse_jp2_header(fp): mode = 'RGBA' break elif tbox == b'colr': - meth, prec, approx = struct.unpack('>BBB', content[:3]) + meth, prec, approx = struct.unpack_from('>BBB', content) if meth == 1: - cs = struct.unpack('>I', content[3:7])[0] + cs = struct.unpack_from('>I', content, 3)[0] if cs == 16: # sRGB if nc == 1 and (bpc & 0x7f) > 8: mode = 'I;16' diff --git a/src/PIL/MspImagePlugin.py b/src/PIL/MspImagePlugin.py index 5ea3c1c49..9692d1162 100644 --- a/src/PIL/MspImagePlugin.py +++ b/src/PIL/MspImagePlugin.py @@ -133,7 +133,7 @@ class MspDecoder(ImageFile.PyDecoder): runtype = i8(row[idx]) idx += 1 if runtype == 0: - (runcount, runval) = struct.unpack("Bc", row[idx:idx+2]) + (runcount, runval) = struct.unpack_from("Bc", row, idx) img.write(runval * runcount) idx += 2 else: diff --git a/src/PIL/_binary.py b/src/PIL/_binary.py index 7e0d560b5..767c13b9d 100644 --- a/src/PIL/_binary.py +++ b/src/PIL/_binary.py @@ -11,7 +11,7 @@ # See the README file for information on usage and redistribution. # -from struct import unpack, pack +from struct import unpack_from, pack from ._util import py3 if py3: @@ -36,7 +36,7 @@ def i16le(c, o=0): c: string containing bytes to convert o: offset of bytes to convert in string """ - return unpack("H", c[o:o+2])[0] + return unpack_from(">H", c, o)[0] def i32be(c, o=0): - return unpack(">I", c[o:o+4])[0] + return unpack_from(">I", c, o)[0] # Output, le = little endian, be = big endian